@zipbul/gildash 0.27.1 → 0.29.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 +89 -20
- package/dist/index.js +9 -9
- package/dist/src/gildash/context.d.ts +1 -1
- package/dist/src/gildash/index.d.ts +22 -1
- package/dist/src/gildash/semantic-api.d.ts +5 -1
- package/dist/src/index.d.ts +4 -2
- package/dist/src/parser/ast-utils.d.ts +64 -0
- package/dist/src/parser/index.d.ts +2 -1
- package/dist/src/semantic/ast-node-utils.d.ts +4 -3
- package/dist/src/semantic/index.d.ts +2 -1
- package/dist/src/semantic/reference-classifier.d.ts +59 -0
- package/dist/src/semantic/reference-resolver.d.ts +7 -1
- package/dist/src/semantic/types.d.ts +25 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -337,6 +337,7 @@ Requires `semantic: true` at open time.
|
|
|
337
337
|
|--------|---------|-------------|
|
|
338
338
|
| `getResolvedType(name, filePath)` | `ResolvedType \| null` | Resolved type via tsc TypeChecker |
|
|
339
339
|
| `getSemanticReferences(name, filePath)` | `SemanticReference[]` | All references to a symbol |
|
|
340
|
+
| `getEnrichedReferences(name, filePath)` | `EnrichedReference[]` | References enriched with `writeKind` / `isAmbient` / `enclosingScope` (dataflow) |
|
|
340
341
|
| `getImplementations(name, filePath)` | `Implementation[]` | Interface / abstract class implementations |
|
|
341
342
|
| `getSemanticModuleInterface(filePath)` | `SemanticModuleInterface` | Module exports with resolved types |
|
|
342
343
|
| `isTypeAssignableTo(opts)` | `boolean` | Whether one symbol's type is assignable to another's |
|
|
@@ -351,6 +352,7 @@ Requires `semantic: true` at open time.
|
|
|
351
352
|
| `getResolvedTypeAtPosition(filePath, position)` | `ResolvedType \| null` | Resolved type at a byte position |
|
|
352
353
|
| `getResolvedTypesAtPositions(filePath, positions)` | `Map<number, ResolvedType>` | Batch type lookup across positions |
|
|
353
354
|
| `getSemanticReferencesAtPosition(filePath, position)` | `SemanticReference[]` | References to the symbol at a position |
|
|
355
|
+
| `getEnrichedReferencesAtPosition(filePath, position)` | `EnrichedReference[]` | Enriched references to the symbol at a position |
|
|
354
356
|
| `getImplementationsAtPosition(filePath, position)` | `Implementation[]` | Implementations of the symbol at a position |
|
|
355
357
|
| `isTypeAssignableToAtPosition(opts)` | `boolean` | Assignability check between two byte positions |
|
|
356
358
|
| `isTypeAssignableToTypeAtPositions(opts)` | `boolean` | Assignability check from a position to an arbitrary type string |
|
|
@@ -427,39 +429,106 @@ Re-exported from `oxc-walker` and `oxc-parser`:
|
|
|
427
429
|
|
|
428
430
|
#### Type predicates over `Node`
|
|
429
431
|
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|-----------|---------------|-------|
|
|
434
|
-
| `isArrowFunctionExpression` | `ArrowFunctionExpression` | |
|
|
435
|
-
| `isAssignmentExpression` | `AssignmentExpression` | |
|
|
436
|
-
| `isCallExpression` | `CallExpression` | |
|
|
437
|
-
| `isFunctionDeclaration` | `FunctionDeclaration` | Narrows to the `Function` interface, which structurally also accepts `TSDeclareFunction` and `TSEmptyBodyFunctionExpression` literals — those return `false` at runtime. |
|
|
438
|
-
| `isFunctionExpression` | `FunctionExpression` | Same `Function`-interface caveat as above. |
|
|
439
|
-
| `isFunctionNode` | `FunctionDeclaration` \| `FunctionExpression` \| `ArrowFunctionExpression` | Union shorthand for "any function-shape node". |
|
|
440
|
-
| `isIdentifier` | `Identifier` | 6-way collision: `IdentifierName`, `IdentifierReference`, `BindingIdentifier`, `LabelIdentifier`, `TSThisParameter`, `TSIndexSignatureName`. All expose `.name`. |
|
|
441
|
-
| `isMemberExpression` | `MemberExpression` | 3-way collision: `ComputedMemberExpression`, `StaticMemberExpression`, `PrivateFieldExpression`. All expose `.object`. |
|
|
442
|
-
| `isTSQualifiedName` | `TSQualifiedName` | 2-way collision: `TSQualifiedName`, `TSImportTypeQualifiedName`. Both expose `.left` / `.right` (different shapes). |
|
|
443
|
-
| `isVariableDeclaration` | `VariableDeclaration` | |
|
|
432
|
+
##### `is` namespace — primary surface
|
|
433
|
+
|
|
434
|
+
`is.X(node)` returns `true` when `node.type === 'X'` and narrows the type to `Node & { type: 'X' }`. Covers every `Node['type']` discriminator that `oxc-parser` exposes — and any future discriminator the upstream union adds — without per-type hand-written code.
|
|
444
435
|
|
|
445
436
|
```ts
|
|
446
|
-
import { parseSource, walk,
|
|
437
|
+
import { parseSource, walk, is } from '@zipbul/gildash';
|
|
447
438
|
|
|
448
|
-
const parsed = parseSource('a.ts', 'foo()');
|
|
439
|
+
const parsed = parseSource('a.ts', 'class A {}; foo();');
|
|
449
440
|
if (!('stack' in parsed)) {
|
|
450
441
|
walk(parsed.program, {
|
|
451
442
|
enter(node) {
|
|
452
|
-
if (
|
|
453
|
-
|
|
454
|
-
|
|
443
|
+
if (is.CallExpression(node)) console.log(node.arguments);
|
|
444
|
+
if (is.ClassDeclaration(node)) console.log(node.id?.name);
|
|
445
|
+
if (is.ImportDeclaration(node)) console.log(node.source.value);
|
|
455
446
|
},
|
|
456
447
|
});
|
|
457
448
|
}
|
|
458
449
|
```
|
|
459
450
|
|
|
451
|
+
Predicate functions are cached by discriminator, so `is.CallExpression === is.CallExpression` holds across calls — safe to pass directly to `Array#filter`. Only PascalCase property names mint predicates; symbols, lowercase typos (`is.callExpression`), and Object-prototype names (`then`, `toString`, `toJSON`, `valueOf`, `constructor`, `hasOwnProperty`) fall through so `String(is)`, `JSON.stringify(is)`, and `await Promise.resolve(is)` behave like a plain object. Calling a predicate with `null` / `undefined` returns `false`.
|
|
452
|
+
|
|
453
|
+
`Node & { type: K }` is used at the type level (rather than `Extract<Node, { type: K }>`) so that fields on backing interfaces with multi-literal `type` unions — `Function` (4-way), `Class` (2-way) — remain accessible inside the narrowed branch.
|
|
454
|
+
|
|
455
|
+
##### Hand-written predicates — kept for documented runtime semantics
|
|
456
|
+
|
|
457
|
+
These remain exported alongside `is.X` because their JSDoc encodes runtime semantics that the bare discriminator does not. Use them when the caveat matters at the call site; otherwise prefer `is.X`.
|
|
458
|
+
|
|
459
|
+
| Predicate | Why hand-written |
|
|
460
|
+
|-----------|------------------|
|
|
461
|
+
| `isFunctionDeclaration` / `isFunctionExpression` | `Function` interface caveat — `TSDeclareFunction` / `TSEmptyBodyFunctionExpression` structurally satisfy the interface but are excluded by the runtime discriminator check. |
|
|
462
|
+
| `isIdentifier` | 6-way collision: `IdentifierName`, `IdentifierReference`, `BindingIdentifier`, `LabelIdentifier`, `TSThisParameter`, `TSIndexSignatureName`. All expose `.name`. |
|
|
463
|
+
| `isMemberExpression` | 3-way collision: `ComputedMemberExpression`, `StaticMemberExpression`, `PrivateFieldExpression`. All expose `.object`. |
|
|
464
|
+
| `isTSQualifiedName` | 2-way collision: `TSQualifiedName`, `TSImportTypeQualifiedName`. Both expose `.left` / `.right` (different shapes). |
|
|
465
|
+
| `isFunctionNode` | Union shorthand for `FunctionDeclaration \| FunctionExpression \| ArrowFunctionExpression`. The only published predicate that narrows to a *union* of multiple discriminators — no `is.X` equivalent. |
|
|
466
|
+
|
|
467
|
+
`isArrowFunctionExpression`, `isAssignmentExpression`, `isCallExpression`, `isVariableDeclaration` are also exported for backward compatibility; pointwise-equivalent to `is.X`.
|
|
468
|
+
|
|
469
|
+
##### Migration from named predicates
|
|
470
|
+
|
|
471
|
+
| Named import | `is`-namespace equivalent |
|
|
472
|
+
|--------------|---------------------------|
|
|
473
|
+
| `isArrowFunctionExpression(n)` | `is.ArrowFunctionExpression(n)` |
|
|
474
|
+
| `isAssignmentExpression(n)` | `is.AssignmentExpression(n)` |
|
|
475
|
+
| `isCallExpression(n)` | `is.CallExpression(n)` |
|
|
476
|
+
| `isFunctionDeclaration(n)` | `is.FunctionDeclaration(n)` |
|
|
477
|
+
| `isFunctionExpression(n)` | `is.FunctionExpression(n)` |
|
|
478
|
+
| `isIdentifier(n)` | `is.Identifier(n)` |
|
|
479
|
+
| `isMemberExpression(n)` | `is.MemberExpression(n)` |
|
|
480
|
+
| `isTSQualifiedName(n)` | `is.TSQualifiedName(n)` |
|
|
481
|
+
| `isVariableDeclaration(n)` | `is.VariableDeclaration(n)` |
|
|
482
|
+
| `isFunctionNode(n)` | *(no `is.X` equivalent — keep the named import)* |
|
|
483
|
+
|
|
484
|
+
##### Composing the `is` namespace with the index layer
|
|
485
|
+
|
|
486
|
+
`Gildash.searchSymbols` (semantic / indexed view) and `parseSource` + `walk` (raw / positional view) are designed as two layers that compose. Use `searchSymbols` to locate the symbol, then re-enter the raw AST for the same file to drill into sub-expressions and slice source by `node.start` / `node.end`:
|
|
487
|
+
|
|
488
|
+
```ts
|
|
489
|
+
import { Gildash, parseSource, walk, is } from '@zipbul/gildash';
|
|
490
|
+
|
|
491
|
+
const ledger = await Gildash.open({ projectRoot });
|
|
492
|
+
|
|
493
|
+
// 1. Index layer: locate the symbol
|
|
494
|
+
const [sym] = ledger.searchSymbols({ text: 'target', exact: true, kind: 'function' });
|
|
495
|
+
if (!sym) return;
|
|
496
|
+
|
|
497
|
+
// 2. Raw layer: re-parse the file (gildash also caches it via `getParsedAst`)
|
|
498
|
+
const src = await Bun.file(sym.filePath).text();
|
|
499
|
+
const parsed = parseSource(sym.filePath, src);
|
|
500
|
+
if ('stack' in parsed) throw parsed;
|
|
501
|
+
|
|
502
|
+
// 3. Compose: outer-node walk + name match → drill into the matched subtree
|
|
503
|
+
walk(parsed.program, {
|
|
504
|
+
enter(node) {
|
|
505
|
+
if (is.FunctionDeclaration(node) && node.id?.name === sym.name) {
|
|
506
|
+
// Inside the symbol's subtree — use `is.X` predicates and raw byte
|
|
507
|
+
// offsets directly. `src.slice(n.start, n.end)` recovers source text.
|
|
508
|
+
if (node.body) {
|
|
509
|
+
walk(node.body, {
|
|
510
|
+
enter(inner) {
|
|
511
|
+
if (is.CallExpression(inner)) {
|
|
512
|
+
const calleeText = src.slice(inner.callee.start, inner.callee.end);
|
|
513
|
+
const argSpans = inner.arguments.map((a) => [a.start, a.end] as const);
|
|
514
|
+
// ...transform / collect / inject
|
|
515
|
+
void calleeText;
|
|
516
|
+
void argSpans;
|
|
517
|
+
}
|
|
518
|
+
},
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
this.skip();
|
|
522
|
+
}
|
|
523
|
+
},
|
|
524
|
+
});
|
|
525
|
+
```
|
|
526
|
+
|
|
527
|
+
This pattern keeps the two layers cleanly separated: the indexed view answers *which* symbols and *where* (`sym.filePath`, `sym.span`); the raw view answers *what shape* and *what byte range* (`is.X(node)`, `node.start` / `node.end`).
|
|
528
|
+
|
|
460
529
|
#### AST utility types
|
|
461
530
|
|
|
462
|
-
`Program`, `Node`, `VisitorObject`, `WalkOptions`, `WalkerEnter`, `WalkerLeave`, `WalkerCallbackContext`, `ScopeTrackerNode`, `ScopeTrackerOptions`, `SourcePosition`, `SourceSpan`, `ParsedFile`, plus `buildLineOffsets` / `getLineColumn` for byte ↔ line/column conversion.
|
|
531
|
+
`Program`, `Node`, `VisitorObject`, `WalkOptions`, `WalkerEnter`, `WalkerLeave`, `WalkerCallbackContext`, `ScopeTrackerNode`, `ScopeTrackerOptions`, `SourcePosition`, `SourceSpan`, `ParsedFile`, `IsNamespace`, `NodeTypePredicate`, plus `buildLineOffsets` / `getLineColumn` for byte ↔ line/column conversion.
|
|
463
532
|
|
|
464
533
|
<br>
|
|
465
534
|
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var T$=Object.defineProperty;var j$=(_)=>_;function g$(_,$){this[_]=j$.bind(null,$)}var k$=(_,$)=>{for(var J in $)T$(_,J,{get:$[J],enumerable:!0,configurable:!0,set:g$.bind($,J)})};var x0=import.meta.require;import{isErr as p_}from"@zipbul/result";import v_ from"path";import{existsSync as M6}from"fs";import{err as h0,isErr as f$}from"@zipbul/result";import{Database as y$}from"bun:sqlite";import{mkdirSync as x$,unlinkSync as m0,existsSync as n0}from"fs";import{dirname as h$,join as d0}from"path";import{drizzle as m$}from"drizzle-orm/bun-sqlite";import{migrate as n$}from"drizzle-orm/bun-sqlite/migrator";class O extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var I_=".gildash",l_="gildash.db";var U0={};k$(U0,{watcherOwner:()=>P$,symbols:()=>f,symbolChangelog:()=>t,relations:()=>k,files:()=>s,annotations:()=>z_});import{sql as E$}from"drizzle-orm";import{sqliteTable as F_,text as b,integer as a,real as u$,index as $_,primaryKey as v$,foreignKey as X0,check as b$}from"drizzle-orm/sqlite-core";var s=F_("files",{project:b("project").notNull(),filePath:b("file_path").notNull(),mtimeMs:u$("mtime_ms").notNull(),size:a("size").notNull(),contentHash:b("content_hash").notNull(),updatedAt:b("updated_at").notNull(),lineCount:a("line_count")},(_)=>[v$({columns:[_.project,_.filePath]})]),f=F_("symbols",{id:a("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),kind:b("kind").notNull(),name:b("name").notNull(),startLine:a("start_line").notNull(),startColumn:a("start_column").notNull(),endLine:a("end_line").notNull(),endColumn:a("end_column").notNull(),isExported:a("is_exported").notNull().default(0),signature:b("signature"),fingerprint:b("fingerprint"),detailJson:b("detail_json"),contentHash:b("content_hash").notNull(),indexedAt:b("indexed_at").notNull(),resolvedType:b("resolved_type"),structuralFingerprint:b("structural_fingerprint")},(_)=>[$_("idx_symbols_project_file").on(_.project,_.filePath),$_("idx_symbols_project_kind").on(_.project,_.kind),$_("idx_symbols_project_name").on(_.project,_.name),$_("idx_symbols_fingerprint").on(_.project,_.fingerprint),X0({columns:[_.project,_.filePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),k=F_("relations",{id:a("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),type:b("type").notNull(),srcFilePath:b("src_file_path").notNull(),srcSymbolName:b("src_symbol_name"),dstProject:b("dst_project"),dstFilePath:b("dst_file_path"),dstSymbolName:b("dst_symbol_name"),metaJson:b("meta_json"),specifier:b("specifier"),isExternal:a("is_external").notNull().default(0)},(_)=>[$_("idx_relations_src").on(_.project,_.srcFilePath),$_("idx_relations_dst").on(_.dstProject,_.dstFilePath),$_("idx_relations_type").on(_.project,_.type),$_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),$_("idx_relations_specifier").on(_.project,_.specifier),X0({columns:[_.project,_.srcFilePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),z_=F_("annotations",{id:a("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),tag:b("tag").notNull(),value:b("value").notNull().default(""),source:b("source").notNull(),symbolName:b("symbol_name"),startLine:a("start_line").notNull(),startColumn:a("start_column").notNull(),endLine:a("end_line").notNull(),endColumn:a("end_column").notNull(),indexedAt:b("indexed_at").notNull()},(_)=>[$_("idx_annotations_project_file").on(_.project,_.filePath),$_("idx_annotations_project_tag").on(_.project,_.tag),$_("idx_annotations_project_symbol").on(_.project,_.symbolName),X0({columns:[_.project,_.filePath],foreignColumns:[s.project,s.filePath]}).onDelete("cascade")]),t=F_("symbol_changelog",{id:a("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),changeType:b("change_type").notNull(),symbolName:b("symbol_name").notNull(),symbolKind:b("symbol_kind").notNull(),filePath:b("file_path").notNull(),oldName:b("old_name"),oldFilePath:b("old_file_path"),fingerprint:b("fingerprint"),changedAt:b("changed_at").notNull(),isFullIndex:a("is_full_index").notNull().default(0),indexRunId:b("index_run_id").notNull()},(_)=>[$_("idx_changelog_project_changed_at").on(_.project,_.changedAt),$_("idx_changelog_project_name").on(_.project,_.symbolName),$_("idx_changelog_project_run").on(_.project,_.indexRunId)]),P$=F_("watcher_owner",{id:a("id").primaryKey(),pid:a("pid").notNull(),startedAt:b("started_at").notNull(),heartbeatAt:b("heartbeat_at").notNull(),instanceId:b("instance_id")},(_)=>[b$("watcher_owner_singleton",E$`${_.id} = 1`)]);class V0{client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=d0(_.projectRoot,I_,l_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{x$(h$(this.dbPath),{recursive:!0}),this.client=new y$(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=m$(this.client,{schema:U0}),n$(this.drizzle,{migrationsFolder:d0(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(_)&&n0(this.dbPath)){this.closeClient(),m0(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(n0(Q))m0(Q)}let $=this.open();if(f$($))return h0(new O("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return h0(new O("store",`Failed to open database at ${this.dbPath}`,{cause:_}))}}close(){this.closeClient(),this.drizzle=null}transaction(_){let $=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return $.transaction(()=>_(this))()}finally{this.txDepth--}}let J=`sp_${this.txDepth++}`;$.run(`SAVEPOINT "${J}"`);try{let Q=_(this);return $.run(`RELEASE SAVEPOINT "${J}"`),Q}catch(Q){throw $.run(`ROLLBACK TO SAVEPOINT "${J}"`),$.run(`RELEASE SAVEPOINT "${J}"`),Q}finally{this.txDepth--}}immediateTransaction(_){let $=this.requireClient();this.txDepth++,$.run("BEGIN IMMEDIATE");try{let J=_();return $.run("COMMIT"),J}catch(J){throw $.run("ROLLBACK"),J}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(($)=>$.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}replaceOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}touchOwner(_){let $=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run($,_)}deleteOwner(_){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(_)}registerRegexpUdf(_){let $=_;if(typeof $.function!=="function")return;$.function.call(_,"regexp",(J,Q)=>{try{return new RegExp(J).test(Q)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(_){if(!(_ instanceof Error))return!1;let $=_.message.toLowerCase();return $.includes("malformed")||$.includes("corrupt")||$.includes("not a database")||$.includes("disk i/o error")||$.includes("sqlite_corrupt")}}import{eq as b_,and as p0}from"drizzle-orm";class O0{db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(s).where(p0(b_(s.project,_),b_(s.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(s).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[s.project,s.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(s).where(b_(s.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(s).where(p0(b_(s.project,_),b_(s.filePath,$))).run()}}import{eq as r,and as A_,sql as c_,count as d$}from"drizzle-orm";function T_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var i0=50;class H0{db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(f).where(A_(r(f.project,_),r(f.filePath,$))).run(),!Q.length)return;let W=new Date().toISOString(),z=Q.map((Y)=>({project:_,filePath:$,kind:Y.kind??"unknown",name:Y.name??"",startLine:Y.startLine??0,startColumn:Y.startColumn??0,endLine:Y.endLine??0,endColumn:Y.endColumn??0,isExported:Y.isExported??0,signature:Y.signature??null,fingerprint:Y.fingerprint??null,detailJson:Y.detailJson??null,contentHash:J,indexedAt:Y.indexedAt??W,resolvedType:Y.resolvedType??null,structuralFingerprint:Y.structuralFingerprint??null}));for(let Y=0;Y<z.length;Y+=i0)this.db.drizzleDb.insert(f).values(z.slice(Y,Y+i0)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(f).where(A_(r(f.project,_),r(f.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,W=T_($);if(!W)return[];return this.db.drizzleDb.select().from(f).where(A_(c_`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${W})`,r(f.project,_),J.kind?r(f.kind,J.kind):void 0)).orderBy(f.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(f).where(A_(r(f.project,_),r(f.kind,$))).orderBy(f.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:d$(),fileCount:c_`COUNT(DISTINCT ${f.filePath})`}).from(f).where(r(f.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(f).where(A_(r(f.project,_),r(f.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(f).where(A_(r(f.project,_),r(f.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(f).where(A_(_.ftsQuery?c_`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?r(f.name,_.exactName):void 0,_.project!==void 0?r(f.project,_.project):void 0,_.kind?r(f.kind,_.kind):void 0,_.filePath!==void 0?r(f.filePath,_.filePath):void 0,_.isExported!==void 0?r(f.isExported,_.isExported?1:0):void 0,_.decorator?c_`${f.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?r(f.resolvedType,_.resolvedType):void 0)).orderBy(f.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new O("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((z)=>J.test(z.name));let Q=[];for(let W of[5,20,100]){let z=_.limit*W,Y=$.limit(z).all();if(Q=Y.filter((Z)=>J.test(Z.name)),Q.length>=_.limit||Y.length<z)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as h,and as H_,isNull as l0,or as p$}from"drizzle-orm";var P_={project:k.project,type:k.type,srcFilePath:k.srcFilePath,srcSymbolName:k.srcSymbolName,dstProject:k.dstProject,dstFilePath:k.dstFilePath,dstSymbolName:k.dstSymbolName,metaJson:k.metaJson,specifier:k.specifier,isExternal:k.isExternal};class M0{db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(k).where(H_(h(k.project,_),h(k.srcFilePath,$))).run(),!J.length)return;for(let W of J)Q.drizzleDb.insert(k).values({project:_,type:W.type??"unknown",srcFilePath:W.srcFilePath??$,srcSymbolName:W.srcSymbolName??null,dstProject:W.dstProject??(W.dstFilePath!=null?_:null),dstFilePath:W.dstFilePath??null,dstSymbolName:W.dstSymbolName??null,metaJson:W.metaJson??null,specifier:W.specifier??null,isExternal:W.isExternal??0}).run()})}getOutgoing(_,$,J){if(J!==void 0)return this.db.drizzleDb.select(P_).from(k).where(H_(h(k.project,_),h(k.srcFilePath,$),p$(h(k.srcSymbolName,J),l0(k.srcSymbolName)))).all();return this.db.drizzleDb.select(P_).from(k).where(H_(h(k.project,_),h(k.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(P_).from(k).where(H_(h(k.dstProject,$),h(k.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(P_).from(k).where(H_(h(k.project,_),h(k.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(k).where(H_(h(k.project,_),h(k.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(k).where(H_(h(k.dstProject,_),h(k.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(P_).from(k).where(H_(_.project!==void 0?h(k.project,_.project):void 0,_.srcFilePath!==void 0?h(k.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?h(k.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?h(k.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?h(k.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?h(k.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?h(k.type,_.type):void 0,_.specifier!==void 0?h(k.specifier,_.specifier):void 0,_.isExternal!==void 0?h(k.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:W,newSymbol:z,newDstProject:Y}=_,Z=Q===null?H_(h(k.dstProject,$),h(k.dstFilePath,J),l0(k.dstSymbolName)):H_(h(k.dstProject,$),h(k.dstFilePath,J),h(k.dstSymbolName,Q)),X={dstFilePath:W,dstSymbolName:z};if(Y!==void 0)X.dstProject=Y;this.db.drizzleDb.update(k).set(X).where(Z).run()}}import{err as a0}from"@zipbul/result";import{subscribe as i$}from"@parcel/watcher";import K0 from"path";import c0 from"path";function J_(_){return _.replaceAll("\\","/")}function f_(_,$){return J_(c0.relative(_,$))}function j_(_,$){return J_(c0.resolve(_,$))}var l$=["**/.git/**",`**/${I_}/**`,"**/dist/**","**/node_modules/**"],c$=new Set(["package.json","tsconfig.json"]);function a$(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class B0{#_;#$;#J;#Z;#W;#z;constructor(_,$=i$,J=console){this.#$=_.projectRoot,this.#J=[...l$,..._.ignorePatterns??[]],this.#Z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#W=$,this.#z=J}async start(_){try{this.#_=await this.#W(this.#$,($,J)=>{if($){this.#z.error(new O("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let W=J_(K0.relative(this.#$,Q.path));if(W.startsWith(".."))continue;let z=K0.basename(W),Y=K0.extname(W).toLowerCase();if(!c$.has(z)&&!this.#Z.has(Y))continue;if(W.endsWith(".d.ts"))continue;_({eventType:a$(Q.type),filePath:W})}}catch(Q){this.#z.error(new O("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return a0(new O("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return a0(new O("watcher","Failed to close watcher",{cause:_}))}}}import L0 from"path";var s$=["**/node_modules/**","**/.git/**",`**/${I_}/**`,"**/dist/**"],r$=s$.map((_)=>new Bun.Glob(_));function o$(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function a_(_,$=o$){let J=[];for await(let Q of $(_)){let W=J_(Q);if(r$.some((K)=>K.match(W)))continue;let z=J_(L0.dirname(Q)),Y=L0.join(_,Q),Z=await Bun.file(Y).json(),X=typeof Z?.name==="string"&&Z.name.length>0?Z.name:L0.basename(z==="."?_:z);J.push({dir:z,project:X})}return J.sort((Q,W)=>W.dir.length-Q.dir.length),J}function l(_,$,J="default"){let Q=J_(_);for(let W of $){if(W.dir===".")return W.project;if(Q===W.dir||Q.startsWith(`${W.dir}/`))return W.project}return J}import y_ from"path";var C_=new Map;async function t$(_){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 e$(_,$){if($.startsWith(".")){let J=y_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return y_.resolve(_,"node_modules",$)}async function s0(_,$=5){if($<=0)return null;let J=await t$(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let W=e$(y_.dirname(_),Q),z=await s0(W,$-1);if(!z)return J;let Y=typeof z.compilerOptions==="object"&&z.compilerOptions!==null?z.compilerOptions:{},Z=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...z,...J,compilerOptions:{...Y,...Z}}}async function x_(_){if(C_.has(_))return C_.get(_)??null;let $=y_.join(_,"tsconfig.json"),J=await s0($);if(!J)return C_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return C_.set(_,null),null;let W=typeof Q.baseUrl==="string"?Q.baseUrl:null,z=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!W&&!z)return C_.set(_,null),null;let Y=W?y_.resolve(_,W):_,Z=new Map;if(z)for(let[K,V]of Object.entries(z)){if(!Array.isArray(V))continue;let B=V.filter((C)=>typeof C==="string");Z.set(K,B)}let X={baseUrl:Y,paths:Z};return C_.set(_,X),X}function s_(_){if(_){C_.delete(_);return}C_.clear()}function V_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as z1}from"@zipbul/result";import{err as _J}from"@zipbul/result";import{parseSync as $J}from"oxc-parser";function g_(_,$,J,Q=$J){try{let W={preserveParens:!1,...J},z=Q(_,$,W);return{filePath:_,program:z.program,errors:z.errors,comments:z.comments,sourceText:$,module:z.module}}catch(W){return _J(new O("parse",`Failed to parse file: ${_}`,{cause:W}))}}import{join as JJ}from"path";function QJ(_,$){let J=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(J).scan({cwd:_,followSymlinks:!1})}async function r0(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:W,scanFilesFn:z=QJ}=_,Y=W.getFilesMap(),Z=new Set,X=[],K=[],V=Q.map((C)=>new Bun.Glob(C));for await(let C of z($,J)){let N=J_(C);if(!J.some((d)=>N.endsWith(d)))continue;if(N.startsWith("node_modules/")||N.includes("/node_modules/"))continue;if(V.some((d)=>d.match(N)))continue;Z.add(N);let w=JJ($,N),S=Bun.file(w),{size:T,lastModified:F}=S,u=Y.get(N);if(!u){let d=await S.text(),p=V_(d);X.push({filePath:N,contentHash:p,mtimeMs:F,size:T});continue}if(u.mtimeMs===F&&u.size===T){K.push({filePath:N,contentHash:u.contentHash,mtimeMs:F,size:T});continue}let E=await S.text(),y=V_(E);if(y===u.contentHash)K.push({filePath:N,contentHash:y,mtimeMs:F,size:T});else X.push({filePath:N,contentHash:y,mtimeMs:F,size:T})}let B=[];for(let C of Y.keys())if(!Z.has(C))B.push(C);return{changed:X,unchanged:K,deleted:B}}function h_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
|
|
3
|
-
`)$.push(J+1);return $}function U_(_,$){let J=0,Q=_.length-1;while(J<Q){let W=J+Q+1>>1;if(_[W]<=$)J=W;else Q=W-1}return{line:J+1,column:$-_[J]}}import{err as WJ}from"@zipbul/result";import{parse as zJ}from"comment-parser";function r_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=zJ(`/** ${$} */`)[0]??{description:"",tags:[]};return{description:(Q.description??"").trim(),tags:(Q.tags??[]).map((W)=>({tag:W.tag??"",name:W.name??"",type:W.type??"",description:W.description??"",optional:W.optional??!1,...W.default!==void 0?{default:W.default}:{}}))}}catch($){return WJ(new O("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as ZJ}from"@zipbul/result";function YJ(_){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 k_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...k_(J.argument));else $.push(...k_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...k_(J.argument));else $.push(...k_(J))}return $}if(_.type==="AssignmentPattern")return k_(_.left);return[]}function XJ(_){let $=new Map;for(let J of _.module.staticImports){let Q=J.moduleRequest.value;for(let W of J.entries){let z=W.localName.value,Y=W.importName.kind==="Name"?W.importName.name:void 0,Z={specifier:Q};if(Y&&Y!==z)Z.originalName=Y;$.set(z,Z)}}return $}function q_(_){let{program:$,sourceText:J,comments:Q}=_,W=h_(J),z=XJ(_),Y=Q.filter((I)=>I.type==="Block"&&I.value.startsWith("*")).sort((I,q)=>I.end-q.end),Z=$.body.map((I)=>I.start).sort((I,q)=>I-q);function X(I,q){return F(I,q)}function K(I,q,U){if(I.type==="PrivateIdentifier")return{kind:"private"};if(!q&&I.type==="Identifier")return;return X(I,U)}function V(I,q){if(q)return J.slice(I.start,I.end);if(I.type==="PrivateIdentifier")return`#${I.name}`;return YJ(I)}function B(I,q,U){let H=I;if(!q&&H.type==="Identifier")return{kind:"string",value:H.name};return X(I,U)}function C(I,q){return{start:U_(W,I),end:U_(W,q)}}function N(I){let q=0,U=Y.length-1,H=-1;while(q<=U){let L=q+U>>>1;if(Y[L].end<=I)H=L,q=L+1;else U=L-1}if(H<0)return;let M=Y[H];q=0,U=Z.length-1;while(q<=U){let L=q+U>>>1,A=Z[L];if(A<=M.end)q=L+1;else if(A>=I)U=L-1;else return}return`/*${M.value}*/`}function w(I){if(!I)return;let q="typeAnnotation"in I&&I.typeAnnotation?I.typeAnnotation:I;return J.slice(q.start,q.end)}let S=8;function T(I){if(I.type==="Identifier")return z.get(I.name);if(I.type==="MemberExpression"){let q=I.object;if(q.type==="Identifier")return z.get(q.name)}return}function F(I,q=0){let U=I;if(q>=S)return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)};let H=U.type;if(H==="Literal"){let M=U.value;if(typeof M==="bigint")return{kind:"bigint",value:typeof U.bigint==="string"?U.bigint:M.toString()};if(typeof U.regex==="object"&&U.regex!==null)return{kind:"regex",value:J.slice(U.start,U.end)};if(M===null)return{kind:"null",value:null};if(typeof M==="string")return{kind:"string",value:M};if(typeof M==="number")return{kind:"number",value:M};if(typeof M==="boolean")return{kind:"boolean",value:M};return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}if(H==="Identifier"){let M=U.name;if(M==="undefined")return{kind:"undefined",value:null};let L=z.get(M),A={kind:"identifier",name:M};if(L){if(A.importSource=L.specifier,L.originalName)A.originalName=L.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,v=J.slice(g.start,g.end),n=g.type==="Identifier"?g.name:void 0,__=n?z.get(n):void 0,X_={kind:"member",object:v,property:j.value};if(__)X_.importSource=__.specifier;return X_}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}let M=U.object,L=J.slice(M.start,M.end),A=U.property.name??J.slice(U.property.start,U.property.end),D=M.type==="Identifier"?M.name:void 0,G=D?z.get(D):void 0,R={kind:"member",object:L,property:A};if(G)R.importSource=G.specifier;return R}if(H==="CallExpression"){let M=U.callee,L=J.slice(M.start,M.end),D=(U.arguments??[]).map((j)=>F(j,q+1)),G=T(M),R={kind:"call",callee:L,arguments:D};if(G)R.importSource=G.specifier;return R}if(H==="NewExpression"){let M=U.callee,L=J.slice(M.start,M.end),D=(U.arguments??[]).map((j)=>F(j,q+1)),G=T(M),R={kind:"new",callee:L,arguments:D};if(G)R.importSource=G.specifier;return R}if(H==="ObjectExpression"){let M=U.properties??[],L=[];for(let A of M){if(A.type==="SpreadElement"){let n=A.argument;L.push({kind:"spread",argument:F(n,q+1)});continue}let D=A.key,G=A.computed===!0,R=A.value,j=A.shorthand||void 0,v={kind:"property",key:B(D,G,q+1),value:F(R,q+1)};if(j)v.shorthand=!0;L.push(v)}return{kind:"object",properties:L}}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 M=U.argument;return{kind:"spread",argument:F(M,q+1)}}if(H==="ArrowFunctionExpression"||H==="FunctionExpression"){let L=U.params.map(E),A={kind:"function",sourceText:J.slice(U.start,U.end)};if(L.length>0)A.parameters=L;return A}if(H==="TemplateLiteral"||H==="TaggedTemplateExpression")return{kind:"template",sourceText:J.slice(U.start,U.end)};if(H==="UnaryExpression"){let{operator:M,argument:L}=U;if(M==="-"&&L.type==="Literal"&&typeof L.value==="number")return{kind:"number",value:-L.value};if(M==="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 M=U.expression;if(M)return F(M,q)}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}function u(I){if(!I||I.length===0)return[];return I.map((q)=>{let U=q.expression;if(U.type==="CallExpression"){let H=U,M=H.callee,L="name"in M&&typeof M.name==="string"?M.name:("property"in M)&&M.property&&typeof M.property.name==="string"?M.property.name:"unknown",A=H.arguments.map((D)=>F(D));return{name:L,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(I){if(I.type==="TSParameterProperty"){let U=I;return d(U.parameter,U.decorators)}if(I.type==="RestElement"){let U=I,H=U.argument,L=`...${"name"in H&&typeof H.name==="string"?H.name:"unknown"}`,A=U.typeAnnotation,D=A?w(A):void 0,G={name:L,isOptional:!1};if(D)G.type=D;return G}let q=I;return d(q,q.decorators)}function y(I){if(!I)return;let q="typeAnnotation"in I&&I.typeAnnotation?I.typeAnnotation:null;if(!q)return;let H=q.typeName?.name;if(!H)return;return z.get(H)?.specifier}function d(I,q){if(I.type==="AssignmentPattern"){let{left:R,right:j}=I,g="name"in R&&typeof R.name==="string"?R.name:"unknown",v="typeAnnotation"in R?R.typeAnnotation:null,n=v?w(v):void 0,__=y(v),X_=J.slice(j.start,j.end),K_="decorators"in R&&Array.isArray(R.decorators)?R.decorators:[],Y0=u(K_),D_={name:g,isOptional:!0,defaultValue:X_};if(n)D_.type=n;if(__)D_.typeImportSource=__;if(Y0.length>0)D_.decorators=Y0;return D_}let U="name"in I&&typeof I.name==="string"?I.name:("pattern"in I)&&I.pattern&&typeof I.pattern.name==="string"?I.pattern.name:"unknown",H=!!(("optional"in I)&&I.optional),M="typeAnnotation"in I?I.typeAnnotation:null,L=M?w(M):void 0,A=y(M),D=u(q??[]),G={name:U,isOptional:H};if(L)G.type=L;if(A)G.typeImportSource=A;if(D.length>0)G.decorators=D;return G}function p(I,q){let U=[];if(q?.async)U.push("async");if(I.static)U.push("static");if(I.abstract)U.push("abstract");if(I.readonly)U.push("readonly");if(I.override)U.push("override");if(I.declare)U.push("declare");if(I.const)U.push("const");let H=I.accessibility;if(H==="private")U.push("private");else if(H==="protected")U.push("protected");else if(H==="public")U.push("public");return U}function Q_(I){if(!I)return;let q=I.params.flatMap((U)=>{let H=U.name.name;return H?[H]:[]});return q.length>0?q:void 0}function Z_(I){let q=[];if(I.superClass){let H=J.slice(I.superClass.start,I.superClass.end);q.push({kind:"extends",name:H})}let U=I.implements??[];for(let H of U){let M=H.expression,L=J.slice(M.start,M.end);q.push({kind:"implements",name:L})}return q}function O_(I){let q=[],U=I.extends;for(let H of U){let M=H.expression,L=J.slice(M.start,M.end);q.push({kind:"extends",name:L})}return q}function Y_(I){let q=[];for(let U of I)if(U.type==="MethodDefinition"||U.type==="TSAbstractMethodDefinition"){let H=U,M=V(H.key,H.computed),L=K(H.key,H.computed,0),A=H.value,D=H.kind,G=D==="constructor"?"constructor":D==="get"?"getter":D==="set"?"setter":"method",R=p(H,A);if(U.type==="TSAbstractMethodDefinition"&&!R.includes("abstract"))R.push("abstract");let j=A.params.map(E),g=w(A.returnType),v=u(H.decorators??[]),n={kind:"method",name:M,span:C(U.start,U.end),isExported:!1,methodKind:G,modifiers:R,parameters:j.length>0?j:void 0,returnType:g};if(L)n.key=L;if(v.length>0)n.decorators=v;q.push(n)}else if(U.type==="PropertyDefinition"||U.type==="TSAbstractPropertyDefinition"||U.type==="AccessorProperty"||U.type==="TSAbstractAccessorProperty"){let H=U,M=V(H.key,H.computed),L=K(H.key,H.computed,0),A=p(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 D=w(H.typeAnnotation),G=H.value,R=G?F(G):void 0,j=u(H.decorators??[]),g={kind:"property",name:M,span:C(U.start,U.end),isExported:!1,modifiers:A,returnType:D,initializer:R};if(L)g.key=L;if(j.length>0)g.decorators=j;q.push(g)}return q}function W_(I){let q=[];for(let U of I)if(U.type==="TSMethodSignature"){let H=U,M=V(H.key,H.computed),L=K(H.key,H.computed,0),A=H.params.map(E),D=w(H.returnType),G={kind:"method",name:M,span:C(U.start,U.end),isExported:!1,modifiers:[],methodKind:"method",parameters:A.length>0?A:void 0,returnType:D};if(L)G.key=L;q.push(G)}else if(U.type==="TSPropertySignature"){let H=U,M=V(H.key,H.computed),L=K(H.key,H.computed,0),A=w(H.typeAnnotation),D={kind:"property",name:M,span:C(U.start,U.end),isExported:!1,modifiers:H.readonly?["readonly"]:[],returnType:A};if(L)D.key=L;q.push(D)}return q}function i(I,q){let U=I.type;if(U==="FunctionDeclaration"||U==="FunctionExpression"||U==="TSDeclareFunction"||U==="TSEmptyBodyFunctionExpression"){let H=I,M=H.id?.name??"default",L=H.params.map(E),A=w(H.returnType),D=p(H,H),G=u(H.decorators??[]),R=Q_(H.typeParameters),j={kind:"function",name:M,span:C(I.start,I.end),isExported:q,modifiers:D,parameters:L.length>0?L:void 0,returnType:A,decorators:G.length>0?G:void 0};if(R&&R.length>0)j.typeParameters=R;return j}if(U==="ClassDeclaration"||U==="ClassExpression"){let H=I,M=H.id?.name??"default",L=Z_(H),A=Y_(H.body.body),D=u(H.decorators),G=p(H),R=Q_(H.typeParameters),j={kind:"class",name:M,span:C(I.start,I.end),isExported:q,modifiers:G,heritage:L.length>0?L:void 0,members:A.length>0?A:void 0,decorators:D.length>0?D:void 0};if(R&&R.length>0)j.typeParameters=R;return j}if(U==="VariableDeclaration"){let H=I,M=[];for(let L of H.declarations){let{id:A,init:D}=L;if(A.type==="ObjectPattern"||A.type==="ArrayPattern"){let X_=k_(A);for(let K_ of X_)M.push({kind:"variable",name:K_.name,span:C(K_.start,K_.end),isExported:q,modifiers:[]});continue}let G="name"in A&&typeof A.name==="string"?A.name:"unknown",R="variable",j,g,v;if(D)if(D.type==="FunctionExpression"||D.type==="ArrowFunctionExpression"){R="function";let X_=D;j=X_.params.map(E),g=w(X_.returnType)}else v=F(D);let n=[],__={kind:R,name:G,span:C(L.start,L.end),isExported:q,modifiers:n,parameters:j,returnType:g};if(v)__.initializer=v;M.push(__)}if(M.length===0)return null;if(M.length===1)return M[0];return M}if(U==="TSTypeAliasDeclaration")return{kind:"type",name:I.id.name,span:C(I.start,I.end),isExported:q,modifiers:[]};if(U==="TSInterfaceDeclaration"){let H=I,M=H.id.name,L=O_(H),A=W_(H.body.body),D=Q_(H.typeParameters),G={kind:"interface",name:M,span:C(I.start,I.end),isExported:q,modifiers:[],heritage:L.length>0?L:void 0,members:A.length>0?A:void 0};if(D&&D.length>0)G.typeParameters=D;return G}if(U==="TSEnumDeclaration"){let H=I,M=H.id.name,L=p(H),D=H.body.members.map((G)=>{let R=G.id,j=R.type!=="Identifier",g="name"in R&&typeof R.name==="string"?R.name:("value"in R)&&typeof R.value==="string"?R.value:"unknown",v=G.initializer?F(G.initializer):void 0,n={kind:"property",name:g,span:C(G.start,G.end),isExported:!1,modifiers:[]};if(j)n.key=X(R,0);if(v)n.initializer=v;return n});return{kind:"enum",name:M,span:C(I.start,I.end),isExported:q,modifiers:L,members:D.length>0?D:void 0}}if(U==="TSModuleDeclaration"){let H=I,M=H.id.name??H.id.value??"unknown",L=p(H),A=[];if(H.body?.type==="TSModuleBlock")for(let D of H.body.body??[]){if(D.type!=="ExportNamedDeclaration")continue;let G=D.declaration;if(!G)continue;let R=i(G,!1);if(R)if(Array.isArray(R))A.push(...R);else A.push(R)}return{kind:"namespace",name:M,span:C(I.start,I.end),isExported:q,modifiers:L,members:A.length>0?A:void 0}}return null}let c=[],w_=new Set;for(let I of $.body){let q=null,U=I;if(U.type==="ExportNamedDeclaration"){let M=U;if(M.declaration){if(q=i(M.declaration,!0),q&&!Array.isArray(q))q.span=C(M.start,M.end)}else if(!M.source&&M.specifiers)for(let L of M.specifiers){let A=L.local,D="name"in A?A.name:A.value;if(D)w_.add(D)}}else if(U.type==="ExportDefaultDeclaration"){let M=U,L=M.declaration;if(L){if(q=i(L,!0),q&&!Array.isArray(q))q.name="id"in L&&L.id&&typeof L.id.name==="string"?L.id.name:"default",q.isExported=!0,q.span=C(M.start,M.end);else if(!q&&"type"in L&&L.type==="Identifier"){let A=L.name;if(A)w_.add(A)}}}else{let M=U.type;if(M==="FunctionDeclaration"||M==="TSDeclareFunction"||M==="ClassDeclaration"||M==="VariableDeclaration"||M==="TSTypeAliasDeclaration"||M==="TSInterfaceDeclaration"||M==="TSEnumDeclaration"||M==="TSModuleDeclaration")q=i(U,!1)}let H=Array.isArray(q)?q:q?[q]:[];for(let M of H){let L=I.start,A=N(L);if(A){let D=r_(A);if(!ZJ(D))M.jsDoc=D}c.push(M)}}if(w_.size>0){for(let I of c)if(!I.isExported&&w_.has(I.name))I.isExported=!0}return c}function o_(_){if(_===null||typeof _!=="object")return JSON.stringify(_);if(Array.isArray(_))return`[${_.map(o_).join(",")}]`;let $=_;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${o_($[Q])}`).join(",")}}`}function UJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function VJ(_){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((z)=>z==="private"||z==="protected"||z==="public"),W={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)W.key=J.key;if(J.initializer)W.initializer=J.initializer;if(J.decorators?.length)W.decorators=J.decorators;return W});return Object.keys($).length>0?JSON.stringify($):null}function OJ(_){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,W)=>Q.name.localeCompare(W.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:${o_(_.key)}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}:${Q.key?o_(Q.key):""}`).sort().join(";");$.push(`mem:${_.members.length}:${V_(J)}`)}return V_($.join("|"))}function o0(_,$,J,Q,W){let z=UJ(_),Y=V_(`${$}|${_.kind}|${z??""}`),Z=OJ(_);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:z,fingerprint:Y,detailJson:VJ(_),contentHash:W,indexedAt:new Date().toISOString(),structuralFingerprint:Z}}function w0(_){let{parsed:$,project:J,filePath:Q,contentHash:W,symbolRepo:z}=_,Y=q_($),Z=[];for(let X of Y){Z.push(o0(X,X.name,J,Q,W));for(let K of X.members??[])Z.push(o0(K,`${X.name}.${K.name}`,J,Q,W))}z.replaceFileSymbols(J,Q,W,Z)}import{resolve as D0,dirname as HJ,extname as MJ}from"path";function N_(_,$,J){let Q=(W)=>{let z=MJ(W);if(z===".js")return[W.slice(0,-3)+".ts"];if(z===".mjs")return[W.slice(0,-4)+".mts"];if(z===".cjs")return[W.slice(0,-4)+".cts"];if(z===".ts"||z===".mts"||z===".cts"||z===".d.ts")return[W];return[W+".ts",W+".d.ts",W+"/index.ts",W+"/index.d.ts",W+".mts",W+"/index.mts",W+".cts",W+"/index.cts"]};if($.startsWith(".")){let W=J_(D0(HJ(_),$));return Q(W)}if(J)for(let[W,z]of J.paths){if(z.length===0)continue;let Y=W.indexOf("*");if(Y===-1){if($===W){let Z=[];for(let X of z)Z.push(...Q(J_(D0(J.baseUrl,X))));return Z}}else{let Z=W.slice(0,Y),X=W.slice(Y+1);if($.startsWith(Z)&&(X===""||$.endsWith(X))){let K=$.slice(Z.length,X===""?void 0:$.length-X.length),V=[];for(let B of z)V.push(...Q(J_(D0(J.baseUrl,B.replace("*",K)))));return V}}}return[]}function t0(_,$,J,Q=N_){let W=new Map,z=_.body??[];for(let Y of z){if(Y.type!=="ImportDeclaration")continue;let Z=Y.source?.value??"",X=Q($,Z,J);if(X.length===0)continue;let K=X[0],V=Y.specifiers??[];for(let B of V)switch(B.type){case"ImportSpecifier":W.set(B.local.name,{path:K,importedName:B.imported.name});break;case"ImportDefaultSpecifier":W.set(B.local.name,{path:K,importedName:"default"});break;case"ImportNamespaceSpecifier":W.set(B.local.name,{path:K,importedName:"*"});break}}return W}import{Visitor as KJ}from"oxc-parser";function t_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function BJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function R_(_,$,J,Q){let W=Q(_,$,J),z=W.length>0?W[0]:null,Y=z===null&&BJ($);return{resolved:z,isExternal:Y}}function LJ(_,$,J,Q,W){for(let z of _.staticImports){let Y=z.moduleRequest.value,{resolved:Z,isExternal:X}=R_($,Y,J,Q),K={dstFilePath:Z,specifier:Y};if(z.entries.length===0){let V={};if(X)V.isExternal=!0;if(Z===null&&!X)V.isUnresolved=!0;W.push({type:"imports",srcFilePath:$,srcSymbolName:null,...K,dstSymbolName:null,...Object.keys(V).length>0?{metaJson:JSON.stringify(V)}:{}});continue}for(let V of z.entries){let B=V.isType,C={};if(B)C.isType=!0;if(X)C.isExternal=!0;if(Z===null&&!X)C.isUnresolved=!0;let N,w,S=V.importName.kind;if(S==="Default")N="default",w=V.localName.value;else if(S==="NamespaceObject")N="*",w=V.localName.value,C.importKind="namespace";else N=V.importName.name??"unknown",w=V.localName.value;W.push({type:B?"type-references":"imports",srcFilePath:$,srcSymbolName:w,...K,dstSymbolName:N,...Object.keys(C).length>0?{metaJson:JSON.stringify(C)}:{}})}}}function wJ(_,$,J,Q,W){let z=new Map;for(let Y of _.staticImports)for(let Z of Y.entries)z.set(Z.localName.value,Y.moduleRequest.value);for(let Y of _.staticExports)for(let Z of Y.entries){let X=null;if(Z.moduleRequest)X=Z.moduleRequest.value;else if(Z.localName.name)X=z.get(Z.localName.name)??null;if(!X)continue;let{resolved:K,isExternal:V}=R_($,X,J,Q),B=Z.exportName.name??"default",C=Z.exportName.kind,N=Z.localName.name??Z.importName.name??B,w=Z.isType,S={isReExport:!0};if(C==="None");else S.specifiers=[{local:N,exported:B}];if(w)S.isType=!0;if(V)S.isExternal=!0;if(K===null&&!V)S.isUnresolved=!0;let T=null,F=null,u=Z.importName.kind;if(u==="All"||u==="AllButDefault"){if(C==="Name"&&B)F=B,S.namespaceAlias=B}else F=N,T=B;W.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:T,dstFilePath:K,dstSymbolName:F,specifier:X,metaJson:JSON.stringify(S)})}}function DJ(_,$,J,Q,W){for(let z of _.body){let Y=z;if(Y.type==="ImportDeclaration"){let Z=Y,X=Z.source.value,{resolved:K,isExternal:V}=R_($,X,J,Q),B=Z.importKind==="type",C=Z.specifiers,N={dstFilePath:K,specifier:X};if(C.length===0){let w={};if(B)w.isType=!0;if(V)w.isExternal=!0;if(K===null&&!V)w.isUnresolved=!0;W.push({type:B?"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 S=w.type,T=B||S==="ImportSpecifier"&&w.importKind==="type",F={};if(T)F.isType=!0;if(V)F.isExternal=!0;if(K===null&&!V)F.isUnresolved=!0;let u,E;if(S==="ImportDefaultSpecifier")u="default",E=w.local.name;else if(S==="ImportNamespaceSpecifier")u="*",E=w.local.name,F.importKind="namespace";else u=t_(w.imported),E=w.local.name;W.push({type:T?"type-references":"imports",srcFilePath:$,srcSymbolName:E,...N,dstSymbolName:u,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Y.type==="ExportAllDeclaration"){let Z=Y,X=Z.source.value,{resolved:K,isExternal:V}=R_($,X,J,Q),B=Z.exportKind==="type",C=Z.exported,N=C?t_(C):null,w={isReExport:!0};if(B)w.isType=!0;if(V)w.isExternal=!0;if(K===null&&!V)w.isUnresolved=!0;if(N)w.namespaceAlias=N;W.push({type:B?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:N,specifier:X,metaJson:JSON.stringify(w)});continue}if(Y.type==="ExportNamedDeclaration"){let Z=Y;if(!Z.source)continue;let X=Z.source.value,{resolved:K,isExternal:V}=R_($,X,J,Q),B=Z.exportKind==="type",C=Z.specifiers??[];for(let N of C){let w=B||N.exportKind==="type",S=t_(N.local),T=t_(N.exported),F={isReExport:!0,specifiers:[{local:S,exported:T}]};if(w)F.isType=!0;if(V)F.isExternal=!0;if(K===null&&!V)F.isUnresolved=!0;W.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:T,dstFilePath:K,dstSymbolName:S,specifier:X,metaJson:JSON.stringify(F)})}}}}function IJ(_,$,J,Q,W){new KJ({ImportExpression(Y){let Z=Y.source;if(Z.type!=="Literal"||typeof Z.value!=="string")return;let X=Z.value,{resolved:K,isExternal:V}=R_($,X,J,Q),B={isDynamic:!0};if(V)B.isExternal=!0;if(K===null&&!V)B.isUnresolved=!0;W.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:null,specifier:X,metaJson:JSON.stringify(B)})},CallExpression(Y){let Z=Y.callee,X=!1;if(Z.type==="Identifier"&&Z.name==="require");else if(Z.type==="MemberExpression"&&!Z.computed){let S=Z,T=S.object,F=S.property;if(T.type==="Identifier"&&T.name==="require"&&F.name==="resolve")X=!0;else return}else return;let K=Y.arguments;if(K.length===0)return;let V=K[0];if(V.type!=="Literal"||typeof V.value!=="string")return;let B=V.value,{resolved:C,isExternal:N}=R_($,B,J,Q),w={isRequire:!0};if(X)w.isRequireResolve=!0;if(N)w.isExternal=!0;if(C===null&&!N)w.isUnresolved=!0;W.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:C,dstSymbolName:null,specifier:B,metaJson:JSON.stringify(w)})}}).visit(_)}function e0(_,$,J,Q=N_,W){let z=[];if(W)LJ(W,$,J,Q,z),wJ(W,$,J,Q,z);else DJ(_,$,J,Q,z);return IJ(_,$,J,Q,z),z}import{walk as gJ}from"oxc-walker";function CJ(_){return _.type==="FunctionDeclaration"||_.type==="FunctionExpression"||_.type==="ArrowFunctionExpression"}function AJ(_){return _.type==="ArrowFunctionExpression"}function qJ(_){return _.type==="AssignmentExpression"}function NJ(_){return _.type==="CallExpression"}function RJ(_){return _.type==="FunctionDeclaration"}function SJ(_){return _.type==="FunctionExpression"}function GJ(_){return _.type==="Identifier"}function FJ(_){return _.type==="MemberExpression"}function TJ(_){return _.type==="TSQualifiedName"}function jJ(_){return _.type==="VariableDeclaration"}function E_(_){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 Y=Q.property;if(!Y||typeof Y.name!=="string")return null;J.push(Y.name),Q=Q.object}let W;if(Q.type==="Identifier")W=Q.name;else if(Q.type==="ThisExpression")W="this";else if(Q.type==="Super")W="super";else return null;J.reverse();let z=[W,...J].join(".");return{root:W,parts:J,full:z}}return null}function _1(_,$,J){let Q=[],W=[],z=[];function Y(){if(W.length>0)return W[W.length-1]??null;return null}function Z(V){if(!V)return null;let B=J.get(V.root);if(V.parts.length===0){if(B)return{dstFilePath:B.path,dstSymbolName:B.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:V.root,resolution:"local"}}else{if(B&&B.importedName==="*"){let C=V.parts[V.parts.length-1];return{dstFilePath:B.path,dstSymbolName:C,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:V.full,resolution:"local-member"}}}function X(V,B){let C=E_(V.callee),N=Z(C);if(N){let w=Y(),S={};if(B)S.isNew=!0;if(w===null)S.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:w,dstFilePath:N.dstFilePath,dstSymbolName:N.dstSymbolName,...Object.keys(S).length>0?{metaJson:JSON.stringify(S)}:{}})}}function K(V,B){if(V.type==="FunctionDeclaration"){W.push(V.id?.name??"anonymous");return}if(V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){if(B?.type==="VariableDeclarator"){let w=B.id,S=w.type==="Identifier"?w.name:"anonymous";W.push(S);return}if(B?.type==="MethodDefinition"||B?.type==="TSAbstractMethodDefinition"){let w=B.key,S=z[z.length-1]??"",T="name"in w?w.name:"anonymous",F=S?`${S}.${T}`:T;W.push(F);return}let C=Y(),N=C?`${C}.<anonymous>`:"<anonymous>";W.push(N)}}return gJ(_,{enter(V,B){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){z.push(V.id?.name??"AnonymousClass");return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){K(V,B);return}if(V.type==="CallExpression"){X(V,!1);return}if(V.type==="NewExpression"){X(V,!0);return}},leave(V){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){z.pop();return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){W.pop();return}}}),Q}import{Visitor as kJ}from"oxc-parser";function $1(_,$,J){let Q=[];function W(Y){let Z=Y.id?.name??"AnonymousClass";if(Y.superClass){let K=E_(Y.superClass);if(K){let V=I0(K,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...V})}}let X=Y.implements??[];for(let K of X){let V=E_(K.expression);if(!V)continue;let B=I0(V,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Z,...B})}}return new kJ({TSInterfaceDeclaration(Y){let Z=Y.id.name??"AnonymousInterface",X=Y.extends;for(let K of X){let V=E_(K.expression);if(!V)continue;let B=I0(V,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Z,...B})}},ClassDeclaration(Y){W(Y)},ClassExpression(Y){W(Y)}}).visit(_),Q}function I0(_,$,J){let Q=J.get(_.root);if(Q){if(Q.importedName==="*"){let W=_.parts[_.parts.length-1]??_.root;return{dstFilePath:Q.path,dstSymbolName:W,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 m_(_,$,J,Q=N_,W){let z=t0(_,$,J,Q),Y=e0(_,$,J,Q,W),Z=_1(_,$,z),X=$1(_,$,z);return[...Y,...Z,...X]}function C0(_){let{ast:$,project:J,filePath:Q,relationRepo:W,projectRoot:z,tsconfigPaths:Y,knownFiles:Z,boundaries:X,module:K}=_,V=j_(z,Q),C=m_($,V,Y,Z?(w,S,T)=>{let F=N_(w,S,T);for(let u of F){let E=f_(z,u);if(X){let y=l(E,X);if(Z.has(`${y}::${E}`))return[u]}else if(Z.has(`${J}::${E}`))return[u]}return[]}:void 0,K),N=[];for(let w of C){if(w.dstFilePath===null){let u=f_(z,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 S=f_(z,w.dstFilePath);if(S.startsWith(".."))continue;let T=f_(z,w.srcFilePath),F=X?l(S,X):J;N.push({project:J,type:w.type,srcFilePath:T,srcSymbolName:w.srcSymbolName??null,dstProject:F,dstFilePath:S,dstSymbolName:w.dstSymbolName??null,metaJson:w.metaJson??null,specifier:w.specifier??null,isExternal:0})}return W.replaceFileRelations(J,Q,N),N.length}import{isErr as EJ}from"@zipbul/result";var J1=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function uJ(_){let $=q_(_),J=[];for(let Q of $){J.push({name:Q.name,startLine:Q.span.start.line});for(let W of Q.members??[])J.push({name:`${Q.name}.${W.name}`,startLine:W.span.start.line})}return J.sort((Q,W)=>Q.startLine-W.startLine),J}function A0(_,$,J){let Q=0,W=_.length-1;while(Q<=W){let z=Q+W>>1;if(_[z].startLine<=$)Q=z+1;else W=z-1}if(Q<_.length){let z=_[Q];if(z.startLine-$<=J)return z.name}return null}function e_(_,$,J){let Q=U_(_,$),W=U_(_,J);return{start:Q,end:W}}function Q1(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=h_(J),W=uJ(_),z=[],Y=[...$].sort((X,K)=>X.start-K.start),Z=null;for(let X of Y)if(X.type==="Block"&&X.value.startsWith("*")){Z=null;let K=`/*${X.value}*/`,V=r_(K);if(EJ(V))continue;let B=V;if(!B.tags?.length)continue;let C=U_(Q,X.end),N=A0(W,C.line,3),w=J.slice(X.start,X.end);for(let S of B.tags){let T=[S.name,S.description].filter(Boolean).join(" "),F=`@${S.tag}`,u=w.indexOf(F),E;if(u>=0){let y=X.start+u,d=J.indexOf(`
|
|
4
|
-
`,
|
|
5
|
-
`),V=0;for(let
|
|
6
|
-
`).length});let D_=(this.opts.parseSourceFn??
|
|
7
|
-
`).length})}let D=new Set;for(let R of H)for(let[j]of Q.getFilesMap(R.project))D.add(`${R.project}::${j}`);let G=this.opts.parseSourceFn??g_;for(let R of L){let j=l(R.filePath,H),g=G(j_(U,R.filePath),R.text);if(z1(g))throw g.data;let v=g;if(A.push({filePath:R.filePath,parsed:v}),w0({parsed:v,project:j,filePath:R.filePath,contentHash:R.contentHash,symbolRepo:W}),F)y+=q0({parsed:v,project:j,filePath:R.filePath,annotationRepo:F});Q_+=C0({ast:v.program,project:j,filePath:R.filePath,relationRepo:z,projectRoot:U,tsconfigPaths:K,knownFiles:D,boundaries:H,module:v.module}),p+=W.getFileSymbols(j,R.filePath).length}});for(let D of A)M.set(D.filePath,D.parsed)}else{E();let U=await d();p=U.symbols,Q_=U.relations,y=U.annotations,Z_=U.failedFiles}for(let U of Z){let H=l(U.filePath,this.opts.boundaries);for(let M of W.getFileSymbols(H,U.filePath))N.set(`${M.filePath}::${M.name}`,w(M))}let O_=new Map;for(let U of Z){let H=l(U.filePath,this.opts.boundaries);for(let M of z.getOutgoing(H,U.filePath))O_.set(S(M),M)}let Y_=(U)=>({type:U.type,srcFilePath:U.srcFilePath,dstFilePath:U.dstFilePath,srcSymbolName:U.srcSymbolName,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,metaJson:U.metaJson}),W_={added:[...O_.entries()].filter(([U])=>!T.has(U)).map(([,U])=>Y_(U)),removed:[...T.entries()].filter(([U])=>!O_.has(U)).map(([,U])=>Y_(U))},i={added:[],modified:[],removed:[]};for(let[U,H]of N){let M=C.get(U);if(!M)i.added.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});else{let L=M.fingerprint!==H.fingerprint,A=M.isExported!==H.isExported,D=M.structuralFingerprint!==null&&H.structuralFingerprint!==null&&M.structuralFingerprint!==H.structuralFingerprint;if(L||A||D)i.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))i.removed.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});let c=W1(C,N),w_=new Set(c.renamed.map((U)=>`${U.filePath}::${U.oldName}`)),I=new Set(c.renamed.map((U)=>`${U.filePath}::${U.newName}`));i.added=i.added.filter((U)=>!I.has(`${U.filePath}::${U.name}`)),i.removed=i.removed.filter((U)=>!w_.has(`${U.filePath}::${U.name}`));let q=[];if(!$){for(let[H,M]of V)for(let L of M){if(!L.fingerprint)continue;let A=l(H,this.opts.boundaries),D=W.getByFingerprint(A,L.fingerprint);if(D.length===1){let G=D[0];z.retargetRelations({dstProject:A,oldFile:H,oldSymbol:L.name,newFile:G.filePath,newSymbol:G.name}),q.push({name:G.name,filePath:G.filePath,kind:G.kind,oldFilePath:H,isExported:G.isExported??0})}}let U=new Set(q.map((H)=>`${H.oldFilePath}::${H.name}`));for(let H of c.removed){if(U.has(`${H.filePath}::${H.name}`))continue;let L=C.get(`${H.filePath}::${H.name}`)?.fingerprint;if(!L)continue;let A=l(H.filePath,this.opts.boundaries),D=W.getByFingerprint(A,L);if(D.length===1){let G=D[0];if(G.filePath!==H.filePath||G.name!==H.name)z.retargetRelations({dstProject:A,oldFile:H.filePath,oldSymbol:H.name,newFile:G.filePath,newSymbol:G.name}),q.push({name:G.name,filePath:G.filePath,kind:G.kind,oldFilePath:H.filePath,isExported:G.isExported??0})}}}if(q.length){let U=new Set(q.map((M)=>`${M.filePath}::${M.name}`)),H=new Set(q.map((M)=>`${M.oldFilePath}::${M.name}`));i.added=i.added.filter((M)=>!U.has(`${M.filePath}::${M.name}`)),i.removed=i.removed.filter((M)=>!H.has(`${M.filePath}::${M.name}`))}if(u){let U=new Date().toISOString(),H=$?1:0,M=[];for(let L of i.added){let A=`${L.filePath}::${L.name}`,D=N.get(A),G=l(L.filePath,this.opts.boundaries);M.push({project:G,changeType:"added",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:D?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:B})}for(let L of i.modified){let A=N.get(`${L.filePath}::${L.name}`),D=l(L.filePath,this.opts.boundaries);M.push({project:D,changeType:"modified",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:B})}for(let L of i.removed){let A=`${L.filePath}::${L.name}`,D=C.get(A),G=l(L.filePath,this.opts.boundaries);M.push({project:G,changeType:"removed",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:null,fingerprint:D?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:B})}for(let L of c.renamed){let A=N.get(`${L.filePath}::${L.newName}`),D=l(L.filePath,this.opts.boundaries);M.push({project:D,changeType:"renamed",symbolName:L.newName,symbolKind:L.kind,filePath:L.filePath,oldName:L.oldName,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:B})}for(let L of q){let A=N.get(`${L.filePath}::${L.name}`),D=l(L.filePath,this.opts.boundaries);M.push({project:D,changeType:"moved",symbolName:L.name,symbolKind:L.kind,filePath:L.filePath,oldName:null,oldFilePath:L.oldFilePath,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:B})}if(M.length)try{Y.transaction(()=>{u.insertBatch(M)})}catch(L){this.logger.error("[IndexCoordinator] changelog insert failed:",L)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let L=new Date(Date.now()-2592000000).toISOString();try{for(let A of this.opts.boundaries)u.pruneOlderThan(A.project,L)}catch(A){this.logger.error("[IndexCoordinator] changelog pruning failed:",A)}}}return{indexedFiles:Z.length,removedFiles:X.length,totalSymbols:p,totalRelations:Q_,totalAnnotations:y,durationMs:Date.now()-J,changedFiles:Z.map((U)=>U.filePath),deletedFiles:[...X],failedFiles:Z_,changedSymbols:i,renamedSymbols:c.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:W_}}fireCallbacks(_){for(let $ of this.callbacks)try{$(_)}catch(J){this.logger.error("[IndexCoordinator] onIndexed callback threw:",J)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let _=this.pendingEvents.splice(0);this.startIndex(_,!1).catch(($)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",$))}}}function bJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function PJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function Y1(_,$,J={}){let Q=J.now??Date.now,W=J.isAlive??bJ,z=J.staleAfterSeconds??60,Y=J.instanceId;return _.immediateTransaction(()=>{let Z=_.selectOwner();if(!Z)return _.insertOwner($,Y),"owner";let X=Math.floor((Q()-PJ(Z.heartbeat_at))/1000),K=W(Z.pid);if(K&&Y&&Z.instance_id&&Z.instance_id!==Y&&Z.pid===$)return _.replaceOwner($,Y),"owner";if(K&&X<z)return"reader";return _.replaceOwner($,Y),"owner"})}function X1(_,$){_.deleteOwner($)}function U1(_,$){_.touchOwner($)}class n_{#_;#$=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 R0{lru;constructor(_=500){this.lru=new n_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function S0(_){let{symbolRepo:$,project:J,query:Q}=_,W=Q.project??J,z={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:W,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)z.exactName=Q.text;else{let Z=T_(Q.text);if(Z)z.ftsQuery=Z}if(Q.decorator)z.decorator=Q.decorator;if(Q.regex)z.regex=Q.regex;return $.searchByQuery(z).map((Z)=>{let X=Z.name.indexOf(".");return{id:Z.id,filePath:Z.filePath,kind:Z.kind,name:Z.name,memberName:X>=0?Z.name.slice(X+1):null,span:{start:{line:Z.startLine,column:Z.startColumn},end:{line:Z.endLine,column:Z.endColumn}},isExported:Z.isExported===1,signature:Z.signature,fingerprint:Z.fingerprint,detail:Z.detailJson?(()=>{try{return JSON.parse(Z.detailJson)}catch{return{}}})():{}}})}function G0(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new O("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new O("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let W=Q.project??J,z=Q.limit,Y=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),Z=Y?void 0:z,K=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:W,specifier:Q.specifier,isExternal:Q.isExternal,limit:Z}).map((V)=>{let B;if(V.metaJson)try{B=JSON.parse(V.metaJson)}catch{}return{type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,dstProject:V.dstProject,isExternal:V.isExternal===1,specifier:V.specifier,metaJson:V.metaJson??void 0,meta:B}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let V=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,B=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;K=K.filter((C)=>(!V||V.match(C.srcFilePath))&&(!B||C.dstFilePath===null||B.match(C.dstFilePath)))}if(Y&&z!==void 0&&K.length>z)K=K.slice(0,z);return K}import{findInFiles as fJ,Lang as yJ}from"@ast-grep/napi";function xJ(_){let $=new Set,J=/\${1,3}([A-Z_][A-Z_0-9]*)/g,Q;while((Q=J.exec(_))!==null)$.add(Q[0]);return[...$]}function hJ(_){return _.replace(/^\$+/,"")}function mJ(_,$){if($.length===0)return;let J={},Q=!1;for(let W of $){let z=hJ(W),Y=_.getMatch(z);if(Y){let X=Y.range();J[W]={text:Y.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 Z=_.getMultipleMatches(z);if(Z.length>0){let X=Z[0].range(),K=Z[Z.length-1].range();J[W]={text:Z.map((V)=>V.text()).join(", "),startLine:X.start.line+1,endLine:K.end.line+1,startColumn:X.start.column,endColumn:K.end.column,startOffset:X.start.index,endOffset:K.end.index},Q=!0}}return Q?J:void 0}async function F0(_){if(_.filePaths.length===0)return[];let $=xJ(_.pattern),J=[];return await fJ(yJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(Q,W)=>{if(Q){console.warn("[patternSearch] findInFiles callback error:",Q);return}for(let z of W){let Y=z.range(),Z={filePath:z.getRoot().filename(),startLine:Y.start.line+1,endLine:Y.end.line+1,startColumn:Y.start.column,endColumn:Y.end.column,startOffset:Y.start.index,endOffset:Y.end.index,matchedText:z.text()},X=mJ(z,$);if(X)Z.captures=X;J.push(Z)}}),J}import o from"typescript";import{isErr as $6}from"@zipbul/result";import B_ from"typescript";import nJ from"path";import{err as T0}from"@zipbul/result";function dJ(_){try{return x0("fs").readFileSync(_,"utf-8")}catch{return}}function pJ(_){try{return x0("fs").readFileSync(_,"utf-8")}catch{return}}class _0{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??dJ,Q=$.resolveNonTrackedFile??pJ,W=nJ.dirname(_),z=J(_);if(z===void 0)return T0(new O("semantic",`tsconfig not found: ${_}`));let Y=B_.parseJsonText(_,z),Z=Y.parseDiagnostics;if(Z&&Z.length>0){let B=Z.map((C)=>B_.flattenDiagnosticMessageText(C.messageText,`
|
|
8
|
-
`)).join("; ");return
|
|
9
|
-
`)).join("; ");return T0(new O("semantic",`tsconfig compile error: ${C}`))}}let K=new V1(X.fileNames,X.options,W,Q),V=B_.createLanguageService(K);return new _0(V,K)}get isDisposed(){return this.#J}getProgram(){this.#Z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#Z(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#Z(),this.#_}notifyFileChanged(_,$){if(this.#J)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#J)return;this.#$.removeFile(_)}dispose(){if(this.#J)return;this.#J=!0,this.#_.dispose()}#Z(){if(this.#J)throw Error("TscProgram is disposed")}}class V1{#_;#$;#J;#Z;#W=new Map;#z=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)this.#z.delete(`${_}:${J.version}`),J.version+=1,J.content=$;else this.#W.set(_,{version:1,content:$})}removeFile(_){let $=this.#W.get(_);if($)this.#z.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 W=`${_}:${$.version}`,z=this.#z.get(W);if(!z)z=B_.ScriptSnapshot.fromString($.content),this.#z.set(W,z);return z}let J=this.#Q.get(_);if(J)return J;let Q=this.#Z(_);if(Q!==void 0)return J=B_.ScriptSnapshot.fromString(Q),this.#Q.set(_,J),J;return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return B_.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 m from"typescript";import iJ from"typescript";function e(_,$){if($<0||$>=_.getEnd())return;let J=iJ.getTokenAtPosition(_,$);if(J.getStart(_,!1)>$)return;return J}var $0=8;function lJ(_){return!!(_.flags&m.TypeFlags.Object)&&!!(_.objectFlags&m.ObjectFlags.Reference)}function M_(_,$,J=0,Q){if(Q){let w=Q.get($);if(w)return w}let W=_.typeToString($),z=$.flags,Y=!!(z&m.TypeFlags.Union),Z=!!(z&m.TypeFlags.Intersection),X;if(J<$0&&lJ($)){let w=_.getTypeArguments($);if(w.length>0)X=w}let K=!!(z&m.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,V;if(Y&&J<$0)V=$.types.map((w)=>M_(_,w,J+1,Q));else if(Z&&J<$0)V=$.types.map((w)=>M_(_,w,J+1,Q));let B;if(X&&X.length>0)B=X.map((w)=>M_(_,w,J+1,Q));let C;if(J<$0&&!!(z&m.TypeFlags.Object)&&!Y&&!Z){let w=_.getPropertiesOfType($);if(w.length>0&&w.length<=50){let S=$.symbol?.declarations?.[0];C=[];for(let T of w){let F=T.declarations?.[0]??S;if(!F)continue;try{let u=_.getTypeOfSymbolAtLocation(T,F);C.push({name:T.getName(),type:M_(_,u,J+1,Q)})}catch{}}if(C.length===0)C=void 0}}let N={text:W,flags:z,isUnion:Y,isIntersection:Z,isGeneric:K,members:V,typeArguments:B,properties:C};if(Q)Q.set($,N);return N}function cJ(_){return m.isFunctionDeclaration(_)||m.isVariableDeclaration(_)||m.isClassDeclaration(_)||m.isInterfaceDeclaration(_)||m.isTypeAliasDeclaration(_)||m.isEnumDeclaration(_)||m.isMethodDeclaration(_)||m.isPropertyDeclaration(_)||m.isPropertySignature(_)||m.isMethodSignature(_)}var j0="/__gildash_type_probe__.ts";class g0{program;#_=null;constructor(_){this.program=_}#$(_){if(this.#_===_)return;this.program.notifyFileChanged(j0,`declare const __gildash_probe__: ${_};`),this.#_=_}#J(_,$){let J=_.getSourceFile(j0);if(!J)return null;let Q=J.statements[0];if(!Q||!m.isVariableStatement(Q))return null;let W=Q.declarationList.declarations[0];if(!W)return null;return $.getTypeAtLocation(W.name)}clearProbe(){if(this.#_!==null)this.program.removeFile(j0),this.#_=null}collectAt(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker();if($<0)return null;let W=J.getSourceFile(_);if(!W)return null;if($>=W.getEnd())return null;let z=e(W,$);if(!z)return null;if(!m.isIdentifier(z)&&!m.isTypeNode(z))return null;try{let Y=Q.getTypeAtLocation(z);return M_(Q,Y,0,new Map)}catch{return null}}isAssignableTo(_,$,J,Q){let W=this.program.getProgram(),z=W.getTypeChecker(),Y=W.getSourceFile(_);if(!Y)return null;let Z=e(Y,$);if(!Z||!m.isIdentifier(Z))return null;let X=W.getSourceFile(J);if(!X)return null;let K=e(X,Q);if(!K||!m.isIdentifier(K))return null;try{let V=z.getTypeAtLocation(Z),B=z.getTypeAtLocation(K);return z.isTypeAssignableTo(V,B)}catch{return null}}isAssignableToType(_,$,J,Q){this.#$(J);let W=this.program.getProgram(),z=W.getTypeChecker(),Y=W.getSourceFile(_);if(!Y)return null;let Z=e(Y,$);if(!Z||!m.isIdentifier(Z)&&!m.isTypeNode(Z))return null;try{let X=this.#J(W,z);if(!X)return null;let K=z.getTypeAtLocation(Z);if(Q?.anyConstituent&&K.isUnion())return K.types.some((V)=>z.isTypeAssignableTo(V,X));return z.isTypeAssignableTo(K,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,J,Q){let W=new Map;if($.length===0)return W;this.#$(J);let z=this.program.getProgram(),Y=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return W;try{let X=this.#J(z,Y);if(!X)return W;let K=Z.getEnd();for(let V of $){if(V<0||V>=K)continue;let B=e(Z,V);if(!B||!m.isIdentifier(B)&&!m.isTypeNode(B))continue;try{let C=Y.getTypeAtLocation(B);if(Q?.anyConstituent&&C.isUnion())W.set(V,C.types.some((N)=>Y.isTypeAssignableTo(N,X)));else W.set(V,Y.isTypeAssignableTo(C,X))}catch{}}}catch{}return W}collectAtPositions(_,$){let J=new Map;if($.length===0)return J;let Q=this.program.getProgram(),W=Q.getTypeChecker(),z=Q.getSourceFile(_);if(!z)return J;let Y=z.getEnd(),Z=new Map;for(let X of $){if(X<0||X>=Y)continue;let K=e(z,X);if(!K)continue;if(!m.isIdentifier(K)&&!m.isTypeNode(K))continue;try{let V=W.getTypeAtLocation(K);J.set(X,M_(W,V,0,Z))}catch{}}return J}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=J.getTypeChecker(),W=J.getSourceFile(_);if(!W)return $;let z=new Map;function Y(Z){if(cJ(Z)&&Z.name&&m.isIdentifier(Z.name)){let X=Z.name;try{let K=Q.getTypeAtLocation(X),V=X.getStart(W);$.set(V,M_(Q,K,0,z))}catch{}}m.forEachChild(Z,Y)}return Y(W),$}}import L_ from"typescript";var aJ=1000,sJ=1;function rJ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?L_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function J0(_,$=0,J){let Q=_.declarations?.[0],W=Q?.getSourceFile(),z=Q?L_.getNameOfDeclaration(Q):void 0,Y=W?.fileName??"",Z=z?.getStart(W,!1)??Q?.getStart(W,!1)??0,X={name:_.getName(),filePath:Y,position:Z},K=_;if(K.parent)X.parent=rJ(K.parent);let V=J&&!!(_.flags&L_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<sJ){let B=V.flags,C=!!(B&L_.SymbolFlags.Enum),N=!!(B&(L_.SymbolFlags.NamespaceModule|L_.SymbolFlags.ValueModule)),w=!!(B&(L_.SymbolFlags.Class|L_.SymbolFlags.Interface));if(C&&V.exports&&V.exports.size>0){let S=[];V.exports.forEach((T)=>{S.push(J0(T,$+1,J))}),X.members=S}else if(w&&V.members&&V.members.size>0){let S=[];V.members.forEach((T)=>{S.push(J0(T,$+1,J))}),X.members=S}if(N&&V.exports&&V.exports.size>0){let S=[];V.exports.forEach((T)=>{S.push(J0(T,$+1,J))}),X.exports=S}}return X}class k0{#_;#$;#J=new Map;constructor(_,$=aJ){this.#_=_,this.#$=new n_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let W=this.#_.getProgram(),z=W.getSourceFile(_);if(!z)return null;let Y=e(z,$);if(!Y||!L_.isIdentifier(Y))return null;let Z=W.getTypeChecker(),X=Z.getSymbolAtLocation(Y);if(!X)return null;let K=J0(X,0,Z);this.#$.set(J,K);let V=this.#J.get(_);if(!V)V=new Set,this.#J.set(_,V);return V.add(J),K}invalidate(_){let $=this.#J.get(_);if($){for(let J of $)this.#$.delete(J);this.#J.delete(_)}}clear(){this.#$.clear(),this.#J.clear()}}import oJ from"typescript";class E0{#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let W=e(Q,$);if(!W||!oJ.isIdentifier(W))return[];let Y=this.#_.getLanguageService().findReferences(_,$);if(!Y||Y.length===0)return[];let Z=[];for(let X of Y)for(let K of X.references){let V=J.getSourceFile(K.fileName);if(!V)continue;let{line:B,character:C}=V.getLineAndCharacterOfPosition(K.textSpan.start);Z.push({filePath:K.fileName,position:K.textSpan.start,line:B+1,column:C,isDefinition:K.isDefinition??!1,isWrite:K.isWriteAccess??!1})}return Z}}import x from"typescript";function tJ(_,$){let J=e(_,$);if(!J)return;if(O1(J))return J;let Q=J.parent;for(let W=0;W<5&&Q;W++){if(O1(Q))return Q;Q=Q.parent}return J}function O1(_){return x.isClassDeclaration(_)||x.isClassExpression(_)||x.isFunctionDeclaration(_)||x.isFunctionExpression(_)||x.isArrowFunction(_)||x.isVariableDeclaration(_)||x.isObjectLiteralExpression(_)}function H1(_){if(x.isClassDeclaration(_)||x.isClassExpression(_))return"class";if(x.isFunctionDeclaration(_)||x.isFunctionExpression(_)||x.isArrowFunction(_))return"function";if(x.isObjectLiteralExpression(_))return"object";if(x.isVariableDeclaration(_)&&_.initializer)return H1(_.initializer);return"class"}function eJ(_,$){if(x.isClassDeclaration(_)||x.isFunctionDeclaration(_))return _.name?.getText($)??"";if(x.isClassExpression(_))return _.name?.getText($)??"";if(x.isVariableDeclaration(_)&&x.isIdentifier(_.name))return _.name.getText($);if(x.isFunctionExpression(_))return _.name?.getText($)??"";if(x.isArrowFunction(_)&&_.parent&&x.isVariableDeclaration(_.parent)){if(x.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(x.isObjectLiteralExpression(_)&&_.parent&&x.isVariableDeclaration(_.parent)){if(x.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function _6(_){if(!x.isClassDeclaration(_)&&!x.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===x.SyntaxKind.ImplementsKeyword)}class u0{#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let W=e(Q,$);if(!W||!x.isIdentifier(W))return[];let Y=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Y||Y.length===0)return[];let Z=[];for(let X of Y){if(X.kind===x.ScriptElementKind.interfaceElement||X.kind===x.ScriptElementKind.typeElement)continue;let K=J.getSourceFile(X.fileName);if(!K)continue;let V=tJ(K,X.textSpan.start);if(!V)continue;let B=H1(V),C=eJ(V,K),N=_6(V);Z.push({filePath:X.fileName,symbolName:C,position:X.textSpan.start,kind:B,isExplicit:N})}return Z}}function J6(_){if(o.isFunctionDeclaration(_))return"function";if(o.isClassDeclaration(_))return"class";if(o.isInterfaceDeclaration(_))return"interface";if(o.isTypeAliasDeclaration(_))return"type";if(o.isEnumDeclaration(_))return"enum";if(o.isVariableDeclaration(_))return"const";if(o.isVariableStatement(_))return"const";return"unknown"}function M1(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class Q0{#_;#$;#J;#Z;#W;#z=!1;constructor(_,$,J,Q,W){this.#_=_,this.#$=$,this.#J=J,this.#Z=Q,this.#W=W}static create(_,$={}){let J=_0.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if($6(J))return J;let Q=J,W=$.typeCollector??new g0(Q),z=$.symbolGraph??new k0(Q),Y=$.referenceResolver??new E0(Q),Z=$.implementationFinder??new u0(Q);return new Q0(Q,W,z,Y,Z)}get isDisposed(){return this.#z}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(_,$)}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 W=e(Q,$);if(!W)return null;let z=J.getTypeChecker(),Y=z.getTypeAtLocation(W);if(!(Y.flags&o.TypeFlags.Object)||!(Y.objectFlags&o.ObjectFlags.ClassOrInterface))return null;let Z=z.getBaseTypes(Y);if(!Z||Z.length===0)return[];let X=new Map;return Z.map((K)=>M_(z,K,0,X))}getModuleInterface(_){this.#Q();let $=[],J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return{filePath:_,exports:$};let W=J.getTypeChecker(),z=W.getSymbolAtLocation(Q);if(z){let Y=W.getExportsOfModule(z),Z=new Map;for(let X of Y){let K=X.getName(),V=X.declarations?.[0],B="unknown";if(V){if(B=J6(V),B==="unknown"&&o.isExportAssignment(V))B="const"}let C=null;try{let N=W.getTypeOfSymbolAtLocation(X,V??Q);C=M_(W,N,0,Z)}catch{}$.push({name:K,kind:B,resolvedType:C})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#z)return;this.#_.notifyFileChanged(_,$),this.#J.invalidate(_)}notifyFileDeleted(_){if(this.#z)return;this.#_.removeFile(_),this.#J.invalidate(_)}lineColumnToPosition(_,$,J){this.#Q();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return o.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#Q();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let W=Q.getFullText(),z=$;while(z<W.length){let Y=W.indexOf(J,z);if(Y<0)return null;let Z=Y>0?W.charCodeAt(Y-1):32,X=Y+J.length<W.length?W.charCodeAt(Y+J.length):32;if(!M1(Z)&&!M1(X))return Y;z=Y+1}return null}getDiagnostics(_,$){this.#Q();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let W={[o.DiagnosticCategory.Error]:"error",[o.DiagnosticCategory.Warning]:"warning",[o.DiagnosticCategory.Suggestion]:"suggestion",[o.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?o.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Y)=>{let Z=1,X=0;if(Y.file&&Y.start!==void 0){let K=o.getLineAndCharacterOfPosition(Y.file,Y.start);Z=K.line+1,X=K.character}return{filePath:Y.file?.fileName??_,line:Z,column:X,message:o.flattenDiagnosticMessageText(Y.messageText,`
|
|
10
|
-
`),code:Y.code,category:W[Y.category]??"error"}})}dispose(){if(this.#z)return;this.#z=!0,this.#$.clearProbe(),this.#_.dispose(),this.#J.clear()}#Q(){if(this.#z)throw Error("SemanticLayer is disposed")}}import{eq as S_,and as K1,sql as Q6}from"drizzle-orm";var B1=80;class v0{db;constructor(_){this.db=_}insertBatch(_,$,J){if(!J.length)return;let Q=J.map((W)=>({project:_,filePath:$,tag:W.tag,value:W.value,source:W.source,symbolName:W.symbolName,startLine:W.startLine,startColumn:W.startColumn,endLine:W.endLine,endColumn:W.endColumn,indexedAt:W.indexedAt}));for(let W=0;W<Q.length;W+=B1)this.db.drizzleDb.insert(z_).values(Q.slice(W,W+B1)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(z_).where(K1(S_(z_.project,_),S_(z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(z_).where(K1(_.project?S_(z_.project,_.project):void 0,_.tag?S_(z_.tag,_.tag):void 0,_.filePath?S_(z_.filePath,_.filePath):void 0,_.symbolName?S_(z_.symbolName,_.symbolName):void 0,_.source?S_(z_.source,_.source):void 0,_.ftsQuery?Q6`${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 u_,and as L1,sql as d_,gt as W6,gte as z6}from"drizzle-orm";var w1=80;class b0{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+=w1)this.db.drizzleDb.insert(t).values($.slice(J,J+w1)).run()}getSince(_){return this.db.drizzleDb.select().from(t).where(L1(u_(t.project,_.project),z6(t.changedAt,_.since),_.symbolName?u_(t.symbolName,_.symbolName):void 0,_.changeTypes?.length?d_`${t.changeType} IN (${d_.join(_.changeTypes.map(($)=>d_`${$}`),d_`, `)})`:void 0,_.filePath?u_(t.filePath,_.filePath):void 0,_.includeFullIndex?void 0:u_(t.isFullIndex,0),_.indexRunId?u_(t.indexRunId,_.indexRunId):void 0,_.afterId?W6(t.id,_.afterId):void 0)).orderBy(t.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(t).where(L1(u_(t.project,_),d_`${t.changedAt} < ${$}`)).run().changes}}function D1(_){let{annotationRepo:$,project:J,query:Q}=_,W=Q.project??J,z;if(Q.text){let Z=T_(Q.text);if(Z)z=Z}return $.search({project:W,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:z,limit:Q.limit}).map((Z)=>({tag:Z.tag,value:Z.value,source:Z.source,filePath:Z.filePath,symbolName:Z.symbolName,span:{start:{line:Z.startLine,column:Z.startColumn},end:{line:Z.endLine,column:Z.endColumn}}}))}class W0{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:W}=J;if(W===null)continue;if(!this.adjacencyList.has(Q))this.adjacencyList.set(Q,new Set);if(this.adjacencyList.get(Q).add(W),!this.adjacencyList.has(W))this.adjacencyList.set(W,new Set);if(!this.reverseAdjacencyList.has(W))this.reverseAdjacencyList.set(W,new Set);this.reverseAdjacencyList.get(W).add(Q)}}patchFiles(_,$,J){let Q=new Set([..._,...$]);for(let W of Q){let z=this.adjacencyList.get(W);if(z){for(let Z of z)this.reverseAdjacencyList.get(Z)?.delete(W);z.clear()}let Y=this.reverseAdjacencyList.get(W);if(Y){for(let Z of Y)this.adjacencyList.get(Z)?.delete(W);Y.clear()}}for(let W of $)this.adjacencyList.delete(W),this.reverseAdjacencyList.delete(W);for(let W of _){let z=J(W);for(let Y of z){if(!this.adjacencyList.has(Y.srcFilePath))this.adjacencyList.set(Y.srcFilePath,new Set);if(this.adjacencyList.get(Y.srcFilePath).add(Y.dstFilePath),!this.adjacencyList.has(Y.dstFilePath))this.adjacencyList.set(Y.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Y.dstFilePath))this.reverseAdjacencyList.set(Y.dstFilePath,new Set);this.reverseAdjacencyList.get(Y.dstFilePath).add(Y.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 W of this.reverseAdjacencyList.get(Q)??[])if(!$.has(W))$.add(W),J.push(W)}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 W=Q.pop();if(W.entered){$.delete(W.node);continue}if($.has(W.node))return!0;if(_.has(W.node))continue;_.add(W.node),$.add(W.node),Q.push({node:W.node,entered:!0});for(let z of this.adjacencyList.get(W.node)??[]){if($.has(z))return!0;if(!_.has(z))Q.push({node:z,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 W of this.adjacencyList.get(Q)??[])if(!$.has(W))$.add(W),J.push(W)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,W]of this.adjacencyList)J.set(Q,Array.from(W));return V6(J,$)}}var Z6=(_,$)=>_.localeCompare($);function Y6(_){let $=_.length>1&&_[0]===_[_.length-1]?_.slice(0,-1):[..._];if($.length===0)return[];let J=$;for(let Q=1;Q<$.length;Q++){let W=$.slice(Q).concat($.slice(0,Q));if(W.join("::")<J.join("::"))J=W}return[...J]}function P0(_,$,J){let Q=Y6(J);if(Q.length===0)return!1;let W=Q.join("->");if(_.has(W))return!1;return _.add(W),$.push(Q),!0}function X6(_){let $=0,J=[],Q=new Set,W=new Map,z=new Map,Y=[],Z=(X)=>{W.set(X,$),z.set(X,$),$+=1,J.push(X),Q.add(X);for(let K of _.get(X)??[])if(!W.has(K))Z(K),z.set(X,Math.min(z.get(X)??0,z.get(K)??0));else if(Q.has(K))z.set(X,Math.min(z.get(X)??0,W.get(K)??0));if(z.get(X)===W.get(X)){let K=[],V="";do V=J.pop()??"",Q.delete(V),K.push(V);while(V!==X&&J.length>0);Y.push(K)}};for(let X of _.keys())if(!W.has(X))Z(X);return{components:Y}}function U6(_,$,J){let Q=[],W=new Set,z=[..._].sort(Z6),Y=(Z,X,K)=>{X.delete(Z);let V=K.get(Z);if(!V)return;for(let B of V)if(X.has(B))Y(B,X,K);V.clear()};for(let Z=0;Z<z.length&&Q.length<J;Z++){let X=z[Z]??"",K=new Set(z.slice(Z)),V=new Set,B=new Map,C=[],N=(S)=>($.get(S)??[]).filter((T)=>K.has(T)),w=(S)=>{if(Q.length>=J)return!0;let T=!1;C.push(S),V.add(S);for(let F of N(S)){if(Q.length>=J)break;if(F===X)P0(W,Q,C.concat(X)),T=!0;else if(!V.has(F)){if(w(F))T=!0}}if(T)Y(S,V,B);else for(let F of N(S)){let u=B.get(F)??new Set;u.add(S),B.set(F,u)}return C.pop(),T};w(X)}return Q}function V6(_,$){let{components:J}=X6(_),Q=[],W=new Set;for(let z of J){if(Q.length>=$)break;if(z.length===0)continue;if(z.length===1){let X=z[0]??"";if((_.get(X)??[]).includes(X))P0(W,Q,[X,X]);continue}let Y=$-Q.length,Z=U6(z,_,Y);for(let X of Z){if(Q.length>=$)break;P0(W,Q,X)}}return Q}var O6=15000;function z0(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function G_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>O6)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new W0({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((W)=>W.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function I1(_,$,J,Q=1e4){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).filter((W)=>W.dstFilePath!==null).map((W)=>W.dstFilePath)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getDependencies failed",{cause:W})}}function C1(_,$,J,Q=1e4){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{dstFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).map((W)=>W.srcFilePath)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getDependents failed",{cause:W})}}async function A1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return G_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getAffected failed",{cause:Q})}}async function q1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return G_(_,$).hasCycle()}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: hasCycle failed",{cause:J})}}async function N1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return G_(_,$).getAdjacencyList()}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getImportGraph failed",{cause:J})}}async function R1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return G_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function S1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return G_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function G1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return G_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getCyclePaths failed",{cause:Q})}}async function F1(_,$,J){if(_.closed)throw new O("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 O)throw Q;throw new O("search","Gildash: getFanMetrics failed",{cause:Q})}}var K6=30000,T1=15000,B6=10;function L6(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??v_.basename(_.projectRoot)}function w6(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(W){_.logger.error("[Gildash] onFileChanged callback threw:",W)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let W of _.onErrorCallbacks)try{W(Q instanceof O?Q:new O("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(W){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",W);for(let z of _.onErrorCallbacks)try{z(W instanceof O?W:new O("semantic","semantic notifyFileChanged failed",{cause:W}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(W){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",W)}})}}async function D6(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=v_.resolve(_.projectRoot,J.filePath),W=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,W)}catch{}}))}async function j1(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new N0({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)=>L6(_,Q),logger:_.logger});_.coordinator=J;for(let Q of _.onIndexedCallbacks)J.onIndexed(Q);if(J.onIndexed((Q)=>{let W=Q.changedFiles.length+Q.deletedFiles.length;if(_.graphCache&&W>0&&W<100){let z=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Y)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>z.getByType(X,"imports").concat(z.getByType(X,"type-references")).concat(z.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Y||X.dstFilePath===Y)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else z0(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new B0({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(w6(_,J)).then((W)=>{if(p_(W))throw W.data}),_.watcher=Q,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},K6)}await J.fullIndex(),await D6(_)}function I6(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let W=()=>{$().catch((z)=>_.logger.error("[Gildash] close error during signal",Q,z))};if(Q==="beforeExit")process.on("beforeExit",W);else process.on(Q,W);_.signalHandlers.push([Q,W])}}async function g1(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:W=500,logger:z=console,existsSyncFn:Y=M6,dbConnectionFactory:Z,watcherFactory:X,coordinatorFactory:K,repositoryFactory:V,acquireWatcherRoleFn:B=Y1,releaseWatcherRoleFn:C=X1,updateHeartbeatFn:N=U1,discoverProjectsFn:w=a_,parseSourceFn:S=g_,extractSymbolsFn:T=q_,extractRelationsFn:F=m_,symbolSearchFn:u=S0,relationSearchFn:E=G0,patternSearchFn:y=F0,loadTsconfigPathsFn:d=x_,readFileFn:p=async(c)=>Bun.file(c).text(),unlinkFn:Q_=async(c)=>{await Bun.file(c).unlink()},watchMode:Z_,semantic:O_,semanticLayerFactory:Y_}=_;if(!v_.isAbsolute($))throw new O("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Y($))throw new O("validation",`Gildash: projectRoot does not exist: "${$}"`);let W_=Z?Z():new V0({projectRoot:$}),i=W_.open();if(p_(i))throw i.data;try{let c=await w($),w_=c[0]?.project??v_.basename($),I=V?V():(()=>{let G=W_;return{fileRepo:new O0(G),symbolRepo:new H0(G),relationRepo:new M0(G),parseCache:new R0(W)}})(),q=V?null:W_,U=q?new v0(q):null,H=q?new b0(q):null,M=Z_??!0,L=crypto.randomUUID(),A;if(M)A=await Promise.resolve(B(W_,process.pid,{instanceId:L}));else A="owner";let D={projectRoot:$,extensions:J,ignorePatterns:Q,logger:z,defaultProject:w_,role:A,db:W_,symbolRepo:I.symbolRepo,relationRepo:I.relationRepo,fileRepo:I.fileRepo,parseCache:I.parseCache,annotationRepo:U,changelogRepo:H,annotationSearchFn:D1,releaseWatcherRoleFn:C,parseSourceFn:S,extractSymbolsFn:T,extractRelationsFn:F,symbolSearchFn:u,relationSearchFn:E,patternSearchFn:y,readFileFn:p,unlinkFn:Q_,existsSyncFn:Y,acquireWatcherRoleFn:B,updateHeartbeatFn:N,watcherFactory:X,coordinatorFactory:K,instanceId:L,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:c,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(s_($),D.tsconfigPaths=await d($),O_){let G=v_.join($,"tsconfig.json");try{if(Y_)D.semanticLayer=Y_(G);else{let R=Q0.create(G);if(p_(R))throw R.data;D.semanticLayer=R}}catch(R){if(R instanceof O)throw R;throw new O("semantic","Gildash: semantic layer creation failed",{cause:R})}}if(A==="owner")await j1(D,{isWatchMode:M});else{let G=0,R=async()=>{try{let j=await Promise.resolve(D.acquireWatcherRoleFn(D.db,process.pid,{instanceId:D.instanceId}));if(G=0,j==="owner"){D.role="owner";for(let g of D.onRoleChangedCallbacks)try{g("owner")}catch(v){D.logger.error("[Gildash] onRoleChanged callback threw:",v)}clearInterval(D.timer),D.timer=null;try{await j1(D,{isWatchMode:!0})}catch(g){if(D.logger.error("[Gildash] owner promotion failed, reverting to reader",g),D.role="reader",D.timer!==null)clearInterval(D.timer),D.timer=null;if(D.watcher){let v=await D.watcher.close();if(p_(v))D.logger.error("[Gildash] watcher close error during promotion rollback",v.data);D.watcher=null}if(D.coordinator)await D.coordinator.shutdown().catch((v)=>D.logger.error("[Gildash] coordinator shutdown error during promotion rollback",v)),D.coordinator=null;try{D.releaseWatcherRoleFn(D.db,process.pid)}catch(v){D.logger.error("[Gildash] failed to release watcher role during promotion rollback",v)}D.timer=setInterval(R,T1)}}}catch(j){G++;let g=j instanceof O?j:new O("watcher","Gildash: healthcheck error",{cause:j});for(let v of D.onErrorCallbacks)try{v(g)}catch(n){D.logger.error("[Gildash] onError callback threw:",n)}if(D.logger.error("[Gildash] healthcheck error",j),G>=B6)D.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(D.timer),D.timer=null,Z0(D).catch((v)=>D.logger.error("[Gildash] close error during healthcheck shutdown",v))}};D.timer=setInterval(R,T1)}if(M)I6(D,()=>Z0(D));return D}catch(c){if(W_.close(),c instanceof O)throw c;throw new O("store","Gildash: initialization failed",{cause:c})}}async function Z0(_,$){if(_.closed)return;_.closed=!0;let J=[];for(let[Q,W]of _.signalHandlers)if(Q==="beforeExit")process.off("beforeExit",W);else process.off(Q,W);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(p_(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(v_.join(_.projectRoot,I_,l_+Q))}catch{}if(J.length>0)throw new O("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as k1}from"@zipbul/result";function E1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");let W=_.parseSourceFn($,J,Q);if(k1(W))throw W.data;return _.parseCache.set($,W),W}async function u1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");let Q=new Map,W=[];return await Promise.all($.map(async(z)=>{try{let Y=await _.readFileFn(z),Z=_.parseSourceFn(z,Y,J);if(!k1(Z))Q.set(z,Z);else W.push({filePath:z,error:Z.data})}catch(Y){W.push({filePath:z,error:Y instanceof Error?Y:Error(String(Y))})}})),{parsed:Q,failures:W}}function v1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.parseCache.get($)}function b1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function P1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import f1 from"path";function y1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: getStats failed",{cause:J})}}function f0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchSymbols failed",{cause:J})}}function x1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchRelations failed",{cause:J})}}function h1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchAllSymbols failed",{cause:J})}}function m1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchAllRelations failed",{cause:J})}}function n1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: listIndexedFiles failed",{cause:J})}}function d1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getInternalRelations failed",{cause:Q})}}function p1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let W=Q??_.defaultProject,z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:W,query:{text:$,exact:!0,filePath:J,limit:1}});if(z.length===0)return null;let Y=z[0],Z=Y.detail,X={...Y,members:Z.members,jsDoc:Z.jsDoc,parameters:Z.parameters,returnType:Z.returnType,heritage:Z.heritage,decorators:Z.decorators,typeParameters:Z.typeParameters,initializer:Z.initializer};if(_.semanticLayer)try{let K=f1.isAbsolute(J)?J:f1.resolve(_.projectRoot,J),V=_.semanticLayer.lineColumnToPosition(K,Y.span.start.line,Y.span.start.column);if(V!==null){let B=_.semanticLayer.findNamePosition(K,V,Y.name)??V,C=_.semanticLayer.collectTypeAt(K,B);if(C)X.resolvedType=C}}catch{}return X}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getFullSymbol failed",{cause:W})}}function i1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,W=_.fileRepo.getFile(Q,$);if(!W)throw new O("search",`Gildash: file '${$}' is not in the index`);let z=_.symbolRepo.getFileSymbols(Q,$),Y=_.relationRepo.getOutgoing(Q,$);return{filePath:W.filePath,lineCount:W.lineCount??0,size:W.size,symbolCount:z.length,exportedSymbolCount:z.filter((Z)=>Z.isExported).length,relationCount:Y.length}}catch(Q){if(Q instanceof O)throw Q;throw new O("store","Gildash: getFileStats failed",{cause:Q})}}function l1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(J??_.defaultProject,$)}catch(Q){if(Q instanceof O)throw Q;throw new O("store","Gildash: getFileInfo failed",{cause:Q})}}function c1(_,$,J){return f0(_,{filePath:$,project:J??void 0,limit:1e4})}function a1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let W=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((z)=>({name:z.name,kind:z.kind,parameters:z.detail.parameters?`(${z.detail.parameters.map((Y)=>`${Y.name}${Y.isOptional?"?":""}: ${Y.type??"unknown"}`).join(", ")})`:void 0,returnType:z.detail.returnType??void 0,jsDoc:z.detail.jsDoc?.description??void 0}));return{filePath:$,exports:W}}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getModuleInterface failed",{cause:Q})}}import P from"path";function i_(_,$,J,Q){let W=Q??_.defaultProject,z=P.isAbsolute(J)?P.relative(_.projectRoot,J):J,Y=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:W,query:{text:$,exact:!0,filePath:z,limit:1}});if(Y.length===0)return null;let Z=Y[0],X=P.isAbsolute(J)?J:P.resolve(_.projectRoot,J),K=_.semanticLayer.lineColumnToPosition(X,Z.span.start.line,Z.span.start.column);if(K===null)return null;let V=_.semanticLayer.findNamePosition(X,K,Z.name)??K;return{sym:Z,position:V,absPath:X}}function s1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=i_(_,$,J,Q);if(!W)return null;return _.semanticLayer.collectTypeAt(W.absPath,W.position)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getResolvedType failed",{cause:W})}}function r1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=i_(_,$,J,Q);if(!W)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(W.absPath,W.position)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getSemanticReferences failed",{cause:W})}}function o1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=i_(_,$,J,Q);if(!W)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(W.absPath,W.position)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getImplementations failed",{cause:W})}}function t1(_,$,J,Q,W,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Y=i_(_,$,J,z);if(!Y)throw new O("search",`Gildash: source symbol '${$}' not found in '${J}'`);let Z=i_(_,Q,W,z);if(!Z)throw new O("search",`Gildash: target symbol '${Q}' not found in '${W}'`);return _.semanticLayer.isTypeAssignableTo(Y.absPath,Y.position,Z.absPath,Z.position)}catch(Y){if(Y instanceof O)throw Y;throw new O("semantic","Gildash: isTypeAssignableTo failed",{cause:Y})}}function e1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getFileTypes failed",{cause:J})}}function _$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$),z=_.semanticLayer.lineColumnToPosition(W,J,Q);if(z===null)return null;return _.semanticLayer.collectTypeAt(W,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: getResolvedTypeAt failed",{cause:W})}}function $$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($.source.filePath)?$.source.filePath:P.resolve(_.projectRoot,$.source.filePath),Q=P.isAbsolute($.target.filePath)?$.target.filePath:P.resolve(_.projectRoot,$.target.filePath),W=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(W===null)return null;let z=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(z===null)return null;return _.semanticLayer.isTypeAssignableTo(J,W,Q,z)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function J$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function Q$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function W$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getResolvedTypesAtPositions failed",{cause:Q})}}function z$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:Q})}}function Z$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:Q})}}function Y$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getImplementationsAtPosition failed",{cause:Q})}}function X$(_,$,J,Q,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P.isAbsolute($)?$:P.resolve(_.projectRoot,$),Y=P.isAbsolute(Q)?Q:P.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(z,J,Y,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:z})}}function U$(_,$,J,Q,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(z,J,Q,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: isTypeAssignableToType failed",{cause:z})}}function V$(_,$,J,Q,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(z,J,Q,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:z})}}function O$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(W,J,Q)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: lineColumnToPosition failed",{cause:W})}}function H$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(W,J,Q)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: findNamePosition failed",{cause:W})}}function M$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSymbolNode failed",{cause:Q})}}function K$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSemanticDiagnostics failed",{cause:Q})}}function B$(_,$){let J=new Map(_.map((Z)=>[`${Z.name}::${Z.filePath}`,Z])),Q=new Map($.map((Z)=>[`${Z.name}::${Z.filePath}`,Z])),W=[],z=[],Y=[];for(let[Z,X]of Q){let K=J.get(Z);if(!K)W.push(X);else if(K.fingerprint!==X.fingerprint)Y.push({before:K,after:X})}for(let[Z,X]of J)if(!Q.has(Z))z.push(X);return{added:W,removed:z,modified:Y}}function L$(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function w$(_){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.coordinator)throw new O("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return z0(_),$}catch($){if($ instanceof O)throw $;throw new O("index","Gildash: reindex failed",{cause:$})}}function D$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");let W=Q??_.defaultProject,z=new Set,Y=[],Z=$,X=J;for(;;){let K=`${X}::${Z}`;if(z.has(K))return{originalName:Z,originalFilePath:X,reExportChain:Y,circular:!0};z.add(K);let V=_.relationSearchFn({relationRepo:_.relationRepo,project:W,query:{type:"re-exports",srcFilePath:X,limit:500}}),B,C;for(let N of V){let w;if(N.metaJson)try{let T=JSON.parse(N.metaJson);if(Array.isArray(T.specifiers))w=T.specifiers}catch{}if(!w)continue;let S=w.find((T)=>T.exported===Z);if(!S)continue;B=N.dstFilePath??void 0,C=S.local;break}if(!B||!C)return{originalName:Z,originalFilePath:X,reExportChain:Y,circular:!1};Y.push({filePath:X,exportedAs:Z}),X=B,Z=C}}function I$(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function C$(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function A$(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function q$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,W=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((z)=>z.filePath);return await _.patternSearchFn({pattern:$,filePaths:W})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: findPattern failed",{cause:Q})}}async function N$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let W=Q??_.defaultProject,z=new Set,Y=(Z,X,K)=>{let V=`${Z}::${X}`;if(z.has(V))return{symbolName:Z,filePath:X,kind:K,children:[]};z.add(V);let N=_.relationSearchFn({relationRepo:_.relationRepo,project:W,query:{srcFilePath:X,srcSymbolName:Z,limit:1000}}).filter((w)=>w.type==="extends"||w.type==="implements").filter((w)=>w.dstSymbolName!=null&&w.dstFilePath!=null).map((w)=>Y(w.dstSymbolName,w.dstFilePath,w.type));return{symbolName:Z,filePath:X,kind:K,children:N}};return Y($,J)}catch(W){if(W instanceof O)throw W;throw new O("search","Gildash: getHeritageChain failed",{cause:W})}}function R$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function S$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,W=J?.project??_.defaultProject,z=J?.limit??1000;return _.changelogRepo.getSince({project:W,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:z}).map((Z)=>({changeType:Z.changeType,symbolName:Z.symbolName,symbolKind:Z.symbolKind,filePath:Z.filePath,oldName:Z.oldName,oldFilePath:Z.oldFilePath,fingerprint:Z.fingerprint,changedAt:Z.changedAt,isFullIndex:Z.isFullIndex===1,indexRunId:Z.indexRunId}))}function G$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,W=[_.defaultProject,..._.boundaries.map((Y)=>Y.project)],z=[...new Set(W)];for(let Y of z)Q+=_.changelogRepo.pruneOlderThan(Y,J);return Q}class y0{_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 g1(_);return new y0($)}async close(_){return Z0(this._ctx,_)}parseSource(_,$,J){return E1(this._ctx,_,$,J)}async batchParse(_,$){return u1(this._ctx,_,$)}getParsedAst(_){return v1(this._ctx,_)}extractSymbols(_){return b1(this._ctx,_)}extractRelations(_){return P1(this._ctx,_)}getStats(_){return y1(this._ctx,_)}searchSymbols(_){return f0(this._ctx,_)}searchRelations(_){return x1(this._ctx,_)}searchAllSymbols(_){return h1(this._ctx,_)}searchAllRelations(_){return m1(this._ctx,_)}listIndexedFiles(_){return n1(this._ctx,_)}getInternalRelations(_,$){return d1(this._ctx,_,$)}getFullSymbol(_,$,J){return p1(this._ctx,_,$,J)}getFileStats(_,$){return i1(this._ctx,_,$)}getFileInfo(_,$){return l1(this._ctx,_,$)}getSymbolsByFile(_,$){return c1(this._ctx,_,$)}getModuleInterface(_,$){return a1(this._ctx,_,$)}getDependencies(_,$,J=1e4){return I1(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return C1(this._ctx,_,$,J)}async getAffected(_,$){return A1(this._ctx,_,$)}async hasCycle(_){return q1(this._ctx,_)}async getImportGraph(_){return N1(this._ctx,_)}async getTransitiveDependencies(_,$){return R1(this._ctx,_,$)}async getTransitiveDependents(_,$){return S1(this._ctx,_,$)}async getCyclePaths(_,$){return G1(this._ctx,_,$)}async getFanMetrics(_,$){return F1(this._ctx,_,$)}getResolvedType(_,$,J){return s1(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return r1(this._ctx,_,$,J)}getImplementations(_,$,J){return o1(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,W){return t1(this._ctx,_,$,J,Q,W)}getSemanticModuleInterface(_){return J$(this._ctx,_)}getFileTypes(_){return e1(this._ctx,_)}getResolvedTypeAt(_,$,J){return _$(this._ctx,_,$,J)}isTypeAssignableToAt(_){return $$(this._ctx,_)}getResolvedTypeAtPosition(_,$){return z$(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return W$(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return Z$(this._ctx,_,$)}getImplementationsAtPosition(_,$){return Y$(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return X$(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return U$(this._ctx,_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return V$(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return O$(this._ctx,_,$,J)}findNamePosition(_,$,J){return H$(this._ctx,_,$,J)}getSymbolNode(_,$){return M$(this._ctx,_,$)}getBaseTypes(_,$){return Q$(this._ctx,_,$)}getSemanticDiagnostics(_,$){return K$(this._ctx,_,$)}diffSymbols(_,$){return B$(_,$)}onIndexed(_){return L$(this._ctx,_)}async reindex(){return w$(this._ctx)}resolveSymbol(_,$,J){return D$(this._ctx,_,$,J)}async findPattern(_,$){return q$(this._ctx,_,$)}async getHeritageChain(_,$,J){return N$(this._ctx,_,$,J)}onFileChanged(_){return I$(this._ctx,_)}onError(_){return C$(this._ctx,_)}onRoleChanged(_){return A$(this._ctx,_)}searchAnnotations(_){return R$(this._ctx,_)}getSymbolChanges(_,$){return S$(this._ctx,_,$)}pruneChangelog(_){return G$(this._ctx,_)}}import{Visitor as A5,visitorKeys as q5}from"oxc-parser";import{walk as R5,parseAndWalk as S5,ScopeTracker as G5}from"oxc-walker";export{R5 as walk,q5 as visitorKeys,S0 as symbolSearch,G0 as relationSearch,F0 as patternSearch,g_ as parseSource,S5 as parseAndWalk,J_ as normalizePath,jJ as isVariableDeclaration,TJ as isTSQualifiedName,FJ as isMemberExpression,GJ as isIdentifier,CJ as isFunctionNode,SJ as isFunctionExpression,RJ as isFunctionDeclaration,NJ as isCallExpression,qJ as isAssignmentExpression,AJ as isArrowFunctionExpression,U_ as getLineColumn,q_ as extractSymbols,m_ as extractRelations,h_ as buildLineOffsets,A5 as Visitor,G5 as ScopeTracker,O as GildashError,y0 as Gildash,W0 as DependencyGraph};
|
|
2
|
+
var y$=Object.defineProperty;var x$=(_)=>_;function h$(_,$){this[_]=x$.bind(null,$)}var m$=(_,$)=>{for(var J in $)y$(_,J,{get:$[J],enumerable:!0,configurable:!0,set:h$.bind($,J)})};var h0=import.meta.require;import{isErr as i_}from"@zipbul/result";import b_ from"path";import{existsSync as TQ}from"fs";import{err as m0,isErr as c$}from"@zipbul/result";import{Database as a$}from"bun:sqlite";import{mkdirSync as s$,unlinkSync as n0,existsSync as d0}from"fs";import{dirname as r$,join as p0}from"path";import{drizzle as o$}from"drizzle-orm/bun-sqlite";import{migrate as t$}from"drizzle-orm/bun-sqlite/migrator";class O extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var C_=".gildash",c_="gildash.db";var V0={};m$(V0,{watcherOwner:()=>i$,symbols:()=>y,symbolChangelog:()=>__,relations:()=>E,files:()=>r,annotations:()=>Y_});import{sql as n$}from"drizzle-orm";import{sqliteTable as F_,text as P,integer as s,real as d$,index as J_,primaryKey as p$,foreignKey as U0,check as l$}from"drizzle-orm/sqlite-core";var r=F_("files",{project:P("project").notNull(),filePath:P("file_path").notNull(),mtimeMs:d$("mtime_ms").notNull(),size:s("size").notNull(),contentHash:P("content_hash").notNull(),updatedAt:P("updated_at").notNull(),lineCount:s("line_count")},(_)=>[p$({columns:[_.project,_.filePath]})]),y=F_("symbols",{id:s("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),filePath:P("file_path").notNull(),kind:P("kind").notNull(),name:P("name").notNull(),startLine:s("start_line").notNull(),startColumn:s("start_column").notNull(),endLine:s("end_line").notNull(),endColumn:s("end_column").notNull(),isExported:s("is_exported").notNull().default(0),signature:P("signature"),fingerprint:P("fingerprint"),detailJson:P("detail_json"),contentHash:P("content_hash").notNull(),indexedAt:P("indexed_at").notNull(),resolvedType:P("resolved_type"),structuralFingerprint:P("structural_fingerprint")},(_)=>[J_("idx_symbols_project_file").on(_.project,_.filePath),J_("idx_symbols_project_kind").on(_.project,_.kind),J_("idx_symbols_project_name").on(_.project,_.name),J_("idx_symbols_fingerprint").on(_.project,_.fingerprint),U0({columns:[_.project,_.filePath],foreignColumns:[r.project,r.filePath]}).onDelete("cascade")]),E=F_("relations",{id:s("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),type:P("type").notNull(),srcFilePath:P("src_file_path").notNull(),srcSymbolName:P("src_symbol_name"),dstProject:P("dst_project"),dstFilePath:P("dst_file_path"),dstSymbolName:P("dst_symbol_name"),metaJson:P("meta_json"),specifier:P("specifier"),isExternal:s("is_external").notNull().default(0)},(_)=>[J_("idx_relations_src").on(_.project,_.srcFilePath),J_("idx_relations_dst").on(_.dstProject,_.dstFilePath),J_("idx_relations_type").on(_.project,_.type),J_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),J_("idx_relations_specifier").on(_.project,_.specifier),U0({columns:[_.project,_.srcFilePath],foreignColumns:[r.project,r.filePath]}).onDelete("cascade")]),Y_=F_("annotations",{id:s("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),filePath:P("file_path").notNull(),tag:P("tag").notNull(),value:P("value").notNull().default(""),source:P("source").notNull(),symbolName:P("symbol_name"),startLine:s("start_line").notNull(),startColumn:s("start_column").notNull(),endLine:s("end_line").notNull(),endColumn:s("end_column").notNull(),indexedAt:P("indexed_at").notNull()},(_)=>[J_("idx_annotations_project_file").on(_.project,_.filePath),J_("idx_annotations_project_tag").on(_.project,_.tag),J_("idx_annotations_project_symbol").on(_.project,_.symbolName),U0({columns:[_.project,_.filePath],foreignColumns:[r.project,r.filePath]}).onDelete("cascade")]),__=F_("symbol_changelog",{id:s("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),changeType:P("change_type").notNull(),symbolName:P("symbol_name").notNull(),symbolKind:P("symbol_kind").notNull(),filePath:P("file_path").notNull(),oldName:P("old_name"),oldFilePath:P("old_file_path"),fingerprint:P("fingerprint"),changedAt:P("changed_at").notNull(),isFullIndex:s("is_full_index").notNull().default(0),indexRunId:P("index_run_id").notNull()},(_)=>[J_("idx_changelog_project_changed_at").on(_.project,_.changedAt),J_("idx_changelog_project_name").on(_.project,_.symbolName),J_("idx_changelog_project_run").on(_.project,_.indexRunId)]),i$=F_("watcher_owner",{id:s("id").primaryKey(),pid:s("pid").notNull(),startedAt:P("started_at").notNull(),heartbeatAt:P("heartbeat_at").notNull(),instanceId:P("instance_id")},(_)=>[l$("watcher_owner_singleton",n$`${_.id} = 1`)]);class O0{client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=p0(_.projectRoot,C_,c_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{s$(r$(this.dbPath),{recursive:!0}),this.client=new a$(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=o$(this.client,{schema:V0}),t$(this.drizzle,{migrationsFolder:p0(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(_)&&d0(this.dbPath)){this.closeClient(),n0(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(d0(Q))n0(Q)}let $=this.open();if(c$($))return m0(new O("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return m0(new O("store",`Failed to open database at ${this.dbPath}`,{cause:_}))}}close(){this.closeClient(),this.drizzle=null}transaction(_){let $=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return $.transaction(()=>_(this))()}finally{this.txDepth--}}let J=`sp_${this.txDepth++}`;$.run(`SAVEPOINT "${J}"`);try{let Q=_(this);return $.run(`RELEASE SAVEPOINT "${J}"`),Q}catch(Q){throw $.run(`ROLLBACK TO SAVEPOINT "${J}"`),$.run(`RELEASE SAVEPOINT "${J}"`),Q}finally{this.txDepth--}}immediateTransaction(_){let $=this.requireClient();this.txDepth++,$.run("BEGIN IMMEDIATE");try{let J=_();return $.run("COMMIT"),J}catch(J){throw $.run("ROLLBACK"),J}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(($)=>$.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}replaceOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}touchOwner(_){let $=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run($,_)}deleteOwner(_){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(_)}registerRegexpUdf(_){let $=_;if(typeof $.function!=="function")return;$.function.call(_,"regexp",(J,Q)=>{try{return new RegExp(J).test(Q)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(_){if(!(_ instanceof Error))return!1;let $=_.message.toLowerCase();return $.includes("malformed")||$.includes("corrupt")||$.includes("not a database")||$.includes("disk i/o error")||$.includes("sqlite_corrupt")}}import{eq as f_,and as l0}from"drizzle-orm";class H0{db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(r).where(l0(f_(r.project,_),f_(r.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(r).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[r.project,r.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(r).where(f_(r.project,_)).all()}getFilesMap(_){let $=this.getAllFiles(_),J=new Map;for(let Q of $)J.set(Q.filePath,Q);return J}deleteFile(_,$){this.db.drizzleDb.delete(r).where(l0(f_(r.project,_),f_(r.filePath,$))).run()}}import{eq as o,and as q_,sql as a_,count as e$}from"drizzle-orm";function j_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var i0=50;class M0{db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(y).where(q_(o(y.project,_),o(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+=i0)this.db.drizzleDb.insert(y).values(W.slice(Z,Z+i0)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(y).where(q_(o(y.project,_),o(y.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=j_($);if(!z)return[];return this.db.drizzleDb.select().from(y).where(q_(a_`${y.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,o(y.project,_),J.kind?o(y.kind,J.kind):void 0)).orderBy(y.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(y).where(q_(o(y.project,_),o(y.kind,$))).orderBy(y.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:e$(),fileCount:a_`COUNT(DISTINCT ${y.filePath})`}).from(y).where(o(y.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(y).where(q_(o(y.project,_),o(y.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(y).where(q_(o(y.project,_),o(y.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(y).where(q_(_.ftsQuery?a_`${y.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?o(y.name,_.exactName):void 0,_.project!==void 0?o(y.project,_.project):void 0,_.kind?o(y.kind,_.kind):void 0,_.filePath!==void 0?o(y.filePath,_.filePath):void 0,_.isExported!==void 0?o(y.isExported,_.isExported?1:0):void 0,_.decorator?a_`${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?o(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 O("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((W)=>J.test(W.name));let Q=[];for(let z of[5,20,100]){let W=_.limit*z,Z=$.limit(W).all();if(Q=Z.filter((Y)=>J.test(Y.name)),Q.length>=_.limit||Z.length<W)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as m,and as M_,isNull as c0,or as _J}from"drizzle-orm";var y_={project:E.project,type:E.type,srcFilePath:E.srcFilePath,srcSymbolName:E.srcSymbolName,dstProject:E.dstProject,dstFilePath:E.dstFilePath,dstSymbolName:E.dstSymbolName,metaJson:E.metaJson,specifier:E.specifier,isExternal:E.isExternal};class K0{db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(E).where(M_(m(E.project,_),m(E.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(E).values({project:_,type:z.type??"unknown",srcFilePath:z.srcFilePath??$,srcSymbolName:z.srcSymbolName??null,dstProject:z.dstProject??(z.dstFilePath!=null?_:null),dstFilePath:z.dstFilePath??null,dstSymbolName:z.dstSymbolName??null,metaJson:z.metaJson??null,specifier:z.specifier??null,isExternal:z.isExternal??0}).run()})}getOutgoing(_,$,J){if(J!==void 0)return this.db.drizzleDb.select(y_).from(E).where(M_(m(E.project,_),m(E.srcFilePath,$),_J(m(E.srcSymbolName,J),c0(E.srcSymbolName)))).all();return this.db.drizzleDb.select(y_).from(E).where(M_(m(E.project,_),m(E.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(y_).from(E).where(M_(m(E.dstProject,$),m(E.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(y_).from(E).where(M_(m(E.project,_),m(E.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(E).where(M_(m(E.project,_),m(E.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(E).where(M_(m(E.dstProject,_),m(E.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(y_).from(E).where(M_(_.project!==void 0?m(E.project,_.project):void 0,_.srcFilePath!==void 0?m(E.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?m(E.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?m(E.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?m(E.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?m(E.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?m(E.type,_.type):void 0,_.specifier!==void 0?m(E.specifier,_.specifier):void 0,_.isExternal!==void 0?m(E.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:W,newDstProject:Z}=_,Y=Q===null?M_(m(E.dstProject,$),m(E.dstFilePath,J),c0(E.dstSymbolName)):M_(m(E.dstProject,$),m(E.dstFilePath,J),m(E.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:W};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(E).set(X).where(Y).run()}}import{err as s0}from"@zipbul/result";import{subscribe as $J}from"@parcel/watcher";import L0 from"path";import a0 from"path";function Q_(_){return _.replaceAll("\\","/")}function x_(_,$){return Q_(a0.relative(_,$))}function g_(_,$){return Q_(a0.resolve(_,$))}var JJ=["**/.git/**",`**/${C_}/**`,"**/dist/**","**/node_modules/**"],QJ=new Set(["package.json","tsconfig.json"]);function zJ(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class B0{#_;#$;#J;#W;#z;#Y;constructor(_,$=$J,J=console){this.#$=_.projectRoot,this.#J=[...JJ,..._.ignorePatterns??[]],this.#W=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#z=$,this.#Y=J}async start(_){try{this.#_=await this.#z(this.#$,($,J)=>{if($){this.#Y.error(new O("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=Q_(L0.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let W=L0.basename(z),Z=L0.extname(z).toLowerCase();if(!QJ.has(W)&&!this.#W.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:zJ(Q.type),filePath:z})}}catch(Q){this.#Y.error(new O("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return s0(new O("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return s0(new O("watcher","Failed to close watcher",{cause:_}))}}}import w0 from"path";var WJ=["**/node_modules/**","**/.git/**",`**/${C_}/**`,"**/dist/**"],YJ=WJ.map((_)=>new Bun.Glob(_));function ZJ(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function s_(_,$=ZJ){let J=[];for await(let Q of $(_)){let z=Q_(Q);if(YJ.some((K)=>K.match(z)))continue;let W=Q_(w0.dirname(Q)),Z=w0.join(_,Q),Y=await Bun.file(Z).json(),X=typeof Y?.name==="string"&&Y.name.length>0?Y.name:w0.basename(W==="."?_:W);J.push({dir:W,project:X})}return J.sort((Q,z)=>z.dir.length-Q.dir.length),J}function c(_,$,J="default"){let Q=Q_(_);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 A_=new Map;async function XJ(_){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 UJ(_,$){if($.startsWith(".")){let J=h_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return h_.resolve(_,"node_modules",$)}async function r0(_,$=5){if($<=0)return null;let J=await XJ(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=UJ(h_.dirname(_),Q),W=await r0(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 m_(_){if(A_.has(_))return A_.get(_)??null;let $=h_.join(_,"tsconfig.json"),J=await r0($);if(!J)return A_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return A_.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 A_.set(_,null),null;let Z=z?h_.resolve(_,z):_,Y=new Map;if(W)for(let[K,V]of Object.entries(W)){if(!Array.isArray(V))continue;let L=V.filter((C)=>typeof C==="string");Y.set(K,L)}let X={baseUrl:Z,paths:Y};return A_.set(_,X),X}function r_(_){if(_){A_.delete(_);return}A_.clear()}function O_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as Z1}from"@zipbul/result";import{err as VJ}from"@zipbul/result";import{parseSync as OJ}from"oxc-parser";function k_(_,$,J,Q=OJ){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 VJ(new O("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{join as HJ}from"path";function MJ(_,$){let J=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(J).scan({cwd:_,followSymlinks:!1})}async function o0(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z,scanFilesFn:W=MJ}=_,Z=z.getFilesMap(),Y=new Set,X=[],K=[],V=Q.map((C)=>new Bun.Glob(C));for await(let C of W($,J)){let N=Q_(C);if(!J.some((p)=>N.endsWith(p)))continue;if(N.startsWith("node_modules/")||N.includes("/node_modules/"))continue;if(V.some((p)=>p.match(N)))continue;Y.add(N);let w=HJ($,N),T=Bun.file(w),{size:F,lastModified:S}=T,v=Z.get(N);if(!v){let p=await T.text(),l=O_(p);X.push({filePath:N,contentHash:l,mtimeMs:S,size:F});continue}if(v.mtimeMs===S&&v.size===F){K.push({filePath:N,contentHash:v.contentHash,mtimeMs:S,size:F});continue}let u=await T.text(),x=O_(u);if(x===v.contentHash)K.push({filePath:N,contentHash:x,mtimeMs:S,size:F});else X.push({filePath:N,contentHash:x,mtimeMs:S,size:F})}let L=[];for(let C of Z.keys())if(!Y.has(C))L.push(C);return{changed:X,unchanged:K,deleted:L}}function n_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
|
|
3
|
+
`)$.push(J+1);return $}function V_(_,$){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 KJ}from"@zipbul/result";import{parse as LJ}from"comment-parser";function o_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=LJ(`/** ${$} */`)[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 KJ(new O("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as BJ}from"@zipbul/result";function wJ(_){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 IJ(_){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 N_(_){let{program:$,sourceText:J,comments:Q}=_,z=n_(J),W=IJ(_),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 S(D,q)}function K(D,q,U){if(D.type==="PrivateIdentifier")return{kind:"private"};if(!q&&D.type==="Identifier")return;return X(D,U)}function V(D,q){if(q)return J.slice(D.start,D.end);if(D.type==="PrivateIdentifier")return`#${D.name}`;return wJ(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:V_(z,D),end:V_(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 M=Z[H];q=0,U=Y.length-1;while(q<=U){let B=q+U>>>1,A=Y[B];if(A<=M.end)q=B+1;else if(A>=D)U=B-1;else return}return`/*${M.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 T=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 S(D,q=0){let U=D;if(q>=T)return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)};let H=U.type;if(H==="Literal"){let M=U.value;if(typeof M==="bigint")return{kind:"bigint",value:typeof U.bigint==="string"?U.bigint:M.toString()};if(typeof U.regex==="object"&&U.regex!==null)return{kind:"regex",value:J.slice(U.start,U.end)};if(M===null)return{kind:"null",value:null};if(typeof M==="string")return{kind:"string",value:M};if(typeof M==="number")return{kind:"number",value:M};if(typeof M==="boolean")return{kind:"boolean",value:M};return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}if(H==="Identifier"){let M=U.name;if(M==="undefined")return{kind:"undefined",value:null};let B=W.get(M),A={kind:"identifier",name:M};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 k=U.object,b=J.slice(k.start,k.end),d=k.type==="Identifier"?k.name:void 0,$_=d?W.get(d):void 0,U_={kind:"member",object:b,property:j.value};if($_)U_.importSource=$_.specifier;return U_}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}let M=U.object,B=J.slice(M.start,M.end),A=U.property.name??J.slice(U.property.start,U.property.end),I=M.type==="Identifier"?M.name:void 0,G=I?W.get(I):void 0,R={kind:"member",object:B,property:A};if(G)R.importSource=G.specifier;return R}if(H==="CallExpression"){let M=U.callee,B=J.slice(M.start,M.end),I=(U.arguments??[]).map((j)=>S(j,q+1)),G=F(M),R={kind:"call",callee:B,arguments:I};if(G)R.importSource=G.specifier;return R}if(H==="NewExpression"){let M=U.callee,B=J.slice(M.start,M.end),I=(U.arguments??[]).map((j)=>S(j,q+1)),G=F(M),R={kind:"new",callee:B,arguments:I};if(G)R.importSource=G.specifier;return R}if(H==="ObjectExpression"){let M=U.properties??[],B=[];for(let A of M){if(A.type==="SpreadElement"){let d=A.argument;B.push({kind:"spread",argument:S(d,q+1)});continue}let I=A.key,G=A.computed===!0,R=A.value,j=A.shorthand||void 0,b={kind:"property",key:L(I,G,q+1),value:S(R,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 S(A,q+1)})};if(H==="SpreadElement"){let M=U.argument;return{kind:"spread",argument:S(M,q+1)}}if(H==="ArrowFunctionExpression"||H==="FunctionExpression"){let B=U.params.map(u),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:M,argument:B}=U;if(M==="-"&&B.type==="Literal"&&typeof B.value==="number")return{kind:"number",value:-B.value};if(M==="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 M=U.expression;if(M)return S(M,q)}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}function v(D){if(!D||D.length===0)return[];return D.map((q)=>{let U=q.expression;if(U.type==="CallExpression"){let H=U,M=H.callee,B="name"in M&&typeof M.name==="string"?M.name:("property"in M)&&M.property&&typeof M.property.name==="string"?M.property.name:"unknown",A=H.arguments.map((I)=>S(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 u(D){if(D.type==="TSParameterProperty"){let U=D;return p(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,G={name:B,isOptional:!1};if(I)G.type=I;return G}let q=D;return p(q,q.decorators)}function x(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 p(D,q){if(D.type==="AssignmentPattern"){let{left:R,right:j}=D,k="name"in R&&typeof R.name==="string"?R.name:"unknown",b="typeAnnotation"in R?R.typeAnnotation:null,d=b?w(b):void 0,$_=x(b),U_=J.slice(j.start,j.end),L_="decorators"in R&&Array.isArray(R.decorators)?R.decorators:[],X0=v(L_),D_={name:k,isOptional:!0,defaultValue:U_};if(d)D_.type=d;if($_)D_.typeImportSource=$_;if(X0.length>0)D_.decorators=X0;return D_}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),M="typeAnnotation"in D?D.typeAnnotation:null,B=M?w(M):void 0,A=x(M),I=v(q??[]),G={name:U,isOptional:H};if(B)G.type=B;if(A)G.typeImportSource=A;if(I.length>0)G.decorators=I;return G}function l(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 z_(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 Z_(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 M=H.expression,B=J.slice(M.start,M.end);q.push({kind:"implements",name:B})}return q}function H_(D){let q=[],U=D.extends;for(let H of U){let M=H.expression,B=J.slice(M.start,M.end);q.push({kind:"extends",name:B})}return q}function X_(D){let q=[];for(let U of D)if(U.type==="MethodDefinition"||U.type==="TSAbstractMethodDefinition"){let H=U,M=V(H.key,H.computed),B=K(H.key,H.computed,0),A=H.value,I=H.kind,G=I==="constructor"?"constructor":I==="get"?"getter":I==="set"?"setter":"method",R=l(H,A);if(U.type==="TSAbstractMethodDefinition"&&!R.includes("abstract"))R.push("abstract");let j=A.params.map(u),k=w(A.returnType),b=v(H.decorators??[]),d={kind:"method",name:M,span:C(U.start,U.end),isExported:!1,methodKind:G,modifiers:R,parameters:j.length>0?j:void 0,returnType:k};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,M=V(H.key,H.computed),B=K(H.key,H.computed,0),A=l(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),G=H.value,R=G?S(G):void 0,j=v(H.decorators??[]),k={kind:"property",name:M,span:C(U.start,U.end),isExported:!1,modifiers:A,returnType:I,initializer:R};if(B)k.key=B;if(j.length>0)k.decorators=j;q.push(k)}return q}function W_(D){let q=[];for(let U of D)if(U.type==="TSMethodSignature"){let H=U,M=V(H.key,H.computed),B=K(H.key,H.computed,0),A=H.params.map(u),I=w(H.returnType),G={kind:"method",name:M,span:C(U.start,U.end),isExported:!1,modifiers:[],methodKind:"method",parameters:A.length>0?A:void 0,returnType:I};if(B)G.key=B;q.push(G)}else if(U.type==="TSPropertySignature"){let H=U,M=V(H.key,H.computed),B=K(H.key,H.computed,0),A=w(H.typeAnnotation),I={kind:"property",name:M,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 i(D,q){let U=D.type;if(U==="FunctionDeclaration"||U==="FunctionExpression"||U==="TSDeclareFunction"||U==="TSEmptyBodyFunctionExpression"){let H=D,M=H.id?.name??"default",B=H.params.map(u),A=w(H.returnType),I=l(H,H),G=v(H.decorators??[]),R=z_(H.typeParameters),j={kind:"function",name:M,span:C(D.start,D.end),isExported:q,modifiers:I,parameters:B.length>0?B:void 0,returnType:A,decorators:G.length>0?G:void 0};if(R&&R.length>0)j.typeParameters=R;return j}if(U==="ClassDeclaration"||U==="ClassExpression"){let H=D,M=H.id?.name??"default",B=Z_(H),A=X_(H.body.body),I=v(H.decorators),G=l(H),R=z_(H.typeParameters),j={kind:"class",name:M,span:C(D.start,D.end),isExported:q,modifiers:G,heritage:B.length>0?B:void 0,members:A.length>0?A:void 0,decorators:I.length>0?I:void 0};if(R&&R.length>0)j.typeParameters=R;return j}if(U==="VariableDeclaration"){let H=D,M=[];for(let B of H.declarations){let{id:A,init:I}=B;if(A.type==="ObjectPattern"||A.type==="ArrayPattern"){let U_=E_(A);for(let L_ of U_)M.push({kind:"variable",name:L_.name,span:C(L_.start,L_.end),isExported:q,modifiers:[]});continue}let G="name"in A&&typeof A.name==="string"?A.name:"unknown",R="variable",j,k,b;if(I)if(I.type==="FunctionExpression"||I.type==="ArrowFunctionExpression"){R="function";let U_=I;j=U_.params.map(u),k=w(U_.returnType)}else b=S(I);let d=[],$_={kind:R,name:G,span:C(B.start,B.end),isExported:q,modifiers:d,parameters:j,returnType:k};if(b)$_.initializer=b;M.push($_)}if(M.length===0)return null;if(M.length===1)return M[0];return M}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,M=H.id.name,B=H_(H),A=W_(H.body.body),I=z_(H.typeParameters),G={kind:"interface",name:M,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)G.typeParameters=I;return G}if(U==="TSEnumDeclaration"){let H=D,M=H.id.name,B=l(H),I=H.body.members.map((G)=>{let R=G.id,j=R.type!=="Identifier",k="name"in R&&typeof R.name==="string"?R.name:("value"in R)&&typeof R.value==="string"?R.value:"unknown",b=G.initializer?S(G.initializer):void 0,d={kind:"property",name:k,span:C(G.start,G.end),isExported:!1,modifiers:[]};if(j)d.key=X(R,0);if(b)d.initializer=b;return d});return{kind:"enum",name:M,span:C(D.start,D.end),isExported:q,modifiers:B,members:I.length>0?I:void 0}}if(U==="TSModuleDeclaration"){let H=D,M=H.id.name??H.id.value??"unknown",B=l(H),A=[];if(H.body?.type==="TSModuleBlock")for(let I of H.body.body??[]){if(I.type!=="ExportNamedDeclaration")continue;let G=I.declaration;if(!G)continue;let R=i(G,!1);if(R)if(Array.isArray(R))A.push(...R);else A.push(R)}return{kind:"namespace",name:M,span:C(D.start,D.end),isExported:q,modifiers:B,members:A.length>0?A:void 0}}return null}let a=[],I_=new Set;for(let D of $.body){let q=null,U=D;if(U.type==="ExportNamedDeclaration"){let M=U;if(M.declaration){if(q=i(M.declaration,!0),q&&!Array.isArray(q))q.span=C(M.start,M.end)}else if(!M.source&&M.specifiers)for(let B of M.specifiers){let A=B.local,I="name"in A?A.name:A.value;if(I)I_.add(I)}}else if(U.type==="ExportDefaultDeclaration"){let M=U,B=M.declaration;if(B){if(q=i(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(M.start,M.end);else if(!q&&"type"in B&&B.type==="Identifier"){let A=B.name;if(A)I_.add(A)}}}else{let M=U.type;if(M==="FunctionDeclaration"||M==="TSDeclareFunction"||M==="ClassDeclaration"||M==="VariableDeclaration"||M==="TSTypeAliasDeclaration"||M==="TSInterfaceDeclaration"||M==="TSEnumDeclaration"||M==="TSModuleDeclaration")q=i(U,!1)}let H=Array.isArray(q)?q:q?[q]:[];for(let M of H){let B=D.start,A=N(B);if(A){let I=o_(A);if(!BJ(I))M.jsDoc=I}a.push(M)}}if(I_.size>0){for(let D of a)if(!D.isExported&&I_.has(D.name))D.isExported=!0}return a}function t_(_){if(_===null||typeof _!=="object")return JSON.stringify(_);if(Array.isArray(_))return`[${_.map(t_).join(",")}]`;let $=_;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${t_($[Q])}`).join(",")}}`}function DJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function CJ(_){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 AJ(_){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:${t_(_.key)}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}:${Q.key?t_(Q.key):""}`).sort().join(";");$.push(`mem:${_.members.length}:${O_(J)}`)}return O_($.join("|"))}function t0(_,$,J,Q,z){let W=DJ(_),Z=O_(`${$}|${_.kind}|${W??""}`),Y=AJ(_);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:CJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:Y}}function I0(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:W}=_,Z=N_($),Y=[];for(let X of Z){Y.push(t0(X,X.name,J,Q,z));for(let K of X.members??[])Y.push(t0(K,`${X.name}.${K.name}`,J,Q,z))}W.replaceFileSymbols(J,Q,z,Y)}import{resolve as D0,dirname as qJ,extname as NJ}from"path";function R_(_,$,J){let Q=(z)=>{let W=NJ(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=Q_(D0(qJ(_),$));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(Q_(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 K=$.slice(Y.length,X===""?void 0:$.length-X.length),V=[];for(let L of W)V.push(...Q(Q_(D0(J.baseUrl,L.replace("*",K)))));return V}}}return[]}function e0(_,$,J,Q=R_){let z=new Map,W=_.body??[];for(let Z of W){if(Z.type!=="ImportDeclaration")continue;let Y=Z.source?.value??"",X=Q($,Y,J);if(X.length===0)continue;let K=X[0],V=Z.specifiers??[];for(let L of V)switch(L.type){case"ImportSpecifier":z.set(L.local.name,{path:K,importedName:L.imported.name});break;case"ImportDefaultSpecifier":z.set(L.local.name,{path:K,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(L.local.name,{path:K,importedName:"*"});break}}return z}import{Visitor as RJ}from"oxc-parser";function e_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function TJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function T_(_,$,J,Q){let z=Q(_,$,J),W=z.length>0?z[0]:null,Z=W===null&&TJ($);return{resolved:W,isExternal:Z}}function GJ(_,$,J,Q,z){for(let W of _.staticImports){let Z=W.moduleRequest.value,{resolved:Y,isExternal:X}=T_($,Z,J,Q),K={dstFilePath:Y,specifier:Z};if(W.entries.length===0){let V={};if(X)V.isExternal=!0;if(Y===null&&!X)V.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...K,dstSymbolName:null,...Object.keys(V).length>0?{metaJson:JSON.stringify(V)}:{}});continue}for(let V of W.entries){let L=V.isType,C={};if(L)C.isType=!0;if(X)C.isExternal=!0;if(Y===null&&!X)C.isUnresolved=!0;let N,w,T=V.importName.kind;if(T==="Default")N="default",w=V.localName.value;else if(T==="NamespaceObject")N="*",w=V.localName.value,C.importKind="namespace";else N=V.importName.name??"unknown",w=V.localName.value;z.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:w,...K,dstSymbolName:N,...Object.keys(C).length>0?{metaJson:JSON.stringify(C)}:{}})}}}function SJ(_,$,J,Q,z){let W=new Map;for(let Z of _.staticImports)for(let Y of Z.entries)W.set(Y.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let Y of Z.entries){let X=null;if(Y.moduleRequest)X=Y.moduleRequest.value;else if(Y.localName.name)X=W.get(Y.localName.name)??null;if(!X)continue;let{resolved:K,isExternal:V}=T_($,X,J,Q),L=Y.exportName.name??"default",C=Y.exportName.kind,N=Y.localName.name??Y.importName.name??L,w=Y.isType,T={isReExport:!0};if(C==="None");else T.specifiers=[{local:N,exported:L}];if(w)T.isType=!0;if(V)T.isExternal=!0;if(K===null&&!V)T.isUnresolved=!0;let F=null,S=null,v=Y.importName.kind;if(v==="All"||v==="AllButDefault"){if(C==="Name"&&L)S=L,T.namespaceAlias=L}else S=N,F=L;z.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:F,dstFilePath:K,dstSymbolName:S,specifier:X,metaJson:JSON.stringify(T)})}}function FJ(_,$,J,Q,z){for(let W of _.body){let Z=W;if(Z.type==="ImportDeclaration"){let Y=Z,X=Y.source.value,{resolved:K,isExternal:V}=T_($,X,J,Q),L=Y.importKind==="type",C=Y.specifiers,N={dstFilePath:K,specifier:X};if(C.length===0){let w={};if(L)w.isType=!0;if(V)w.isExternal=!0;if(K===null&&!V)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 T=w.type,F=L||T==="ImportSpecifier"&&w.importKind==="type",S={};if(F)S.isType=!0;if(V)S.isExternal=!0;if(K===null&&!V)S.isUnresolved=!0;let v,u;if(T==="ImportDefaultSpecifier")v="default",u=w.local.name;else if(T==="ImportNamespaceSpecifier")v="*",u=w.local.name,S.importKind="namespace";else v=e_(w.imported),u=w.local.name;z.push({type:F?"type-references":"imports",srcFilePath:$,srcSymbolName:u,...N,dstSymbolName:v,...Object.keys(S).length>0?{metaJson:JSON.stringify(S)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let Y=Z,X=Y.source.value,{resolved:K,isExternal:V}=T_($,X,J,Q),L=Y.exportKind==="type",C=Y.exported,N=C?e_(C):null,w={isReExport:!0};if(L)w.isType=!0;if(V)w.isExternal=!0;if(K===null&&!V)w.isUnresolved=!0;if(N)w.namespaceAlias=N;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,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:K,isExternal:V}=T_($,X,J,Q),L=Y.exportKind==="type",C=Y.specifiers??[];for(let N of C){let w=L||N.exportKind==="type",T=e_(N.local),F=e_(N.exported),S={isReExport:!0,specifiers:[{local:T,exported:F}]};if(w)S.isType=!0;if(V)S.isExternal=!0;if(K===null&&!V)S.isUnresolved=!0;z.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:F,dstFilePath:K,dstSymbolName:T,specifier:X,metaJson:JSON.stringify(S)})}}}}function jJ(_,$,J,Q,z){new RJ({ImportExpression(Z){let Y=Z.source;if(Y.type!=="Literal"||typeof Y.value!=="string")return;let X=Y.value,{resolved:K,isExternal:V}=T_($,X,J,Q),L={isDynamic:!0};if(V)L.isExternal=!0;if(K===null&&!V)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,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 T=Y,F=T.object,S=T.property;if(F.type==="Identifier"&&F.name==="require"&&S.name==="resolve")X=!0;else return}else return;let K=Z.arguments;if(K.length===0)return;let V=K[0];if(V.type!=="Literal"||typeof V.value!=="string")return;let L=V.value,{resolved:C,isExternal:N}=T_($,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 _1(_,$,J,Q=R_,z){let W=[];if(z)GJ(z,$,J,Q,W),SJ(z,$,J,Q,W);else FJ(_,$,J,Q,W);return jJ(_,$,J,Q,W),W}import{walk as mJ}from"oxc-walker";function gJ(_){return _.type==="FunctionDeclaration"||_.type==="FunctionExpression"||_.type==="ArrowFunctionExpression"}function kJ(_){return _.type==="ArrowFunctionExpression"}function EJ(_){return _.type==="AssignmentExpression"}function uJ(_){return _.type==="CallExpression"}function vJ(_){return _.type==="FunctionDeclaration"}function bJ(_){return _.type==="FunctionExpression"}function PJ(_){return _.type==="Identifier"}function fJ(_){return _.type==="MemberExpression"}function yJ(_){return _.type==="TSQualifiedName"}function xJ(_){return _.type==="VariableDeclaration"}var $1=new Map,hJ=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=$1.get($);if(z===void 0)z=(W)=>W!==null&&W!==void 0&&W.type===$,$1.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 J1(_,$,J){let Q=[],z=[],W=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function Y(V){if(!V)return null;let L=J.get(V.root);if(V.parts.length===0){if(L)return{dstFilePath:L.path,dstSymbolName:L.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:V.root,resolution:"local"}}else{if(L&&L.importedName==="*"){let C=V.parts[V.parts.length-1];return{dstFilePath:L.path,dstSymbolName:C,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:V.full,resolution:"local-member"}}}function X(V,L){let C=u_(V.callee),N=Y(C);if(N){let w=Z(),T={};if(L)T.isNew=!0;if(w===null)T.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:w,dstFilePath:N.dstFilePath,dstSymbolName:N.dstSymbolName,...Object.keys(T).length>0?{metaJson:JSON.stringify(T)}:{}})}}function K(V,L){if(V.type==="FunctionDeclaration"){z.push(V.id?.name??"anonymous");return}if(V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){if(L?.type==="VariableDeclarator"){let w=L.id,T=w.type==="Identifier"?w.name:"anonymous";z.push(T);return}if(L?.type==="MethodDefinition"||L?.type==="TSAbstractMethodDefinition"){let w=L.key,T=W[W.length-1]??"",F="name"in w?w.name:"anonymous",S=T?`${T}.${F}`:F;z.push(S);return}let C=Z(),N=C?`${C}.<anonymous>`:"<anonymous>";z.push(N)}}return mJ(_,{enter(V,L){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.push(V.id?.name??"AnonymousClass");return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){K(V,L);return}if(V.type==="CallExpression"){X(V,!1);return}if(V.type==="NewExpression"){X(V,!0);return}},leave(V){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.pop();return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as nJ}from"oxc-parser";function Q1(_,$,J){let Q=[];function z(Z){let Y=Z.id?.name??"AnonymousClass";if(Z.superClass){let K=u_(Z.superClass);if(K){let V=C0(K,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...V})}}let X=Z.implements??[];for(let K of X){let V=u_(K.expression);if(!V)continue;let L=C0(V,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Y,...L})}}return new nJ({TSInterfaceDeclaration(Z){let Y=Z.id.name??"AnonymousInterface",X=Z.extends;for(let K of X){let V=u_(K.expression);if(!V)continue;let L=C0(V,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...L})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).visit(_),Q}function C0(_,$,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=R_,z){let W=e0(_,$,J,Q),Z=_1(_,$,J,Q,z),Y=J1(_,$,W),X=Q1(_,$,W);return[...Z,...Y,...X]}function A0(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:W,tsconfigPaths:Z,knownFiles:Y,boundaries:X,module:K}=_,V=g_(W,Q),C=d_($,V,Z,Y?(w,T,F)=>{let S=R_(w,T,F);for(let v of S){let u=x_(W,v);if(X){let x=c(u,X);if(Y.has(`${x}::${u}`))return[v]}else if(Y.has(`${J}::${u}`))return[v]}return[]}:void 0,K),N=[];for(let w of C){if(w.dstFilePath===null){let v=x_(W,w.srcFilePath),u;if(w.metaJson)try{u=JSON.parse(w.metaJson)}catch{}let x=u?.isExternal===!0;N.push({project:J,type:w.type,srcFilePath:v,srcSymbolName:w.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:w.dstSymbolName??null,metaJson:w.metaJson??null,specifier:w.specifier??null,isExternal:x?1:0});continue}let T=x_(W,w.dstFilePath);if(T.startsWith(".."))continue;let F=x_(W,w.srcFilePath),S=X?c(T,X):J;N.push({project:J,type:w.type,srcFilePath:F,srcSymbolName:w.srcSymbolName??null,dstProject:S,dstFilePath:T,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 dJ}from"@zipbul/result";var z1=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function pJ(_){let $=N_(_),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 q0(_,$,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=V_(_,$),z=V_(_,J);return{start:Q,end:z}}function W1(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=n_(J),z=pJ(_),W=[],Z=[...$].sort((X,K)=>X.start-K.start),Y=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){Y=null;let K=`/*${X.value}*/`,V=o_(K);if(dJ(V))continue;let L=V;if(!L.tags?.length)continue;let C=V_(Q,X.end),N=q0(z,C.line,3),w=J.slice(X.start,X.end);for(let T of L.tags){let F=[T.name,T.description].filter(Boolean).join(" "),S=`@${T.tag}`,v=w.indexOf(S),u;if(v>=0){let x=X.start+v,p=J.indexOf(`
|
|
4
|
+
`,x),l=p>=0?Math.min(p,X.end):X.end;u=_0(Q,x,l)}else u=_0(Q,X.start,X.end);W.push({tag:T.tag,value:F,source:"jsdoc",span:u,symbolName:N})}}else if(X.type==="Block"){Y=null;let K=X.value.split(`
|
|
5
|
+
`),V=0;for(let L of K){let C=L.replace(/^\s*\*?\s?/,""),N=z1.exec(C);if(N){let w=N[1],T=N[2]?.trim()??"",F=`@${w}`,S=L.indexOf(F),v=X.start+2+V+(S>=0?S:0),u=X.start+2+V+L.length,x=_0(Q,v,u),p=V_(Q,X.end),l=q0(z,p.line,3);W.push({tag:w,value:T,source:"block",span:x,symbolName:l})}V+=L.length+1}}else{let K=X.value,V=z1.exec(K),L=V_(Q,X.start),C=V_(Q,X.end);if(V){let N=V[1],w=V[2]?.trim()??"",T=`@${N}`,F=K.indexOf(T),S=X.start+2+(F>=0?F:0),v=_0(Q,S,X.end),u=q0(z,C.line,3),x={tag:N,value:w,source:"line",span:v,symbolName:u};W.push(x),Y={annotation:x,endLine:C.line}}else if(Y&&L.line===Y.endLine+1){let N=K.trim();if(N)Y.annotation.value+=" "+N,Y.annotation.span.end=V_(Q,X.end),Y.endLine=C.line}else Y=null}return W}function N0(_){let{parsed:$,project:J,filePath:Q,annotationRepo:z}=_,W=W1($);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 Y1(_,$){let J=[],Q=[],z=[];for(let[V,L]of $)if(!_.has(V))J.push({name:L.name,filePath:L.filePath,kind:L.kind,fingerprint:L.fingerprint});for(let[V,L]of _)if(!$.has(V))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 V of J){let L=W.get(V.filePath)??[];L.push(V),W.set(V.filePath,L)}for(let V of Q){let L=Z.get(V.filePath)??[];L.push(V),Z.set(V.filePath,L)}let Y=new Set,X=new Set;for(let[V,L]of W){let C=Z.get(V);if(!C)continue;for(let N of new Set(L.map((w)=>w.kind))){let w=L.filter((u)=>u.kind===N&&!Y.has(u)),T=C.filter((u)=>u.kind===N&&!X.has(u));if(!w.length||!T.length)continue;let F=(u,x)=>{return x.get(`${u.filePath}::${u.name}`)?.structuralFingerprint??null},S=(u,x)=>{return x.get(`${u.filePath}::${u.name}`)?.startLine??0},v=new Map;for(let u of T){let x=F(u,_);if(!x)continue;let p=v.get(x)??[];p.push(u),v.set(x,p)}for(let u of w){if(Y.has(u))continue;let x=F(u,$);if(!x)continue;let p=v.get(x);if(!p)continue;let l=p.filter((Z_)=>!X.has(Z_));if(!l.length)continue;let z_=l[0];if(l.length>1){let Z_=S(u,$),H_=Math.abs(S(z_,_)-Z_);for(let X_=1;X_<l.length;X_++){let W_=Math.abs(S(l[X_],_)-Z_);if(W_<H_)H_=W_,z_=l[X_]}}z.push({oldName:z_.name,newName:u.name,filePath:V,kind:N}),Y.add(u),X.add(z_)}}}let K=z.filter((V)=>!V.oldName.includes("."));for(let V of K){let L=`${V.oldName}.`,C=`${V.newName}.`,N=Q.filter((T)=>T.filePath===V.filePath&&T.name.startsWith(L)&&!X.has(T)),w=J.filter((T)=>T.filePath===V.filePath&&T.name.startsWith(C)&&!Y.has(T));for(let T of N){let F=T.name.slice(L.length),S=w.find((v)=>v.name.slice(C.length)===F);if(S)z.push({oldName:T.name,newName:S.name,filePath:V.filePath,kind:T.kind}),Y.add(S),X.add(T)}}return{renamed:z,added:J.filter((V)=>!Y.has(V)),removed:Q.filter((V)=>!X.has(V))}}var lJ=100,X1=50;class R0{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=m_(_.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")){r_(this.opts.projectRoot),this.tsconfigPathsRaw=m_(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??s_;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()},lJ)}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 M of this.opts.boundaries)for(let[B,A]of Q.getFilesMap(M.project))U.set(B,A);let H=await o0({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>U}});Y=H.changed,X=H.deleted}let K=await this.tsconfigPathsRaw??void 0,V=new Map;for(let U of X){let H=c(U,this.opts.boundaries),M=z.getFileSymbols(H,U);V.set(U,M)}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 M of z.getFileSymbols(U.project,H.filePath))C.set(`${M.filePath}::${M.name}`,w(M));else{for(let U of Y){let H=c(U.filePath,this.opts.boundaries);for(let M of z.getFileSymbols(H,U.filePath))C.set(`${M.filePath}::${M.name}`,w(M))}for(let[,U]of V)for(let H of U)C.set(`${H.filePath}::${H.name}`,w(H))}let T=(U)=>`${U.type}|${U.srcFilePath}|${U.dstFilePath??""}|${U.srcSymbolName??""}|${U.dstSymbolName??""}|${O_(U.metaJson??"")}`,F=new Map;if($)for(let U of this.opts.boundaries)for(let H of Q.getAllFiles(U.project))for(let M of W.getOutgoing(U.project,H.filePath))F.set(T(M),M);else{for(let U of Y){let H=c(U.filePath,this.opts.boundaries);for(let M of W.getOutgoing(H,U.filePath))F.set(T(M),M)}for(let U of X){let H=c(U,this.opts.boundaries);for(let M of W.getOutgoing(H,U))F.set(T(M),M)}}let{annotationRepo:S,changelogRepo:v}=this.opts,u=()=>{for(let U of X){let H=c(U,this.opts.boundaries);if(z.deleteFileSymbols(H,U),W.deleteFileRelations(H,U),W.deleteIncomingRelations(H,U),S)S.deleteFileAnnotations(H,U);Q.deleteFile(H,U)}},x=0,p=async()=>{let{projectRoot:U,boundaries:H}=this.opts,{parseCache:M}=this.opts,B=0,A=0,I=0,G=[],R=[];for(let k of Y)try{let b=g_(U,k.filePath),d=Bun.file(b),$_=await d.text(),U_=k.contentHash||O_($_),L_=c(k.filePath,H);Q.upsertFile({project:L_,filePath:k.filePath,mtimeMs:d.lastModified,size:d.size,contentHash:U_,updatedAt:new Date().toISOString(),lineCount:$_.split(`
|
|
6
|
+
`).length});let D_=(this.opts.parseSourceFn??k_)(b,$_);if(Z1(D_))throw D_.data;let f$=D_;R.push({filePath:k.filePath,text:$_,contentHash:U_,parsed:f$,project:L_})}catch(b){this.logger.error(`[IndexCoordinator] Failed to prepare ${k.filePath}:`,b),G.push(k.filePath)}let j=new Set;for(let k of H)for(let[b]of Q.getFilesMap(k.project))j.add(`${k.project}::${b}`);return Z.transaction(()=>{for(let k of R){if(I0({parsed:k.parsed,project:k.project,filePath:k.filePath,contentHash:k.contentHash,symbolRepo:z}),A+=A0({ast:k.parsed.program,project:k.project,filePath:k.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:K,knownFiles:j,boundaries:H,module:k.parsed.module}),S)I+=N0({parsed:k.parsed,project:k.project,filePath:k.filePath,annotationRepo:S});M.set(k.filePath,k.parsed),B+=z.getFileSymbols(k.project,k.filePath).length}}),{symbols:B,relations:A,annotations:I,failedFiles:G}},l=0,z_=0,Z_=[];if($){let{projectRoot:U,boundaries:H}=this.opts,{parseCache:M}=this.opts,B=[];for(let I=0;I<Y.length;I+=X1){let G=Y.slice(I,I+X1),R=await Promise.allSettled(G.map(async(j)=>{let k=g_(U,j.filePath),b=Bun.file(k),d=await b.text(),$_=j.contentHash||O_(d);return{filePath:j.filePath,text:d,contentHash:$_,mtimeMs:b.lastModified,size:b.size}}));for(let j=0;j<R.length;j++){let k=R[j];if(k.status==="fulfilled")B.push(k.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",k.reason),Z_.push(G[j].filePath)}}let A=[];Z.transaction(()=>{for(let R of B){let j=c(R.filePath,H);Q.deleteFile(j,R.filePath)}for(let R of X){let j=c(R,H);if(z.deleteFileSymbols(j,R),W.deleteFileRelations(j,R),W.deleteIncomingRelations(j,R),S)S.deleteFileAnnotations(j,R);Q.deleteFile(j,R)}for(let R of B){let j=c(R.filePath,H);Q.upsertFile({project:j,filePath:R.filePath,mtimeMs:R.mtimeMs,size:R.size,contentHash:R.contentHash,updatedAt:new Date().toISOString(),lineCount:R.text.split(`
|
|
7
|
+
`).length})}let I=new Set;for(let R of H)for(let[j]of Q.getFilesMap(R.project))I.add(`${R.project}::${j}`);let G=this.opts.parseSourceFn??k_;for(let R of B){let j=c(R.filePath,H),k=G(g_(U,R.filePath),R.text);if(Z1(k))throw k.data;let b=k;if(A.push({filePath:R.filePath,parsed:b}),I0({parsed:b,project:j,filePath:R.filePath,contentHash:R.contentHash,symbolRepo:z}),S)x+=N0({parsed:b,project:j,filePath:R.filePath,annotationRepo:S});z_+=A0({ast:b.program,project:j,filePath:R.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:K,knownFiles:I,boundaries:H,module:b.module}),l+=z.getFileSymbols(j,R.filePath).length}});for(let I of A)M.set(I.filePath,I.parsed)}else{u();let U=await p();l=U.symbols,z_=U.relations,x=U.annotations,Z_=U.failedFiles}for(let U of Y){let H=c(U.filePath,this.opts.boundaries);for(let M of z.getFileSymbols(H,U.filePath))N.set(`${M.filePath}::${M.name}`,w(M))}let H_=new Map;for(let U of Y){let H=c(U.filePath,this.opts.boundaries);for(let M of W.getOutgoing(H,U.filePath))H_.set(T(M),M)}let X_=(U)=>({type:U.type,srcFilePath:U.srcFilePath,dstFilePath:U.dstFilePath,srcSymbolName:U.srcSymbolName,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,metaJson:U.metaJson}),W_={added:[...H_.entries()].filter(([U])=>!F.has(U)).map(([,U])=>X_(U)),removed:[...F.entries()].filter(([U])=>!H_.has(U)).map(([,U])=>X_(U))},i={added:[],modified:[],removed:[]};for(let[U,H]of N){let M=C.get(U);if(!M)i.added.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});else{let B=M.fingerprint!==H.fingerprint,A=M.isExported!==H.isExported,I=M.structuralFingerprint!==null&&H.structuralFingerprint!==null&&M.structuralFingerprint!==H.structuralFingerprint;if(B||A||I)i.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))i.removed.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});let a=Y1(C,N),I_=new Set(a.renamed.map((U)=>`${U.filePath}::${U.oldName}`)),D=new Set(a.renamed.map((U)=>`${U.filePath}::${U.newName}`));i.added=i.added.filter((U)=>!D.has(`${U.filePath}::${U.name}`)),i.removed=i.removed.filter((U)=>!I_.has(`${U.filePath}::${U.name}`));let q=[];if(!$){for(let[H,M]of V)for(let B of M){if(!B.fingerprint)continue;let A=c(H,this.opts.boundaries),I=z.getByFingerprint(A,B.fingerprint);if(I.length===1){let G=I[0];W.retargetRelations({dstProject:A,oldFile:H,oldSymbol:B.name,newFile:G.filePath,newSymbol:G.name}),q.push({name:G.name,filePath:G.filePath,kind:G.kind,oldFilePath:H,isExported:G.isExported??0})}}let U=new Set(q.map((H)=>`${H.oldFilePath}::${H.name}`));for(let H of a.removed){if(U.has(`${H.filePath}::${H.name}`))continue;let B=C.get(`${H.filePath}::${H.name}`)?.fingerprint;if(!B)continue;let A=c(H.filePath,this.opts.boundaries),I=z.getByFingerprint(A,B);if(I.length===1){let G=I[0];if(G.filePath!==H.filePath||G.name!==H.name)W.retargetRelations({dstProject:A,oldFile:H.filePath,oldSymbol:H.name,newFile:G.filePath,newSymbol:G.name}),q.push({name:G.name,filePath:G.filePath,kind:G.kind,oldFilePath:H.filePath,isExported:G.isExported??0})}}}if(q.length){let U=new Set(q.map((M)=>`${M.filePath}::${M.name}`)),H=new Set(q.map((M)=>`${M.oldFilePath}::${M.name}`));i.added=i.added.filter((M)=>!U.has(`${M.filePath}::${M.name}`)),i.removed=i.removed.filter((M)=>!H.has(`${M.filePath}::${M.name}`))}if(v){let U=new Date().toISOString(),H=$?1:0,M=[];for(let B of i.added){let A=`${B.filePath}::${B.name}`,I=N.get(A),G=c(B.filePath,this.opts.boundaries);M.push({project:G,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 i.modified){let A=N.get(`${B.filePath}::${B.name}`),I=c(B.filePath,this.opts.boundaries);M.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 i.removed){let A=`${B.filePath}::${B.name}`,I=C.get(A),G=c(B.filePath,this.opts.boundaries);M.push({project:G,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 a.renamed){let A=N.get(`${B.filePath}::${B.newName}`),I=c(B.filePath,this.opts.boundaries);M.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=c(B.filePath,this.opts.boundaries);M.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(M.length)try{Z.transaction(()=>{v.insertBatch(M)})}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)v.pruneOlderThan(A.project,B)}catch(A){this.logger.error("[IndexCoordinator] changelog pruning failed:",A)}}}return{indexedFiles:Y.length,removedFiles:X.length,totalSymbols:l,totalRelations:z_,totalAnnotations:x,durationMs:Date.now()-J,changedFiles:Y.map((U)=>U.filePath),deletedFiles:[...X],failedFiles:Z_,changedSymbols:i,renamedSymbols:a.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:W_}}fireCallbacks(_){for(let $ of this.callbacks)try{$(_)}catch(J){this.logger.error("[IndexCoordinator] onIndexed callback threw:",J)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let _=this.pendingEvents.splice(0);this.startIndex(_,!1).catch(($)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",$))}}}function iJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function cJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function U1(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??iJ,W=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let Y=_.selectOwner();if(!Y)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-cJ(Y.heartbeat_at))/1000),K=z(Y.pid);if(K&&Z&&Y.instance_id&&Y.instance_id!==Z&&Y.pid===$)return _.replaceOwner($,Z),"owner";if(K&&X<W)return"reader";return _.replaceOwner($,Z),"owner"})}function V1(_,$){_.deleteOwner($)}function O1(_,$){_.touchOwner($)}class p_{#_;#$=new Map;constructor(_){this.#_=Math.max(1,_)}get size(){return this.#$.size}has(_){return this.#$.has(_)}get(_){if(!this.#$.has(_))return;let $=this.#$.get(_);return this.#$.delete(_),this.#$.set(_,$),$}set(_,$){if(this.#$.has(_))this.#$.delete(_);if(this.#$.set(_,$),this.#$.size>this.#_){let J=this.#$.keys().next().value;if(J!==void 0)this.#$.delete(J)}}delete(_){return this.#$.delete(_)}clear(){this.#$.clear()}}class T0{lru;constructor(_=500){this.lru=new p_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function 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=j_(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 S0(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new O("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new O("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,W=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),Y=Z?void 0:W,K=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:z,specifier:Q.specifier,isExternal:Q.isExternal,limit:Y}).map((V)=>{let L;if(V.metaJson)try{L=JSON.parse(V.metaJson)}catch{}return{type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,dstProject:V.dstProject,isExternal:V.isExternal===1,specifier:V.specifier,metaJson:V.metaJson??void 0,meta:L}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let V=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,L=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;K=K.filter((C)=>(!V||V.match(C.srcFilePath))&&(!L||C.dstFilePath===null||L.match(C.dstFilePath)))}if(Z&&W!==void 0&&K.length>W)K=K.slice(0,W);return K}import{findInFiles as aJ,Lang as sJ}from"@ast-grep/napi";function rJ(_){let $=new Set,J=/\${1,3}([A-Z_][A-Z_0-9]*)/g,Q;while((Q=J.exec(_))!==null)$.add(Q[0]);return[...$]}function oJ(_){return _.replace(/^\$+/,"")}function tJ(_,$){if($.length===0)return;let J={},Q=!1;for(let z of $){let W=oJ(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(),K=Y[Y.length-1].range();J[z]={text:Y.map((V)=>V.text()).join(", "),startLine:X.start.line+1,endLine:K.end.line+1,startColumn:X.start.column,endColumn:K.end.column,startOffset:X.start.index,endOffset:K.end.index},Q=!0}}return Q?J:void 0}async function F0(_){if(_.filePaths.length===0)return[];let $=rJ(_.pattern),J=[];return await aJ(sJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(Q,z)=>{if(Q){console.warn("[patternSearch] findInFiles callback error:",Q);return}for(let W of z){let Z=W.range(),Y={filePath:W.getRoot().filename(),startLine:Z.start.line+1,endLine:Z.end.line+1,startColumn:Z.start.column,endColumn:Z.end.column,startOffset:Z.start.index,endOffset:Z.end.index,matchedText:W.text()},X=tJ(W,$);if(X)Y.captures=X;J.push(Y)}}),J}import e from"typescript";import{isErr as MQ}from"@zipbul/result";import B_ from"typescript";import eJ from"path";import{err as j0}from"@zipbul/result";function _Q(_){try{return h0("fs").readFileSync(_,"utf-8")}catch{return}}function $Q(_){try{return h0("fs").readFileSync(_,"utf-8")}catch{return}}class $0{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??_Q,Q=$.resolveNonTrackedFile??$Q,z=eJ.dirname(_),W=J(_);if(W===void 0)return j0(new O("semantic",`tsconfig not found: ${_}`));let Z=B_.parseJsonText(_,W),Y=Z.parseDiagnostics;if(Y&&Y.length>0){let L=Y.map((C)=>B_.flattenDiagnosticMessageText(C.messageText,`
|
|
8
|
+
`)).join("; ");return j0(new O("semantic",`tsconfig parse error: ${L}`))}let X=B_.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===B_.DiagnosticCategory.Error&&C.code!==18003);if(L.length>0){let C=L.map((N)=>B_.flattenDiagnosticMessageText(N.messageText,`
|
|
9
|
+
`)).join("; ");return j0(new O("semantic",`tsconfig compile error: ${C}`))}}let K=new H1(X.fileNames,X.options,z,Q),V=B_.createLanguageService(K);return new $0(V,K)}get isDisposed(){return this.#J}getProgram(){this.#W();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#W(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#W(),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()}#W(){if(this.#J)throw Error("TscProgram is disposed")}}class H1{#_;#$;#J;#W;#z=new Map;#Y=new Map;#Q=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#J=J,this.#W=Q}updateFile(_,$){let J=this.#z.get(_);if(J)this.#Y.delete(`${_}:${J.version}`),J.version+=1,J.content=$;else this.#z.set(_,{version:1,content:$})}removeFile(_){let $=this.#z.get(_);if($)this.#Y.delete(`${_}:${$.version}`);this.#z.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#z.keys()];return[...[...this.#_].filter((J)=>!this.#z.has(J)),..._]}getScriptVersion(_){let $=this.#z.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#z.get(_);if($){let z=`${_}:${$.version}`,W=this.#Y.get(z);if(!W)W=B_.ScriptSnapshot.fromString($.content),this.#Y.set(z,W);return W}let J=this.#Q.get(_);if(J)return J;let Q=this.#W(_);if(Q!==void 0)return J=B_.ScriptSnapshot.fromString(Q),this.#Q.set(_,J),J;return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return B_.getDefaultLibFilePath(_)}fileExists(_){if(this.#z.has(_))return!0;return this.#W(_)!==void 0}readFile(_){let $=this.#z.get(_);if($)return $.content;return this.#W(_)}}import n from"typescript";import M1 from"typescript";function t(_,$){if($<0||$>=_.getEnd())return;let J,Q=(z)=>{if($<z.getStart(_,!1)||$>=z.getEnd())return;J=z,M1.forEachChild(z,Q)};return M1.forEachChild(_,Q),J}var J0=8;function JQ(_){return!!(_.flags&n.TypeFlags.Object)&&!!(_.objectFlags&n.ObjectFlags.Reference)}function K_(_,$,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<J0&&JQ($)){let w=_.getTypeArguments($);if(w.length>0)X=w}let K=!!(W&n.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,V;if(Z&&J<J0)V=$.types.map((w)=>K_(_,w,J+1,Q));else if(Y&&J<J0)V=$.types.map((w)=>K_(_,w,J+1,Q));let L;if(X&&X.length>0)L=X.map((w)=>K_(_,w,J+1,Q));let C;if(J<J0&&!!(W&n.TypeFlags.Object)&&!Z&&!Y){let w=_.getPropertiesOfType($);if(w.length>0&&w.length<=50){let T=$.symbol?.declarations?.[0];C=[];for(let F of w){let S=F.declarations?.[0]??T;if(!S)continue;try{let v=_.getTypeOfSymbolAtLocation(F,S);C.push({name:F.getName(),type:K_(_,v,J+1,Q)})}catch{}}if(C.length===0)C=void 0}}let N={text:z,flags:W,isUnion:Z,isIntersection:Y,isGeneric:K,members:V,typeArguments:L,properties:C};if(Q)Q.set($,N);return N}function QQ(_){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 k0{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=t(z,$);if(!W)return null;if(!n.isIdentifier(W)&&!n.isTypeNode(W))return null;try{let Z=Q.getTypeAtLocation(W);return K_(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=t(Z,$);if(!Y||!n.isIdentifier(Y))return null;let X=z.getSourceFile(J);if(!X)return null;let K=t(X,Q);if(!K||!n.isIdentifier(K))return null;try{let V=W.getTypeAtLocation(Y),L=W.getTypeAtLocation(K);return W.isTypeAssignableTo(V,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=t(Z,$);if(!Y||!n.isIdentifier(Y)&&!n.isTypeNode(Y))return null;try{let X=this.#J(z,W);if(!X)return null;let K=W.getTypeAtLocation(Y);if(Q?.anyConstituent&&K.isUnion())return K.types.some((V)=>W.isTypeAssignableTo(V,X));return W.isTypeAssignableTo(K,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,J,Q){let z=new Map;if($.length===0)return z;this.#$(J);let W=this.program.getProgram(),Z=W.getTypeChecker(),Y=W.getSourceFile(_);if(!Y)return z;try{let X=this.#J(W,Z);if(!X)return z;let K=Y.getEnd();for(let V of $){if(V<0||V>=K)continue;let L=t(Y,V);if(!L||!n.isIdentifier(L)&&!n.isTypeNode(L))continue;try{let C=Z.getTypeAtLocation(L);if(Q?.anyConstituent&&C.isUnion())z.set(V,C.types.some((N)=>Z.isTypeAssignableTo(N,X)));else z.set(V,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 K=t(W,X);if(!K)continue;if(!n.isIdentifier(K)&&!n.isTypeNode(K))continue;try{let V=z.getTypeAtLocation(K);J.set(X,K_(z,V,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(QQ(Y)&&Y.name&&n.isIdentifier(Y.name)){let X=Y.name;try{let K=Q.getTypeAtLocation(X),V=X.getStart(z);$.set(V,K_(Q,K,0,W))}catch{}}n.forEachChild(Y,Z)}return Z(z),$}}import w_ from"typescript";var zQ=1000,WQ=1;function YQ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?w_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function Q0(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),W=Q?w_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",Y=W?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:Y},K=_;if(K.parent)X.parent=YQ(K.parent);let V=J&&!!(_.flags&w_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<WQ){let L=V.flags,C=!!(L&w_.SymbolFlags.Enum),N=!!(L&(w_.SymbolFlags.NamespaceModule|w_.SymbolFlags.ValueModule)),w=!!(L&(w_.SymbolFlags.Class|w_.SymbolFlags.Interface));if(C&&V.exports&&V.exports.size>0){let T=[];V.exports.forEach((F)=>{T.push(Q0(F,$+1,J))}),X.members=T}else if(w&&V.members&&V.members.size>0){let T=[];V.members.forEach((F)=>{T.push(Q0(F,$+1,J))}),X.members=T}if(N&&V.exports&&V.exports.size>0){let T=[];V.exports.forEach((F)=>{T.push(Q0(F,$+1,J))}),X.exports=T}}return X}class E0{#_;#$;#J=new Map;constructor(_,$=zQ){this.#_=_,this.#$=new p_($)}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=t(W,$);if(!Z||!w_.isIdentifier(Z))return null;let Y=z.getTypeChecker(),X=Y.getSymbolAtLocation(Z);if(!X)return null;let K=Q0(X,0,Y);this.#$.set(J,K);let V=this.#J.get(_);if(!V)V=new Set,this.#J.set(_,V);return V.add(J),K}invalidate(_){let $=this.#J.get(_);if($){for(let J of $)this.#$.delete(J);this.#J.delete(_)}}clear(){this.#$.clear(),this.#J.clear()}}import w1 from"typescript";import g from"typescript";function K1(_){if(_.getSourceFile().isDeclarationFile)return!0;for(let $=_;$;$=$.parent)if(ZQ($))return!0;return!1}function ZQ(_){if(!g.canHaveModifiers(_))return!1;return g.getModifiers(_)?.some((J)=>J.kind===g.SyntaxKind.DeclareKeyword)??!1}function L1(_){let $=(Q,z)=>({kind:Q,pos:z.getStart(),end:z.getEnd()}),J=_.parent;while(J){if(g.isSourceFile(J)||g.isModuleDeclaration(J))return $("module",J);if(g.isFunctionLike(J))return $("function",J);if(g.isClassStaticBlockDeclaration(J))return $("function",J);if(g.isPropertyDeclaration(J))return $("function",J);if(g.isBlock(J)){let Q=J.parent;if(Q&&(g.isFunctionLike(Q)||g.isClassStaticBlockDeclaration(Q)))return $("function",Q);return $("block",J)}if(g.isForStatement(J)||g.isForInStatement(J)||g.isForOfStatement(J)||g.isCatchClause(J)||g.isCaseBlock(J)||g.isWithStatement(J))return $("block",J);J=J.parent}return $("module",_.getSourceFile())}function B1(_){let $=_.parent;if(!$)return;if(g.isVariableDeclaration($)&&$.name===_)return"declaration";if(g.isParameter($)&&$.name===_)return"declaration";if(g.isBindingElement($)&&$.name===_)return"declaration";if((g.isForOfStatement($)||g.isForInStatement($))&&$.initializer===_)return"assignment";if((g.isPrefixUnaryExpression($)||g.isPostfixUnaryExpression($))&&$.operand===_&&($.operator===g.SyntaxKind.PlusPlusToken||$.operator===g.SyntaxKind.MinusMinusToken))return"update";let J=_;while(J.parent&&g.isParenthesizedExpression(J.parent))J=J.parent;let Q=J.parent;if(Q&&g.isBinaryExpression(Q)&&Q.left===J)return XQ(Q.operatorToken.kind);if(UQ(_))return"assignment";return}function XQ(_){switch(_){case g.SyntaxKind.EqualsToken:return"assignment";case g.SyntaxKind.PlusEqualsToken:case g.SyntaxKind.MinusEqualsToken:case g.SyntaxKind.AsteriskEqualsToken:case g.SyntaxKind.AsteriskAsteriskEqualsToken:case g.SyntaxKind.SlashEqualsToken:case g.SyntaxKind.PercentEqualsToken:case g.SyntaxKind.LessThanLessThanEqualsToken:case g.SyntaxKind.GreaterThanGreaterThanEqualsToken:case g.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:case g.SyntaxKind.AmpersandEqualsToken:case g.SyntaxKind.BarEqualsToken:case g.SyntaxKind.CaretEqualsToken:return"compound-assignment";case g.SyntaxKind.AmpersandAmpersandEqualsToken:case g.SyntaxKind.BarBarEqualsToken:case g.SyntaxKind.QuestionQuestionEqualsToken:return"logical-assignment";default:return}}function UQ(_){let $=_.parent;if(!$)return!1;if(!(g.isShorthandPropertyAssignment($)&&$.name===_||g.isPropertyAssignment($)&&$.initializer===_||g.isArrayLiteralExpression($)||g.isSpreadAssignment($)&&$.expression===_||g.isSpreadElement($)&&$.expression===_))return!1;let Q=$;while(Q.parent){let z=Q.parent;if(g.isBinaryExpression(z)&&z.left===Q&&z.operatorToken.kind===g.SyntaxKind.EqualsToken)return!0;if(g.isObjectLiteralExpression(z)||g.isArrayLiteralExpression(z)||g.isPropertyAssignment(z)||g.isShorthandPropertyAssignment(z)||g.isSpreadAssignment(z)||g.isSpreadElement(z)){Q=z;continue}return!1}return!1}class u0{#_;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 K=Q.getSourceFile(X.fileName);if(!K)continue;let V=t(K,X.textSpan.start),L=V&&w1.isIdentifier(V)?V:void 0;W.push({...I1(X,K),writeKind:L?B1(L):void 0,isAmbient:Y,enclosingScope:L1(L??K)})}}return W}#$(_,$){if(this.#_.isDisposed)return null;let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=t(Q,$);if(!z||!w1.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=t(z,Q.textSpan.start);if(!W)return!1;let Y=J.getSymbolAtLocation(W)?.declarations;if(!Y||Y.length===0)return!1;return Y.every(K1)}}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 VQ(_,$){let J=t(_,$);if(!J)return;if(D1(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(D1(Q))return Q;Q=Q.parent}return J}function D1(_){return h.isClassDeclaration(_)||h.isClassExpression(_)||h.isFunctionDeclaration(_)||h.isFunctionExpression(_)||h.isArrowFunction(_)||h.isVariableDeclaration(_)||h.isObjectLiteralExpression(_)}function C1(_){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 C1(_.initializer);return"class"}function OQ(_,$){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 HQ(_){if(!h.isClassDeclaration(_)&&!h.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===h.SyntaxKind.ImplementsKeyword)}class v0{#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=t(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 K=J.getSourceFile(X.fileName);if(!K)continue;let V=VQ(K,X.textSpan.start);if(!V)continue;let L=C1(V),C=OQ(V,K),N=HQ(V);Y.push({filePath:X.fileName,symbolName:C,position:X.textSpan.start,kind:L,isExplicit:N})}return Y}}function KQ(_){if(e.isFunctionDeclaration(_))return"function";if(e.isClassDeclaration(_))return"class";if(e.isInterfaceDeclaration(_))return"interface";if(e.isTypeAliasDeclaration(_))return"type";if(e.isEnumDeclaration(_))return"enum";if(e.isVariableDeclaration(_))return"const";if(e.isVariableStatement(_))return"const";return"unknown"}function A1(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class z0{#_;#$;#J;#W;#z;#Y=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#J=J,this.#W=Q,this.#z=z}static create(_,$={}){let J=$0.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(MQ(J))return J;let Q=J,z=$.typeCollector??new k0(Q),W=$.symbolGraph??new E0(Q),Z=$.referenceResolver??new u0(Q),Y=$.implementationFinder??new v0(Q);return new z0(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.#W.findAt(_,$)}findEnrichedReferences(_,$){return this.#Q(),this.#W.findEnrichedAt(_,$)}findImplementations(_,$){return this.#Q(),this.#z.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=t(Q,$);if(!z)return null;let W=J.getTypeChecker(),Z=W.getTypeAtLocation(z);if(!(Z.flags&e.TypeFlags.Object)||!(Z.objectFlags&e.ObjectFlags.ClassOrInterface))return null;let Y=W.getBaseTypes(Z);if(!Y||Y.length===0)return[];let X=new Map;return Y.map((K)=>K_(W,K,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 K=X.getName(),V=X.declarations?.[0],L="unknown";if(V){if(L=KQ(V),L==="unknown"&&e.isExportAssignment(V))L="const"}let C=null;try{let N=z.getTypeOfSymbolAtLocation(X,V??Q);C=K_(z,N,0,Y)}catch{}$.push({name:K,kind:L,resolvedType:C})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#_.notifyFileChanged(_,$),this.#J.invalidate(_)}notifyFileDeleted(_){if(this.#Y)return;this.#_.removeFile(_),this.#J.invalidate(_)}lineColumnToPosition(_,$,J){this.#Q();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return e.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={[e.DiagnosticCategory.Error]:"error",[e.DiagnosticCategory.Warning]:"warning",[e.DiagnosticCategory.Suggestion]:"suggestion",[e.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?e.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let Y=1,X=0;if(Z.file&&Z.start!==void 0){let K=e.getLineAndCharacterOfPosition(Z.file,Z.start);Y=K.line+1,X=K.character}return{filePath:Z.file?.fileName??_,line:Y,column:X,message:e.flattenDiagnosticMessageText(Z.messageText,`
|
|
10
|
+
`),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#$.clearProbe(),this.#_.dispose(),this.#J.clear()}#Q(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as G_,and as q1,sql as LQ}from"drizzle-orm";var N1=80;class b0{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(Y_).values(Q.slice(z,z+N1)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Y_).where(q1(G_(Y_.project,_),G_(Y_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Y_).where(q1(_.project?G_(Y_.project,_.project):void 0,_.tag?G_(Y_.tag,_.tag):void 0,_.filePath?G_(Y_.filePath,_.filePath):void 0,_.symbolName?G_(Y_.symbolName,_.symbolName):void 0,_.source?G_(Y_.source,_.source):void 0,_.ftsQuery?LQ`${Y_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as v_,and as R1,sql as l_,gt as BQ,gte as wQ}from"drizzle-orm";var T1=80;class P0{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(v_(__.project,_.project),wQ(__.changedAt,_.since),_.symbolName?v_(__.symbolName,_.symbolName):void 0,_.changeTypes?.length?l_`${__.changeType} IN (${l_.join(_.changeTypes.map(($)=>l_`${$}`),l_`, `)})`:void 0,_.filePath?v_(__.filePath,_.filePath):void 0,_.includeFullIndex?void 0:v_(__.isFullIndex,0),_.indexRunId?v_(__.indexRunId,_.indexRunId):void 0,_.afterId?BQ(__.id,_.afterId):void 0)).orderBy(__.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(__).where(R1(v_(__.project,_),l_`${__.changedAt} < ${$}`)).run().changes}}function G1(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,W;if(Q.text){let Y=j_(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 W0{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 qQ(J,$)}}var IQ=(_,$)=>_.localeCompare($);function DQ(_){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 f0(_,$,J){let Q=DQ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function CQ(_){let $=0,J=[],Q=new Set,z=new Map,W=new Map,Z=[],Y=(X)=>{z.set(X,$),W.set(X,$),$+=1,J.push(X),Q.add(X);for(let K of _.get(X)??[])if(!z.has(K))Y(K),W.set(X,Math.min(W.get(X)??0,W.get(K)??0));else if(Q.has(K))W.set(X,Math.min(W.get(X)??0,z.get(K)??0));if(W.get(X)===z.get(X)){let K=[],V="";do V=J.pop()??"",Q.delete(V),K.push(V);while(V!==X&&J.length>0);Z.push(K)}};for(let X of _.keys())if(!z.has(X))Y(X);return{components:Z}}function AQ(_,$,J){let Q=[],z=new Set,W=[..._].sort(IQ),Z=(Y,X,K)=>{X.delete(Y);let V=K.get(Y);if(!V)return;for(let L of V)if(X.has(L))Z(L,X,K);V.clear()};for(let Y=0;Y<W.length&&Q.length<J;Y++){let X=W[Y]??"",K=new Set(W.slice(Y)),V=new Set,L=new Map,C=[],N=(T)=>($.get(T)??[]).filter((F)=>K.has(F)),w=(T)=>{if(Q.length>=J)return!0;let F=!1;C.push(T),V.add(T);for(let S of N(T)){if(Q.length>=J)break;if(S===X)f0(z,Q,C.concat(X)),F=!0;else if(!V.has(S)){if(w(S))F=!0}}if(F)Z(T,V,L);else for(let S of N(T)){let v=L.get(S)??new Set;v.add(T),L.set(S,v)}return C.pop(),F};w(X)}return Q}function qQ(_,$){let{components:J}=CQ(_),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))f0(z,Q,[X,X]);continue}let Z=$-Q.length,Y=AQ(W,_,Z);for(let X of Y){if(Q.length>=$)break;f0(z,Q,X)}}return Q}var NQ=15000;function Y0(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function S_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>NQ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new W0({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((z)=>z.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function S1(_,$,J,Q=1e4){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).filter((z)=>z.dstFilePath!==null).map((z)=>z.dstFilePath)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getDependencies failed",{cause:z})}}function F1(_,$,J,Q=1e4){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{dstFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).map((z)=>z.srcFilePath)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getDependents failed",{cause:z})}}async function j1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return S_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getAffected failed",{cause:Q})}}async function g1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return S_(_,$).hasCycle()}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: hasCycle failed",{cause:J})}}async function k1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return S_(_,$).getAdjacencyList()}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getImportGraph failed",{cause:J})}}async function E1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return S_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function u1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return S_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function v1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return S_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getCyclePaths failed",{cause:Q})}}async function b1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let Q=S_(_,J);return{filePath:$,fanIn:Q.getDependents($).length,fanOut:Q.getDependencies($).length}}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getFanMetrics failed",{cause:Q})}}var GQ=30000,P1=15000,SQ=10;function FQ(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??b_.basename(_.projectRoot)}function jQ(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(z){_.logger.error("[Gildash] onFileChanged callback threw:",z)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let z of _.onErrorCallbacks)try{z(Q instanceof O?Q:new O("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",z);for(let W of _.onErrorCallbacks)try{W(z instanceof O?z:new O("semantic","semantic notifyFileChanged failed",{cause:z}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",z)}})}}async function gQ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=b_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function f1(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new R0({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)=>FQ(_,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 Y0(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new B0({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(jQ(_,J)).then((z)=>{if(i_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},GQ)}await J.fullIndex(),await gQ(_)}function kQ(_,$){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=TQ,dbConnectionFactory:Y,watcherFactory:X,coordinatorFactory:K,repositoryFactory:V,acquireWatcherRoleFn:L=U1,releaseWatcherRoleFn:C=V1,updateHeartbeatFn:N=O1,discoverProjectsFn:w=s_,parseSourceFn:T=k_,extractSymbolsFn:F=N_,extractRelationsFn:S=d_,symbolSearchFn:v=G0,relationSearchFn:u=S0,patternSearchFn:x=F0,loadTsconfigPathsFn:p=m_,readFileFn:l=async(a)=>Bun.file(a).text(),unlinkFn:z_=async(a)=>{await Bun.file(a).unlink()},watchMode:Z_,semantic:H_,semanticLayerFactory:X_}=_;if(!b_.isAbsolute($))throw new O("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Z($))throw new O("validation",`Gildash: projectRoot does not exist: "${$}"`);let W_=Y?Y():new O0({projectRoot:$}),i=W_.open();if(i_(i))throw i.data;try{let a=await w($),I_=a[0]?.project??b_.basename($),D=V?V():(()=>{let G=W_;return{fileRepo:new H0(G),symbolRepo:new M0(G),relationRepo:new K0(G),parseCache:new T0(z)}})(),q=V?null:W_,U=q?new b0(q):null,H=q?new P0(q):null,M=Z_??!0,B=crypto.randomUUID(),A;if(M)A=await Promise.resolve(L(W_,process.pid,{instanceId:B}));else A="owner";let I={projectRoot:$,extensions:J,ignorePatterns:Q,logger:W,defaultProject:I_,role:A,db:W_,symbolRepo:D.symbolRepo,relationRepo:D.relationRepo,fileRepo:D.fileRepo,parseCache:D.parseCache,annotationRepo:U,changelogRepo:H,annotationSearchFn:G1,releaseWatcherRoleFn:C,parseSourceFn:T,extractSymbolsFn:F,extractRelationsFn:S,symbolSearchFn:v,relationSearchFn:u,patternSearchFn:x,readFileFn:l,unlinkFn:z_,existsSyncFn:Z,acquireWatcherRoleFn:L,updateHeartbeatFn:N,watcherFactory:X,coordinatorFactory:K,instanceId:B,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:a,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(r_($),I.tsconfigPaths=await p($),H_){let G=b_.join($,"tsconfig.json");try{if(X_)I.semanticLayer=X_(G);else{let R=z0.create(G);if(i_(R))throw R.data;I.semanticLayer=R}}catch(R){if(R instanceof O)throw R;throw new O("semantic","Gildash: semantic layer creation failed",{cause:R})}}if(A==="owner")await f1(I,{isWatchMode:M});else{let G=0,R=async()=>{try{let j=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(G=0,j==="owner"){I.role="owner";for(let k of I.onRoleChangedCallbacks)try{k("owner")}catch(b){I.logger.error("[Gildash] onRoleChanged callback threw:",b)}clearInterval(I.timer),I.timer=null;try{await f1(I,{isWatchMode:!0})}catch(k){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",k),I.role="reader",I.timer!==null)clearInterval(I.timer),I.timer=null;if(I.watcher){let b=await I.watcher.close();if(i_(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(R,P1)}}}catch(j){G++;let k=j instanceof O?j:new O("watcher","Gildash: healthcheck error",{cause:j});for(let b of I.onErrorCallbacks)try{b(k)}catch(d){I.logger.error("[Gildash] onError callback threw:",d)}if(I.logger.error("[Gildash] healthcheck error",j),G>=SQ)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,Z0(I).catch((b)=>I.logger.error("[Gildash] close error during healthcheck shutdown",b))}};I.timer=setInterval(R,P1)}if(M)kQ(I,()=>Z0(I));return I}catch(a){if(W_.close(),a instanceof O)throw a;throw new O("store","Gildash: initialization failed",{cause:a})}}async function Z0(_,$){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(i_(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(b_.join(_.projectRoot,C_,c_+Q))}catch{}if(J.length>0)throw new O("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 O("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 O("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(W)=>{try{let Z=await _.readFileFn(W),Y=_.parseSourceFn(W,Z,J);if(!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 O("closed","Gildash: instance is closed");return _.parseCache.get($)}function d1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function p1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import l1 from"path";function i1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: getStats failed",{cause:J})}}function y0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchSymbols failed",{cause:J})}}function c1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchRelations failed",{cause:J})}}function a1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchAllSymbols failed",{cause:J})}}function s1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchAllRelations failed",{cause:J})}}function r1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: listIndexedFiles failed",{cause:J})}}function o1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getInternalRelations failed",{cause:Q})}}function t1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(W.length===0)return null;let Z=W[0],Y=Z.detail,X={...Z,members:Y.members,jsDoc:Y.jsDoc,parameters:Y.parameters,returnType:Y.returnType,heritage:Y.heritage,decorators:Y.decorators,typeParameters:Y.typeParameters,initializer:Y.initializer};if(_.semanticLayer)try{let K=l1.isAbsolute(J)?J:l1.resolve(_.projectRoot,J),V=_.semanticLayer.lineColumnToPosition(K,Z.span.start.line,Z.span.start.column);if(V!==null){let L=_.semanticLayer.findNamePosition(K,V,Z.name)??V,C=_.semanticLayer.collectTypeAt(K,L);if(C)X.resolvedType=C}}catch{}return X}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getFullSymbol failed",{cause:z})}}function e1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new O("search",`Gildash: file '${$}' is not in the index`);let W=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:W.length,exportedSymbolCount:W.filter((Y)=>Y.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof O)throw Q;throw new O("store","Gildash: getFileStats failed",{cause:Q})}}function _$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(J??_.defaultProject,$)}catch(Q){if(Q instanceof O)throw Q;throw new O("store","Gildash: getFileInfo failed",{cause:Q})}}function $$(_,$,J){return y0(_,{filePath:$,project:J??void 0,limit:1e4})}function J$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((W)=>({name:W.name,kind:W.kind,parameters:W.detail.parameters?`(${W.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:W.detail.returnType??void 0,jsDoc:W.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getModuleInterface failed",{cause:Q})}}import f from"path";function P_(_,$,J,Q){let z=Q??_.defaultProject,W=f.isAbsolute(J)?f.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=f.isAbsolute(J)?J:f.resolve(_.projectRoot,J),K=_.semanticLayer.lineColumnToPosition(X,Y.span.start.line,Y.span.start.column);if(K===null)return null;let V=_.semanticLayer.findNamePosition(X,K,Y.name)??K;return{sym:Y,position:V,absPath:X}}function Q$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P_(_,$,J,Q);if(!z)return null;return _.semanticLayer.collectTypeAt(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getResolvedType failed",{cause:z})}}function z$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P_(_,$,J,Q);if(!z)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getSemanticReferences failed",{cause:z})}}function W$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P_(_,$,J,Q);if(!z)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findEnrichedReferences(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getEnrichedReferences failed",{cause:z})}}function Y$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=P_(_,$,J,Q);if(!z)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getImplementations failed",{cause:z})}}function Z$(_,$,J,Q,z,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Z=P_(_,$,J,W);if(!Z)throw new O("search",`Gildash: source symbol '${$}' not found in '${J}'`);let Y=P_(_,Q,z,W);if(!Y)throw new O("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,Y.absPath,Y.position)}catch(Z){if(Z instanceof O)throw Z;throw new O("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function X$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getFileTypes failed",{cause:J})}}function U$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=f.isAbsolute($)?$:f.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(z,J,Q);if(W===null)return null;return _.semanticLayer.collectTypeAt(z,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function V$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=f.isAbsolute($.source.filePath)?$.source.filePath:f.resolve(_.projectRoot,$.source.filePath),Q=f.isAbsolute($.target.filePath)?$.target.filePath:f.resolve(_.projectRoot,$.target.filePath),z=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(z===null)return null;let W=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(W===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,W)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function O$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function H$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function M$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getResolvedTypesAtPositions failed",{cause:Q})}}function K$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:Q})}}function L$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:Q})}}function B$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.findEnrichedReferences(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getEnrichedReferencesAtPosition failed",{cause:Q})}}function w$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getImplementationsAtPosition failed",{cause:Q})}}function I$(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=f.isAbsolute($)?$:f.resolve(_.projectRoot,$),Z=f.isAbsolute(Q)?Q:f.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(W,J,Z,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:W})}}function D$(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,J,Q,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToType failed",{cause:W})}}function C$(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,J,Q,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:W})}}function A$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(z,J,Q)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: lineColumnToPosition failed",{cause:z})}}function q$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(z,J,Q)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: findNamePosition failed",{cause:z})}}function N$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSymbolNode failed",{cause:Q})}}function R$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=f.isAbsolute($)?$:f.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSemanticDiagnostics failed",{cause:Q})}}function T$(_,$){let J=new Map(_.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),Q=new Map($.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),z=[],W=[],Z=[];for(let[Y,X]of Q){let K=J.get(Y);if(!K)z.push(X);else if(K.fingerprint!==X.fingerprint)Z.push({before:K,after:X})}for(let[Y,X]of J)if(!Q.has(Y))W.push(X);return{added:z,removed:W,modified:Z}}function G$(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function S$(_){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.coordinator)throw new O("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return Y0(_),$}catch($){if($ instanceof O)throw $;throw new O("index","Gildash: reindex failed",{cause:$})}}function F$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");let z=Q??_.defaultProject,W=new Set,Z=[],Y=$,X=J;for(;;){let K=`${X}::${Y}`;if(W.has(K))return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!0};W.add(K);let V=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),L,C;for(let N of V){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 T=w.find((F)=>F.exported===Y);if(!T)continue;L=N.dstFilePath??void 0,C=T.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 j$(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function g$(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function k$(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function E$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,z=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((W)=>W.filePath);return await _.patternSearchFn({pattern:$,filePaths:z})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: findPattern failed",{cause:Q})}}async function u$(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=new Set,Z=(Y,X,K)=>{let V=`${Y}::${X}`;if(W.has(V))return{symbolName:Y,filePath:X,kind:K,children:[]};W.add(V);let N=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:Y,limit:1000}}).filter((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:K,children:N}};return Z($,J)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getHeritageChain failed",{cause:z})}}function v$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function b$(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,W=J?.limit??1000;return _.changelogRepo.getSince({project:z,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:W}).map((Y)=>({changeType:Y.changeType,symbolName:Y.symbolName,symbolKind:Y.symbolKind,filePath:Y.filePath,oldName:Y.oldName,oldFilePath:Y.oldFilePath,fingerprint:Y.fingerprint,changedAt:Y.changedAt,isFullIndex:Y.isFullIndex===1,indexRunId:Y.indexRunId}))}function P$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Z)=>Z.project)],W=[...new Set(z)];for(let Z of W)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class x0{_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 x0($)}async close(_){return Z0(this._ctx,_)}parseSource(_,$,J){return h1(this._ctx,_,$,J)}async batchParse(_,$){return m1(this._ctx,_,$)}getParsedAst(_){return n1(this._ctx,_)}extractSymbols(_){return d1(this._ctx,_)}extractRelations(_){return p1(this._ctx,_)}getStats(_){return i1(this._ctx,_)}searchSymbols(_){return y0(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 S1(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return F1(this._ctx,_,$,J)}async getAffected(_,$){return j1(this._ctx,_,$)}async hasCycle(_){return g1(this._ctx,_)}async getImportGraph(_){return k1(this._ctx,_)}async getTransitiveDependencies(_,$){return E1(this._ctx,_,$)}async getTransitiveDependents(_,$){return u1(this._ctx,_,$)}async getCyclePaths(_,$){return v1(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 K$(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return M$(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return L$(this._ctx,_,$)}getEnrichedReferencesAtPosition(_,$){return B$(this._ctx,_,$)}getImplementationsAtPosition(_,$){return w$(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return I$(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return D$(this._ctx,_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return C$(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return A$(this._ctx,_,$,J)}findNamePosition(_,$,J){return q$(this._ctx,_,$,J)}getSymbolNode(_,$){return N$(this._ctx,_,$)}getBaseTypes(_,$){return H$(this._ctx,_,$)}getSemanticDiagnostics(_,$){return R$(this._ctx,_,$)}diffSymbols(_,$){return T$(_,$)}onIndexed(_){return G$(this._ctx,_)}async reindex(){return S$(this._ctx)}resolveSymbol(_,$,J){return F$(this._ctx,_,$,J)}async findPattern(_,$){return E$(this._ctx,_,$)}async getHeritageChain(_,$,J){return u$(this._ctx,_,$,J)}onFileChanged(_){return j$(this._ctx,_)}onError(_){return g$(this._ctx,_)}onRoleChanged(_){return k$(this._ctx,_)}searchAnnotations(_){return v$(this._ctx,_)}getSymbolChanges(_,$){return b$(this._ctx,_,$)}pruneChangelog(_){return P$(this._ctx,_)}}import{Visitor as P5,visitorKeys as f5}from"oxc-parser";import{walk as x5,parseAndWalk as h5,ScopeTracker as m5}from"oxc-walker";export{x5 as walk,f5 as visitorKeys,G0 as symbolSearch,S0 as relationSearch,F0 as patternSearch,k_ as parseSource,h5 as parseAndWalk,Q_ as normalizePath,xJ as isVariableDeclaration,yJ as isTSQualifiedName,fJ as isMemberExpression,PJ as isIdentifier,gJ as isFunctionNode,bJ as isFunctionExpression,vJ as isFunctionDeclaration,uJ as isCallExpression,EJ as isAssignmentExpression,kJ as isArrowFunctionExpression,hJ as is,V_ as getLineColumn,N_ as extractSymbols,d_ as extractRelations,n_ as buildLineOffsets,P5 as Visitor,m5 as ScopeTracker,O as GildashError,x0 as Gildash,W0 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' | 'findImplementations' | 'isTypeAssignableTo' | 'isTypeAssignableToType' | 'isTypeAssignableToTypeAtPositions' | 'getModuleInterface' | 'getSymbolNode' | 'getBaseTypes' | 'getDiagnostics' | 'notifyFileChanged' | 'notifyFileDeleted' | 'dispose' | 'isDisposed' | 'lineColumnToPosition' | 'findNamePosition'>;
|
|
60
|
+
export type SemanticLayerLike = Pick<SemanticLayer, 'collectTypeAt' | 'collectFileTypes' | 'collectTypesAtPositions' | 'findReferences' | 'findEnrichedReferences' | '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, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from '../semantic/types';
|
|
12
|
+
import type { ResolvedType, SemanticReference, EnrichedReference, 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';
|
|
@@ -337,6 +337,17 @@ export declare class Gildash {
|
|
|
337
337
|
* @throws {GildashError} With type `'semantic'` if tsc initialisation fails.
|
|
338
338
|
*/
|
|
339
339
|
getSemanticReferences(symbolName: string, filePath: string, project?: string): SemanticReference[];
|
|
340
|
+
/**
|
|
341
|
+
* Like {@link getSemanticReferences}, but each reference is enriched with
|
|
342
|
+
* `writeKind`, `isAmbient`, and `enclosingScope` for dataflow analysis.
|
|
343
|
+
*
|
|
344
|
+
* @param symbolName - Exact symbol name.
|
|
345
|
+
* @param filePath - Relative path to the declaring file.
|
|
346
|
+
* @param project - Project name. Defaults to the primary project.
|
|
347
|
+
* @returns Array of enriched reference locations. Empty array if none found.
|
|
348
|
+
* @throws {GildashError} With type `'semantic'` if tsc initialisation fails.
|
|
349
|
+
*/
|
|
350
|
+
getEnrichedReferences(symbolName: string, filePath: string, project?: string): EnrichedReference[];
|
|
340
351
|
/**
|
|
341
352
|
* Find all implementations of an interface or abstract class member.
|
|
342
353
|
*
|
|
@@ -436,6 +447,16 @@ export declare class Gildash {
|
|
|
436
447
|
* @throws {GildashError} With type `'semantic'` if tsc initialisation fails.
|
|
437
448
|
*/
|
|
438
449
|
getSemanticReferencesAtPosition(filePath: string, position: number): SemanticReference[];
|
|
450
|
+
/**
|
|
451
|
+
* Like {@link getSemanticReferencesAtPosition}, but each reference is enriched
|
|
452
|
+
* with `writeKind`, `isAmbient`, and `enclosingScope` for dataflow analysis.
|
|
453
|
+
*
|
|
454
|
+
* @param filePath - Relative path to the file.
|
|
455
|
+
* @param position - 0-based byte offset of the symbol.
|
|
456
|
+
* @returns Array of enriched reference locations. Empty array if none found.
|
|
457
|
+
* @throws {GildashError} With type `'semantic'` if tsc initialisation fails.
|
|
458
|
+
*/
|
|
459
|
+
getEnrichedReferencesAtPosition(filePath: string, position: number): EnrichedReference[];
|
|
439
460
|
/**
|
|
440
461
|
* Find all implementations of the symbol at a specific byte position.
|
|
441
462
|
*
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SymbolSearchResult } from '../search/symbol-search';
|
|
2
|
-
import type { ResolvedType, SemanticReference, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from '../semantic/types';
|
|
2
|
+
import type { ResolvedType, SemanticReference, EnrichedReference, 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
|
/**
|
|
@@ -15,6 +15,8 @@ export declare function resolveSymbolPosition(ctx: GildashContext, symbolName: s
|
|
|
15
15
|
export declare function getResolvedType(ctx: GildashContext, symbolName: string, filePath: string, project?: string): ResolvedType | null;
|
|
16
16
|
/** Find all semantic references to a symbol. */
|
|
17
17
|
export declare function getSemanticReferences(ctx: GildashContext, symbolName: string, filePath: string, project?: string): SemanticReference[];
|
|
18
|
+
/** Find all references to a symbol, enriched with writeKind / isAmbient / enclosingScope. */
|
|
19
|
+
export declare function getEnrichedReferences(ctx: GildashContext, symbolName: string, filePath: string, project?: string): EnrichedReference[];
|
|
18
20
|
/** Find implementations of an interface/abstract class. */
|
|
19
21
|
export declare function getImplementations(ctx: GildashContext, symbolName: string, filePath: string, project?: string): Implementation[];
|
|
20
22
|
/** Check whether a source symbol's type is assignable to a target symbol's type. */
|
|
@@ -46,6 +48,8 @@ export declare function getResolvedTypesAtPositions(ctx: GildashContext, filePat
|
|
|
46
48
|
export declare function getResolvedTypeAtPosition(ctx: GildashContext, filePath: string, position: number): ResolvedType | null;
|
|
47
49
|
/** Find all semantic references at a byte offset. */
|
|
48
50
|
export declare function getSemanticReferencesAtPosition(ctx: GildashContext, filePath: string, position: number): SemanticReference[];
|
|
51
|
+
/** Find all enriched references at a byte offset. */
|
|
52
|
+
export declare function getEnrichedReferencesAtPosition(ctx: GildashContext, filePath: string, position: number): EnrichedReference[];
|
|
49
53
|
/** Find implementations at a byte offset. */
|
|
50
54
|
export declare function getImplementationsAtPosition(ctx: GildashContext, filePath: string, position: number): Implementation[];
|
|
51
55
|
/** Check type assignability at byte offsets. */
|
package/dist/src/index.d.ts
CHANGED
|
@@ -16,7 +16,8 @@ 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, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from "./semantic/types";
|
|
19
|
+
export type { ResolvedType, SemanticReference, EnrichedReference, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from "./semantic/types";
|
|
20
|
+
export type { WriteKind, ScopeKind, EnclosingScope } from "./semantic/reference-classifier";
|
|
20
21
|
export type { SymbolNode } from "./semantic/symbol-graph";
|
|
21
22
|
export type { AnnotationSource, ExtractedAnnotation } from "./extractor/types";
|
|
22
23
|
export type { AnnotationSearchQuery, AnnotationSearchResult } from "./search/annotation-search";
|
|
@@ -32,4 +33,5 @@ export { Visitor, visitorKeys } from 'oxc-parser';
|
|
|
32
33
|
export type { VisitorObject } from 'oxc-parser';
|
|
33
34
|
export { walk, parseAndWalk, ScopeTracker } from 'oxc-walker';
|
|
34
35
|
export type { WalkerEnter, WalkerLeave, WalkerCallbackContext, WalkerThisContextEnter, WalkerThisContextLeave, WalkOptions, ScopeTrackerNode, ScopeTrackerOptions, } from 'oxc-walker';
|
|
35
|
-
export { isArrowFunctionExpression, isAssignmentExpression, isCallExpression, isFunctionDeclaration, isFunctionExpression, isFunctionNode, isIdentifier, isMemberExpression, isTSQualifiedName, isVariableDeclaration, } from './parser/ast-utils';
|
|
36
|
+
export { isArrowFunctionExpression, isAssignmentExpression, isCallExpression, isFunctionDeclaration, isFunctionExpression, isFunctionNode, isIdentifier, isMemberExpression, isTSQualifiedName, isVariableDeclaration, is, } from './parser/ast-utils';
|
|
37
|
+
export type { IsNamespace, NodeTypePredicate } from './parser/ast-utils';
|
|
@@ -71,6 +71,70 @@ export declare function isTSQualifiedName(node: Node): node is Node & {
|
|
|
71
71
|
export declare function isVariableDeclaration(node: Node): node is Node & {
|
|
72
72
|
type: 'VariableDeclaration';
|
|
73
73
|
};
|
|
74
|
+
/**
|
|
75
|
+
* Per-Node-type predicate signature: narrows a `Node` to the union of
|
|
76
|
+
* interfaces sharing the discriminator literal `K`.
|
|
77
|
+
*
|
|
78
|
+
* Uses the `Node & { type: K }` intersection form rather than `Extract<Node, { type: K }>`
|
|
79
|
+
* because some backing interfaces in `@oxc-project/types` declare `type` as a
|
|
80
|
+
* multi-literal union (e.g. `Function`'s `'FunctionDeclaration' | 'FunctionExpression'
|
|
81
|
+
* | 'TSDeclareFunction' | 'TSEmptyBodyFunctionExpression'`, `Class`'s
|
|
82
|
+
* `'ClassDeclaration' | 'ClassExpression'`). Distributive `Extract` against a
|
|
83
|
+
* single literal evaluates the constraint as broader than the field and drops
|
|
84
|
+
* those branches to `never`, breaking field access inside the narrowed branch.
|
|
85
|
+
* Intersection narrows the discriminator while preserving the backing interface's
|
|
86
|
+
* structural fields. See commit 1c73175 for the original fix on the hand-written
|
|
87
|
+
* predicates.
|
|
88
|
+
*/
|
|
89
|
+
export type NodeTypePredicate<K extends Node['type']> = (node: Node) => node is Node & {
|
|
90
|
+
type: K;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Object-shape of the {@link is} namespace: one predicate per `Node['type']`
|
|
94
|
+
* literal. Resolved lazily via a Proxy — every `is.X` access returns a stable
|
|
95
|
+
* predicate function (cached by discriminator).
|
|
96
|
+
*/
|
|
97
|
+
export type IsNamespace = {
|
|
98
|
+
[K in Node['type']]: NodeTypePredicate<K>;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Per-`Node['type']` predicate namespace. Covers every discriminator literal
|
|
102
|
+
* that oxc-parser's `Node` union currently exposes (and any future variants
|
|
103
|
+
* automatically), without per-type hand-written code.
|
|
104
|
+
*
|
|
105
|
+
* Usage:
|
|
106
|
+
*
|
|
107
|
+
* ```ts
|
|
108
|
+
* if (is.CallExpression(node)) {
|
|
109
|
+
* // node: CallExpression
|
|
110
|
+
* console.log(node.arguments);
|
|
111
|
+
* }
|
|
112
|
+
* ```
|
|
113
|
+
*
|
|
114
|
+
* Each `is.X` call is equivalent to `node?.type === 'X'` at runtime and to
|
|
115
|
+
* `node is Extract<Node, { type: 'X' }>` at the type level. Predicate
|
|
116
|
+
* functions are cached by discriminator, so `is.CallExpression ===
|
|
117
|
+
* is.CallExpression` holds across calls — safe to pass directly to
|
|
118
|
+
* `Array#filter` etc.
|
|
119
|
+
*
|
|
120
|
+
* Hand-written predicates with non-trivial JSDoc caveats (collision narrowing
|
|
121
|
+
* or union shorthand) — `isIdentifier`, `isMemberExpression`,
|
|
122
|
+
* `isTSQualifiedName`, `isFunctionDeclaration`, `isFunctionExpression`,
|
|
123
|
+
* `isFunctionNode` — remain exported alongside this namespace and continue to
|
|
124
|
+
* carry the documented runtime semantics.
|
|
125
|
+
*
|
|
126
|
+
* Defensive runtime behaviour: any non-string property access (Symbol keys),
|
|
127
|
+
* any string key that is not a PascalCase discriminator candidate (`then`,
|
|
128
|
+
* `toString`, `toJSON`, `valueOf`, `constructor`, `hasOwnProperty`, etc.), and
|
|
129
|
+
* any lowercase typo (`is.callExpression`) all return `undefined`. This is
|
|
130
|
+
* mandatory for hostable behaviour: without it, `is.then` would satisfy the
|
|
131
|
+
* Promise thenable probe — `await Promise.resolve(is)` deadlocks because the
|
|
132
|
+
* generated predicate ignores `resolve`/`reject`. Likewise `is.toString` would
|
|
133
|
+
* shadow `Object.prototype.toString`, making `String(is)` return `"false"` and
|
|
134
|
+
* `JSON.stringify(is)` return `"false"`. Calling a predicate with `null` /
|
|
135
|
+
* `undefined` returns `false`.
|
|
136
|
+
*/
|
|
137
|
+
export declare const is: IsNamespace;
|
|
74
138
|
export declare function getNodeName(node: unknown): string | null;
|
|
75
139
|
export declare function getStringLiteralValue(node: unknown): string | null;
|
|
76
140
|
export declare function getQualifiedName(expr: unknown): QualifiedName | null;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { parseSource } from './parse-source';
|
|
2
2
|
export { ParseCache } from './parse-cache';
|
|
3
3
|
export { buildLineOffsets, getLineColumn, } from './source-position';
|
|
4
|
-
export { getNodeHeader, isArrowFunctionExpression, isAssignmentExpression, isCallExpression, isFunctionDeclaration, isFunctionExpression, isFunctionNode, isIdentifier, isMemberExpression, isTSQualifiedName, isVariableDeclaration, getNodeName, getStringLiteralValue, getQualifiedName, } from './ast-utils';
|
|
4
|
+
export { getNodeHeader, isArrowFunctionExpression, isAssignmentExpression, isCallExpression, isFunctionDeclaration, isFunctionExpression, isFunctionNode, isIdentifier, isMemberExpression, isTSQualifiedName, isVariableDeclaration, getNodeName, getStringLiteralValue, getQualifiedName, is, } from './ast-utils';
|
|
5
|
+
export type { IsNamespace, NodeTypePredicate } from './ast-utils';
|
|
5
6
|
export { parseJsDoc } from './jsdoc-parser';
|
|
6
7
|
export type { ParsedFile, SourcePosition, SourceSpan } from './types';
|
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import ts from "typescript";
|
|
5
5
|
/**
|
|
6
|
-
* `pos`
|
|
7
|
-
* 범위
|
|
6
|
+
* `pos` 위치를 포함하는 가장 작은(innermost) 노드를 반환한다.
|
|
7
|
+
* 범위 밖이거나 트리비아 위치면 `undefined`.
|
|
8
8
|
*
|
|
9
|
-
*
|
|
9
|
+
* 공개 API(`forEachChild`)만으로 하강 탐색한다 — `pos`를 실제로 포함하는
|
|
10
|
+
* (`getStart() <= pos < getEnd()`) 자식으로만 재귀하므로 가이드된 하강이다.
|
|
10
11
|
*/
|
|
11
12
|
export declare function findNodeAtPosition(sourceFile: ts.SourceFile, pos: 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, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from "./types";
|
|
14
|
+
import type { ResolvedType, SemanticReference, EnrichedReference, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from "./types";
|
|
15
15
|
export interface SemanticLayerOptions extends TscProgramOptions {
|
|
16
16
|
/** Override TypeCollector (for testing). */
|
|
17
17
|
typeCollector?: TypeCollector;
|
|
@@ -37,6 +37,7 @@ export declare class SemanticLayer {
|
|
|
37
37
|
collectFileTypes(filePath: string): Map<number, ResolvedType>;
|
|
38
38
|
collectTypesAtPositions(filePath: string, positions: number[]): Map<number, ResolvedType>;
|
|
39
39
|
findReferences(filePath: string, position: number): SemanticReference[];
|
|
40
|
+
findEnrichedReferences(filePath: string, position: number): EnrichedReference[];
|
|
40
41
|
findImplementations(filePath: string, position: number): Implementation[];
|
|
41
42
|
isTypeAssignableTo(sourceFilePath: string, sourcePosition: number, targetFilePath: string, targetPosition: number): boolean | null;
|
|
42
43
|
/**
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* reference-classifier — purely syntactic classification of identifier references.
|
|
3
|
+
*
|
|
4
|
+
* tsc's `LanguageService.findReferences` answers the authoritative binding
|
|
5
|
+
* question (which declaration a reference binds to, and `isWriteAccess`), but it
|
|
6
|
+
* does NOT distinguish *kinds* of writes. This module fills that gap by inspecting
|
|
7
|
+
* the syntactic context of an identifier — no type information is required.
|
|
8
|
+
*/
|
|
9
|
+
import ts from 'typescript';
|
|
10
|
+
/**
|
|
11
|
+
* The kind of write a reference represents.
|
|
12
|
+
*
|
|
13
|
+
* - `declaration` — a binding site (`var a`, `let {x}`, parameter, etc.).
|
|
14
|
+
* - `assignment` — plain assignment (`a = …`).
|
|
15
|
+
* - `compound-assignment` — arithmetic/bitwise compound (`a += …`, `a &= …`).
|
|
16
|
+
* - `logical-assignment` — short-circuit compound (`a &&= …`, `a ||= …`, `a ??= …`).
|
|
17
|
+
* - `update` — increment/decrement (`a++`, `--a`).
|
|
18
|
+
*/
|
|
19
|
+
export type WriteKind = 'declaration' | 'assignment' | 'compound-assignment' | 'logical-assignment' | 'update';
|
|
20
|
+
/** The kind of scope that lexically encloses a reference. */
|
|
21
|
+
export type ScopeKind = 'function' | 'module' | 'block';
|
|
22
|
+
/**
|
|
23
|
+
* The nearest scope enclosing a reference, with the scope-defining node's span
|
|
24
|
+
* for identity (two distinct blocks have distinct spans — needed by flow analysis).
|
|
25
|
+
*/
|
|
26
|
+
export interface EnclosingScope {
|
|
27
|
+
kind: ScopeKind;
|
|
28
|
+
/** Start offset of the scope-defining node. */
|
|
29
|
+
pos: number;
|
|
30
|
+
/** End offset of the scope-defining node. */
|
|
31
|
+
end: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Whether `decl` is an ambient declaration (no runtime definition) — `declare`
|
|
35
|
+
* declarations, members of `declare namespace`/`declare module`/`declare global`,
|
|
36
|
+
* and anything in a `.d.ts` declaration file.
|
|
37
|
+
*
|
|
38
|
+
* This is a per-declaration primitive. A *symbol* may have multiple declarations
|
|
39
|
+
* (declaration merging); the integration layer composes ambientness across them
|
|
40
|
+
* (`symbol.declarations.every(isAmbientDeclaration)` — ambient only when no
|
|
41
|
+
* declaration carries a runtime definition).
|
|
42
|
+
*/
|
|
43
|
+
export declare function isAmbientDeclaration(decl: ts.Declaration): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Find the nearest scope (`function` | `module` | `block`) that lexically
|
|
46
|
+
* encloses `node`. A function body's own block reports as `function`; nested
|
|
47
|
+
* blocks, `for` bodies and `catch` bodies report as `block`; the source file and
|
|
48
|
+
* `namespace`/`module` bodies report as `module`. Always resolves (module is the
|
|
49
|
+
* root fallback).
|
|
50
|
+
*/
|
|
51
|
+
export declare function getEnclosingScope(node: ts.Node): EnclosingScope;
|
|
52
|
+
/**
|
|
53
|
+
* Classify whether `node` is a write reference, and of what kind.
|
|
54
|
+
*
|
|
55
|
+
* Returns the {@link WriteKind} when the identifier occupies a write position,
|
|
56
|
+
* or `undefined` when it is a read. The compound/logical/update kinds also read
|
|
57
|
+
* their target; splitting out that read-component is the caller's responsibility.
|
|
58
|
+
*/
|
|
59
|
+
export declare function classifyWriteKind(node: ts.Identifier): WriteKind | undefined;
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* 텍스트 검색과 달리 심볼 identity 기반으로 참조를 찾으므로
|
|
5
5
|
* rename, re-export, shadowing을 정확히 처리한다.
|
|
6
6
|
*/
|
|
7
|
-
import type { SemanticReference } from "./types";
|
|
7
|
+
import type { EnrichedReference, SemanticReference } from "./types";
|
|
8
8
|
import type { TscProgram } from "./tsc-program";
|
|
9
9
|
export declare class ReferenceResolver {
|
|
10
10
|
#private;
|
|
@@ -16,4 +16,10 @@ export declare class ReferenceResolver {
|
|
|
16
16
|
* - LanguageService.findReferences를 사용하므로 cross-file 참조도 포함된다.
|
|
17
17
|
*/
|
|
18
18
|
findAt(filePath: string, position: number): SemanticReference[];
|
|
19
|
+
/**
|
|
20
|
+
* Like {@link findAt}, but enriches each reference with `writeKind`,
|
|
21
|
+
* `isAmbient`, and `enclosingScope` — the syntactic metadata that
|
|
22
|
+
* `findReferences` does not provide. Returns `[]` if disposed or unresolved.
|
|
23
|
+
*/
|
|
24
|
+
findEnrichedAt(filePath: string, position: number): EnrichedReference[];
|
|
19
25
|
}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* All types in this file are plain data shapes — no runtime logic.
|
|
5
5
|
* The Semantic Layer is opt-in via `Gildash.open({ semantic: true })`.
|
|
6
6
|
*/
|
|
7
|
+
import type { WriteKind, EnclosingScope } from './reference-classifier';
|
|
7
8
|
/**
|
|
8
9
|
* The resolved type of a TypeScript symbol, as determined by the tsc TypeChecker.
|
|
9
10
|
*
|
|
@@ -70,6 +71,30 @@ export interface SemanticReference {
|
|
|
70
71
|
/** Whether this reference is a write (assignment) rather than a read. */
|
|
71
72
|
isWrite: boolean;
|
|
72
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* A {@link SemanticReference} enriched with the syntactic classification that
|
|
76
|
+
* tsc's `findReferences` does not provide on its own: the kind of write, whether
|
|
77
|
+
* the binding is ambient (no runtime definition), and the lexical scope in which
|
|
78
|
+
* the reference occurs.
|
|
79
|
+
*
|
|
80
|
+
* Binding identity (which declaration each reference binds to, including `var`
|
|
81
|
+
* hoisting and shadowing) is supplied authoritatively by tsc; these fields layer
|
|
82
|
+
* dataflow-relevant metadata on top.
|
|
83
|
+
*/
|
|
84
|
+
export interface EnrichedReference extends SemanticReference {
|
|
85
|
+
/**
|
|
86
|
+
* The kind of write, or `undefined` for reads. Compound/logical/update writes
|
|
87
|
+
* also read their target — splitting that read-component is the consumer's job.
|
|
88
|
+
*/
|
|
89
|
+
writeKind?: WriteKind;
|
|
90
|
+
/**
|
|
91
|
+
* `true` when the binding has no runtime definition (all declarations are
|
|
92
|
+
* ambient: `declare` / `.d.ts`). Computed across the symbol's declarations.
|
|
93
|
+
*/
|
|
94
|
+
isAmbient: boolean;
|
|
95
|
+
/** The lexical scope in which this reference occurs. */
|
|
96
|
+
enclosingScope: EnclosingScope;
|
|
97
|
+
}
|
|
73
98
|
/**
|
|
74
99
|
* A concrete implementation of an interface or abstract class,
|
|
75
100
|
* found via `LanguageService.getImplementationAtPosition` and
|