-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsymbol-references.ts
More file actions
150 lines (124 loc) · 3.97 KB
/
symbol-references.ts
File metadata and controls
150 lines (124 loc) · 3.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { promises as fs } from 'fs';
import path from 'path';
import { CODEBASE_CONTEXT_DIRNAME, KEYWORD_INDEX_FILENAME } from '../constants/codebase-context.js';
import { IndexCorruptedError } from '../errors/index.js';
interface IndexedChunk {
content?: unknown;
startLine?: unknown;
relativePath?: unknown;
filePath?: unknown;
}
export interface SymbolUsage {
file: string;
line: number;
preview: string;
}
interface SymbolReferencesSuccess {
status: 'success';
symbol: string;
usageCount: number;
usages: SymbolUsage[];
confidence: 'syntactic';
isComplete: boolean;
}
interface SymbolReferencesError {
status: 'error';
message: string;
}
export type SymbolReferencesResult = SymbolReferencesSuccess | SymbolReferencesError;
function escapeRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function getUsageFile(rootPath: string, chunk: IndexedChunk): string {
if (typeof chunk.relativePath === 'string' && chunk.relativePath.trim()) {
return chunk.relativePath.replace(/\\/g, '/');
}
if (typeof chunk.filePath === 'string' && chunk.filePath.trim()) {
const relativePath = path.relative(rootPath, chunk.filePath);
if (!relativePath || relativePath.startsWith('..')) {
return path.basename(chunk.filePath);
}
return relativePath.replace(/\\/g, '/');
}
return 'unknown';
}
function buildPreview(content: string, lineOffset: number): string {
const lines = content.split('\n');
const start = Math.max(0, lineOffset - 1);
const end = Math.min(lines.length, lineOffset + 2);
const previewLines = lines.slice(start, end);
return previewLines.join('\n').trim();
}
export async function findSymbolReferences(
rootPath: string,
symbol: string,
limit = 10
): Promise<SymbolReferencesResult> {
const normalizedSymbol = symbol.trim();
const normalizedLimit = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : 10;
if (!normalizedSymbol) {
return {
status: 'error',
message: 'Symbol is required'
};
}
const indexPath = path.join(rootPath, CODEBASE_CONTEXT_DIRNAME, KEYWORD_INDEX_FILENAME);
let chunksRaw: unknown;
try {
const content = await fs.readFile(indexPath, 'utf-8');
chunksRaw = JSON.parse(content);
} catch (error) {
throw new IndexCorruptedError(
`Keyword index missing or unreadable (rebuild required): ${
error instanceof Error ? error.message : String(error)
}`
);
}
if (Array.isArray(chunksRaw)) {
throw new IndexCorruptedError(
'Legacy keyword index format detected (missing header). Rebuild required.'
);
}
const chunks =
chunksRaw && typeof chunksRaw === 'object' && Array.isArray((chunksRaw as any).chunks)
? ((chunksRaw as any).chunks as unknown[])
: null;
if (!chunks) {
throw new IndexCorruptedError('Keyword index corrupted: expected { header, chunks }');
}
const usages: SymbolUsage[] = [];
let usageCount = 0;
const escapedSymbol = escapeRegex(normalizedSymbol);
const matcher = new RegExp(`\\b${escapedSymbol}\\b`, 'g');
for (const chunkRaw of chunks) {
const chunk = chunkRaw as IndexedChunk;
if (typeof chunk.content !== 'string') {
continue;
}
const chunkContent = chunk.content;
const startLine = typeof chunk.startLine === 'number' ? chunk.startLine : 1;
matcher.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = matcher.exec(chunkContent)) !== null) {
usageCount += 1;
if (usages.length >= normalizedLimit) {
continue;
}
const prefix = chunkContent.slice(0, match.index);
const lineOffset = prefix.split('\n').length - 1;
usages.push({
file: getUsageFile(rootPath, chunk),
line: startLine + lineOffset,
preview: buildPreview(chunkContent, lineOffset)
});
}
}
return {
status: 'success',
symbol: normalizedSymbol,
usageCount,
usages,
confidence: 'syntactic',
isComplete: usageCount < normalizedLimit
};
}