-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindexer.ts
More file actions
716 lines (639 loc) · 25 KB
/
indexer.ts
File metadata and controls
716 lines (639 loc) · 25 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/**
* Core Indexer - Orchestrates codebase indexing
* Scans files, delegates to analyzers, creates embeddings, stores in vector DB
*/
import { promises as fs } from 'fs';
import path from 'path';
import { glob } from 'glob';
import ignore from 'ignore';
import {
CodebaseMetadata,
CodeChunk,
IndexingProgress,
IndexingStats,
IndexingPhase,
CodebaseConfig
} from '../types/index.js';
import { analyzerRegistry } from './analyzer-registry.js';
import { isCodeFile, isBinaryFile } from '../utils/language-detection.js';
import { getEmbeddingProvider } from '../embeddings/index.js';
import { getStorageProvider, CodeChunkWithEmbedding } from '../storage/index.js';
import {
LibraryUsageTracker,
PatternDetector,
ImportGraph,
InternalFileGraph,
FileExport
} from '../utils/usage-tracker.js';
import { getFileCommitDates } from '../utils/git-dates.js';
export interface IndexerOptions {
rootPath: string;
config?: Partial<CodebaseConfig>;
onProgress?: (progress: IndexingProgress) => void;
}
export class CodebaseIndexer {
private rootPath: string;
private config: CodebaseConfig;
private progress: IndexingProgress;
private onProgressCallback?: (progress: IndexingProgress) => void;
constructor(options: IndexerOptions) {
this.rootPath = path.resolve(options.rootPath);
this.config = this.mergeConfig(options.config);
this.onProgressCallback = options.onProgress;
this.progress = {
phase: 'initializing',
percentage: 0,
filesProcessed: 0,
totalFiles: 0,
chunksCreated: 0,
errors: [],
startedAt: new Date()
};
}
private mergeConfig(userConfig?: Partial<CodebaseConfig>): CodebaseConfig {
const defaultConfig: CodebaseConfig = {
analyzers: {
angular: { enabled: true, priority: 100 },
react: { enabled: false, priority: 90 },
vue: { enabled: false, priority: 90 },
generic: { enabled: true, priority: 10 }
},
include: ['**/*.{ts,tsx,js,jsx,html,css,scss,sass,less}'],
exclude: ['node_modules/**', 'dist/**', 'build/**', '.git/**', 'coverage/**'],
respectGitignore: true,
parsing: {
maxFileSize: 1048576, // 1MB
chunkSize: 100,
chunkOverlap: 10,
parseTests: true,
parseNodeModules: false
},
styleGuides: {
autoDetect: true,
paths: ['STYLE_GUIDE.md', 'docs/style-guide.md', 'ARCHITECTURE.md'],
parseMarkdown: true
},
documentation: {
autoDetect: true,
includeReadmes: true,
includeChangelogs: false
},
embedding: {
provider: 'transformers',
model: 'Xenova/bge-small-en-v1.5',
batchSize: 100
},
skipEmbedding: false,
storage: {
provider: 'lancedb',
path: './codebase-index'
}
};
return {
...defaultConfig,
...userConfig,
analyzers: { ...defaultConfig.analyzers, ...userConfig?.analyzers },
parsing: { ...defaultConfig.parsing, ...userConfig?.parsing },
styleGuides: { ...defaultConfig.styleGuides, ...userConfig?.styleGuides },
documentation: {
...defaultConfig.documentation,
...userConfig?.documentation
},
embedding: { ...defaultConfig.embedding, ...userConfig?.embedding },
storage: { ...defaultConfig.storage, ...userConfig?.storage }
};
}
async index(): Promise<IndexingStats> {
const startTime = Date.now();
const stats: IndexingStats = {
totalFiles: 0,
indexedFiles: 0,
skippedFiles: 0,
totalChunks: 0,
totalLines: 0,
duration: 0,
avgChunkSize: 0,
componentsByType: {},
componentsByLayer: {
presentation: 0,
business: 0,
data: 0,
state: 0,
core: 0,
shared: 0,
feature: 0,
infrastructure: 0,
unknown: 0
},
errors: [],
startedAt: new Date()
};
try {
// Phase 1: Scanning
this.updateProgress('scanning', 0);
let files = await this.scanFiles();
// Memory safety: limit total files to prevent heap exhaustion
const MAX_FILES = 10000;
if (files.length > MAX_FILES) {
console.warn(
`WARNING: Found ${files.length} files, limiting to ${MAX_FILES} to prevent memory issues.`
);
console.warn(
`Consider using more specific include patterns or excluding large directories.`
);
files = files.slice(0, MAX_FILES);
}
stats.totalFiles = files.length;
this.progress.totalFiles = files.length;
console.error(`Found ${files.length} files to index`);
// Phase 2: Analyzing & Parsing
this.updateProgress('analyzing', 0);
const allChunks: CodeChunk[] = [];
const libraryTracker = new LibraryUsageTracker();
const patternDetector = new PatternDetector();
const importGraph = new ImportGraph();
const internalFileGraph = new InternalFileGraph(this.rootPath);
// Fetch git commit dates for pattern momentum analysis
const fileDates = await getFileCommitDates(this.rootPath);
for (let i = 0; i < files.length; i++) {
const file = files[i];
this.progress.currentFile = file;
this.progress.filesProcessed = i + 1;
this.progress.percentage = Math.round(((i + 1) / files.length) * 100);
try {
// Normalize line endings to \n for consistent cross-platform output
const rawContent = await fs.readFile(file, 'utf-8');
const content = rawContent.replace(/\r\n/g, '\n');
const result = await analyzerRegistry.analyzeFile(file, content);
if (result) {
allChunks.push(...result.chunks);
stats.indexedFiles++;
stats.totalLines += content.split('\n').length;
// Track library usage AND import graph from imports
for (const imp of result.imports) {
libraryTracker.track(imp.source, file);
importGraph.trackImport(imp.source, file, imp.line || 1);
// Track internal file-to-file imports (relative paths)
if (imp.source.startsWith('.')) {
// Resolve the relative import to an absolute path
const fileDir = path.dirname(file);
let resolvedPath = path.resolve(fileDir, imp.source);
// Try common extensions if not already specified
const ext = path.extname(resolvedPath);
if (!ext) {
for (const tryExt of ['.ts', '.tsx', '.js', '.jsx']) {
const withExt = resolvedPath + tryExt;
// We don't check if file exists for performance - just track what's referenced
resolvedPath = withExt;
break;
}
}
internalFileGraph.trackImport(file, resolvedPath, imp.imports);
}
}
// Track exports for unused export detection
if (result.exports && result.exports.length > 0) {
const fileExports: FileExport[] = result.exports.map((exp) => ({
name: exp.name,
type: exp.isDefault ? 'default' : (exp.type as FileExport['type']) || 'other'
}));
internalFileGraph.trackExports(file, fileExports);
}
// Detect generic patterns from code
patternDetector.detectFromCode(content, file);
// Helper to extract code snippet around a pattern
const extractSnippet = (
pattern: RegExp,
linesBefore = 1,
linesAfter = 3
): string | undefined => {
const match = content.match(pattern);
if (!match) return undefined;
const lines = content.split('\n');
const matchIndex = content.substring(0, match.index).split('\n').length - 1;
const start = Math.max(0, matchIndex - linesBefore);
const end = Math.min(lines.length, matchIndex + linesAfter + 1);
return lines.slice(start, end).join('\n').trim();
};
const relPath = file.split(/[\\/]/).slice(-3).join('/');
// Get file date for pattern momentum tracking
// Try multiple path formats since git uses forward slashes
const normalizedRelPath = path.relative(this.rootPath, file).replace(/\\/g, '/');
const fileDate = fileDates.get(normalizedRelPath);
// GENERIC PATTERN FORWARDING
// Framework analyzers return detectedPatterns in metadata - we just forward them
// This keeps the indexer framework-agnostic
if (result.metadata?.detectedPatterns) {
for (const pattern of result.metadata.detectedPatterns) {
// Try to extract a relevant snippet for the pattern
const snippetPattern = this.getSnippetPatternFor(pattern.category, pattern.name);
const snippet = snippetPattern ? extractSnippet(snippetPattern) : undefined;
patternDetector.track(
pattern.category,
pattern.name,
snippet ? { file: relPath, snippet } : undefined,
fileDate
);
}
}
// Track file for Golden File scoring (framework-agnostic based on patterns)
const detectedPatterns = result.metadata?.detectedPatterns || [];
const hasPattern = (category: string, name: string) =>
detectedPatterns.some(
(p: { category: string; name: string }) =>
p.category === category && p.name === name
);
const patternScore =
(hasPattern('dependencyInjection', 'inject() function') ? 1 : 0) +
(hasPattern('stateManagement', 'Signals') ? 1 : 0) +
(hasPattern('reactivity', 'Computed') ? 1 : 0) +
(hasPattern('reactivity', 'Effect') ? 1 : 0) +
(hasPattern('componentStyle', 'Standalone') ? 1 : 0) +
(hasPattern('componentInputs', 'Signal-based inputs') ? 1 : 0);
if (patternScore >= 3) {
patternDetector.trackGoldenFile(relPath, patternScore, {
inject: hasPattern('dependencyInjection', 'inject() function'),
signals: hasPattern('stateManagement', 'Signals'),
computed: hasPattern('reactivity', 'Computed'),
effect: hasPattern('reactivity', 'Effect'),
standalone: hasPattern('componentStyle', 'Standalone'),
signalInputs: hasPattern('componentInputs', 'Signal-based inputs')
});
}
// Update component statistics
for (const component of result.components) {
if (component.componentType) {
stats.componentsByType[component.componentType] =
(stats.componentsByType[component.componentType] || 0) + 1;
}
if (component.layer) {
stats.componentsByLayer[component.layer]++;
}
}
} else {
stats.skippedFiles++;
}
} catch (error) {
stats.skippedFiles++;
stats.errors.push({
filePath: file,
error: error instanceof Error ? error.message : String(error),
phase: 'analyzing',
timestamp: new Date()
});
}
if (this.onProgressCallback) {
this.onProgressCallback(this.progress);
}
}
stats.totalChunks = allChunks.length;
stats.avgChunkSize =
allChunks.length > 0
? Math.round(allChunks.reduce((sum, c) => sum + c.content.length, 0) / allChunks.length)
: 0;
// Memory safety: limit chunks to prevent embedding memory issues
const MAX_CHUNKS = 5000;
let chunksToEmbed = allChunks;
if (allChunks.length > MAX_CHUNKS) {
console.warn(
`WARNING: ${allChunks.length} chunks exceed limit. Indexing first ${MAX_CHUNKS} chunks.`
);
chunksToEmbed = allChunks.slice(0, MAX_CHUNKS);
}
// Phase 3: Embedding
const chunksWithEmbeddings: CodeChunkWithEmbedding[] = [];
if (!this.config.skipEmbedding) {
this.updateProgress('embedding', 50);
console.error(`Creating embeddings for ${chunksToEmbed.length} chunks...`);
// Initialize embedding provider
const embeddingProvider = await getEmbeddingProvider(this.config.embedding);
// Generate embeddings for all chunks
const batchSize = this.config.embedding?.batchSize || 32;
for (let i = 0; i < chunksToEmbed.length; i += batchSize) {
const batch = chunksToEmbed.slice(i, i + batchSize);
const texts = batch.map((chunk) => {
// Create a searchable text representation
const parts = [chunk.content];
if (chunk.metadata?.componentName) {
parts.unshift(`Component: ${chunk.metadata.componentName}`);
}
if (chunk.componentType) {
parts.unshift(`Type: ${chunk.componentType}`);
}
return parts.join('\n');
});
const embeddings = await embeddingProvider.embedBatch(texts);
for (let j = 0; j < batch.length; j++) {
chunksWithEmbeddings.push({
...batch[j],
embedding: embeddings[j]
});
}
// Update progress
const embeddingProgress = 50 + Math.round((i / chunksToEmbed.length) * 25);
this.updateProgress('embedding', embeddingProgress);
if ((i + batchSize) % 100 === 0 || i + batchSize >= chunksToEmbed.length) {
console.error(
`Embedded ${Math.min(i + batchSize, chunksToEmbed.length)}/${
chunksToEmbed.length
} chunks`
);
}
}
} else {
console.error('Skipping embedding generation (skipEmbedding=true)');
}
// Phase 4: Storing
this.updateProgress('storing', 75);
if (!this.config.skipEmbedding) {
console.error(`Storing ${chunksToEmbed.length} chunks...`);
// Store in LanceDB for vector search
const storagePath = path.join(this.rootPath, '.codebase-index');
const storageProvider = await getStorageProvider({ path: storagePath });
await storageProvider.clear(); // Clear existing index
await storageProvider.store(chunksWithEmbeddings);
}
// Also save JSON for keyword search (Fuse.js) - use chunksToEmbed for consistency
const indexPath = path.join(this.rootPath, '.codebase-index.json');
// Write without pretty-printing to save memory
await fs.writeFile(indexPath, JSON.stringify(chunksToEmbed));
// Save library usage and pattern stats
const intelligencePath = path.join(this.rootPath, '.codebase-intelligence.json');
const libraryStats = libraryTracker.getStats();
// Extract tsconfig paths for AI to understand import aliases
let tsconfigPaths: Record<string, string[]> | undefined;
try {
const tsconfigPath = path.join(this.rootPath, 'tsconfig.json');
const tsconfigContent = await fs.readFile(tsconfigPath, 'utf-8');
const tsconfig = JSON.parse(tsconfigContent);
if (tsconfig.compilerOptions?.paths) {
tsconfigPaths = tsconfig.compilerOptions.paths;
console.error(
`Found ${Object.keys(tsconfigPaths!).length} path aliases in tsconfig.json`
);
}
} catch (_error) {
// No tsconfig.json or no paths defined
}
const intelligence = {
libraryUsage: libraryStats,
patterns: patternDetector.getAllPatterns(),
goldenFiles: patternDetector.getGoldenFiles(5),
// tsconfig paths help AI understand import aliases (e.g., @mycompany/* -> libs/*)
// This reveals which @scoped packages are internal vs external
tsconfigPaths,
importGraph: {
usages: importGraph.getAllUsages(),
topUsed: importGraph.getTopUsed(30)
},
// Internal file graph for circular dependency and unused export detection
internalFileGraph: internalFileGraph.toJSON(),
generatedAt: new Date().toISOString()
};
await fs.writeFile(intelligencePath, JSON.stringify(intelligence, null, 2));
// Phase 5: Complete
this.updateProgress('complete', 100);
stats.duration = Date.now() - startTime;
stats.completedAt = new Date();
console.error(`Indexing complete in ${stats.duration}ms`);
console.error(`Indexed ${stats.indexedFiles} files, ${stats.totalChunks} chunks`);
return stats;
} catch (error) {
this.progress.phase = 'error';
stats.errors.push({
filePath: this.rootPath,
error: error instanceof Error ? error.message : String(error),
phase: this.progress.phase,
timestamp: new Date()
});
throw error;
}
}
private async scanFiles(): Promise<string[]> {
const files: string[] = [];
// Read .gitignore if respecting it
let ig: ReturnType<typeof ignore.default> | null = null;
if (this.config.respectGitignore) {
try {
const gitignorePath = path.join(this.rootPath, '.gitignore');
const gitignoreContent = await fs.readFile(gitignorePath, 'utf-8');
ig = ignore.default().add(gitignoreContent);
} catch (_error) {
// No .gitignore or couldn't read it
}
}
// Scan with glob
const includePatterns = this.config.include || ['**/*'];
const excludePatterns = this.config.exclude || [];
for (const pattern of includePatterns) {
const matches = await glob(pattern, {
cwd: this.rootPath,
absolute: true,
ignore: excludePatterns,
nodir: true
});
for (const file of matches) {
const relativePath = path.relative(this.rootPath, file);
// Check gitignore
if (ig && ig.ignores(relativePath)) {
continue;
}
// Check if it's a code file
if (!isCodeFile(file) || isBinaryFile(file)) {
continue;
}
// Check file size
try {
const stats = await fs.stat(file);
if (stats.size > (this.config.parsing?.maxFileSize || 1048576)) {
console.warn(`Skipping large file: ${file} (${stats.size} bytes)`);
continue;
}
} catch (_error) {
continue;
}
files.push(file);
}
}
return files;
}
private updateProgress(phase: IndexingPhase, percentage: number): void {
this.progress.phase = phase;
this.progress.percentage = percentage;
if (this.onProgressCallback) {
this.onProgressCallback(this.progress);
}
}
async detectMetadata(): Promise<CodebaseMetadata> {
// Get all registered analyzers (sorted by priority, highest first)
const analyzers = analyzerRegistry.getAll();
// Start with base metadata template
let metadata: CodebaseMetadata = {
name: path.basename(this.rootPath),
rootPath: this.rootPath,
languages: [],
dependencies: [],
architecture: {
type: 'mixed',
layers: {
presentation: 0,
business: 0,
data: 0,
state: 0,
core: 0,
shared: 0,
feature: 0,
infrastructure: 0,
unknown: 0
},
patterns: []
},
styleGuides: [],
documentation: [],
projectStructure: {
type: 'single-app'
},
statistics: {
totalFiles: 0,
totalLines: 0,
totalComponents: 0,
componentsByType: {},
componentsByLayer: {
presentation: 0,
business: 0,
data: 0,
state: 0,
core: 0,
shared: 0,
feature: 0,
infrastructure: 0,
unknown: 0
}
},
customMetadata: {}
};
// Loop through all analyzers (highest priority first) and merge their metadata
// Higher priority analyzers' values win on conflicts
for (const analyzer of analyzers) {
try {
const analyzerMeta = await analyzer.detectCodebaseMetadata(this.rootPath);
metadata = this.mergeMetadata(metadata, analyzerMeta);
} catch (error) {
// Analyzer failed, continue with next
console.warn(`Analyzer ${analyzer.name} failed to detect metadata:`, error);
}
}
// Load intelligence data if available
try {
const intelligencePath = path.join(this.rootPath, '.codebase-intelligence.json');
const intelligenceContent = await fs.readFile(intelligencePath, 'utf-8');
const intelligence = JSON.parse(intelligenceContent);
metadata.customMetadata = {
...metadata.customMetadata,
libraryUsage: intelligence.libraryUsage,
patterns: intelligence.patterns,
intelligenceGeneratedAt: intelligence.generatedAt
};
} catch (_error) {
// Intelligence file doesn't exist yet (indexing not run)
}
return metadata;
}
/**
* Merge two CodebaseMetadata objects.
* The 'incoming' metadata takes precedence for non-empty values.
*/
private mergeMetadata(base: CodebaseMetadata, incoming: CodebaseMetadata): CodebaseMetadata {
return {
name: incoming.name || base.name,
rootPath: incoming.rootPath || base.rootPath,
languages: [...new Set([...base.languages, ...incoming.languages])], // Merge and deduplicate
dependencies: this.mergeDependencies(base.dependencies, incoming.dependencies),
framework: incoming.framework || base.framework, // Framework from higher priority analyzer wins
architecture: {
type: incoming.architecture?.type || base.architecture.type,
layers: this.mergeLayers(base.architecture.layers, incoming.architecture?.layers),
patterns: [
...new Set([
...(base.architecture.patterns || []),
...(incoming.architecture?.patterns || [])
])
] // Merge and deduplicate
},
styleGuides: [...new Set([...base.styleGuides, ...incoming.styleGuides])], // Merge and deduplicate
documentation: [...new Set([...base.documentation, ...incoming.documentation])], // Merge and deduplicate
projectStructure:
incoming.projectStructure?.type !== 'single-app'
? incoming.projectStructure
: base.projectStructure,
statistics: this.mergeStatistics(base.statistics, incoming.statistics),
customMetadata: { ...base.customMetadata, ...incoming.customMetadata }
};
}
private mergeDependencies(base: any[], incoming: any[]): any[] {
const seen = new Set(base.map((d) => d.name));
const result = [...base];
for (const dep of incoming) {
if (!seen.has(dep.name)) {
result.push(dep);
seen.add(dep.name);
}
}
return result;
}
private mergeLayers(base: any, incoming?: any): any {
if (!incoming) return base;
return {
presentation: Math.max(base.presentation || 0, incoming.presentation || 0),
business: Math.max(base.business || 0, incoming.business || 0),
data: Math.max(base.data || 0, incoming.data || 0),
state: Math.max(base.state || 0, incoming.state || 0),
core: Math.max(base.core || 0, incoming.core || 0),
shared: Math.max(base.shared || 0, incoming.shared || 0),
feature: Math.max(base.feature || 0, incoming.feature || 0),
infrastructure: Math.max(base.infrastructure || 0, incoming.infrastructure || 0),
unknown: Math.max(base.unknown || 0, incoming.unknown || 0)
};
}
private mergeStatistics(base: any, incoming: any): any {
return {
totalFiles: Math.max(base.totalFiles || 0, incoming.totalFiles || 0),
totalLines: Math.max(base.totalLines || 0, incoming.totalLines || 0),
totalComponents: Math.max(base.totalComponents || 0, incoming.totalComponents || 0),
componentsByType: { ...base.componentsByType, ...incoming.componentsByType },
componentsByLayer: this.mergeLayers(base.componentsByLayer, incoming.componentsByLayer)
};
}
/**
* Get regex pattern for extracting code snippets based on pattern category and name
* This maps abstract pattern names to actual code patterns
*/
private getSnippetPatternFor(category: string, name: string): RegExp | null {
const patterns: Record<string, Record<string, RegExp>> = {
dependencyInjection: {
'inject() function': /\binject\s*[<(]/,
'Constructor injection': /constructor\s*\(/
},
stateManagement: {
RxJS: /BehaviorSubject|ReplaySubject|Subject|Observable/,
Signals: /\bsignal\s*[<(]/
},
reactivity: {
Effect: /\beffect\s*\(/,
Computed: /\bcomputed\s*[<(]/
},
componentStyle: {
Standalone: /standalone\s*:\s*true/,
'NgModule-based': /@(?:Component|Directive|Pipe)\s*\(/
},
componentInputs: {
'Signal-based inputs': /\binput\s*[<(]/,
'Decorator-based @Input': /@Input\(\)/
}
};
return patterns[category]?.[name] || null;
}
getProgress(): IndexingProgress {
return { ...this.progress };
}
}