forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresolution.test.ts
More file actions
1606 lines (1419 loc) · 56.4 KB
/
resolution.test.ts
File metadata and controls
1606 lines (1419 loc) · 56.4 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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Resolution Module Tests
*
* Tests for Phase 3: Reference Resolution
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph } from '../src';
import { Node, UnresolvedReference } from '../src/types';
import { ReferenceResolver, createResolver, ResolutionContext } from '../src/resolution';
import { matchReference } from '../src/resolution/name-matcher';
import { resolveImportPath, extractImportMappings, resolveJvmImport, loadCppIncludeDirs, clearCppIncludeDirCache } from '../src/resolution/import-resolver';
import type { UnresolvedRef } from '../src/resolution/types';
import { detectFrameworks, getAllFrameworkResolvers } from '../src/resolution/frameworks';
import { QueryBuilder } from '../src/db/queries';
import { DatabaseConnection } from '../src/db';
describe('Resolution Module', () => {
let tempDir: string;
let cg: CodeGraph;
beforeEach(() => {
// Create temp directory
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-resolution-test-'));
});
afterEach(() => {
// Clean up
if (cg) {
cg.destroy();
} else if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true });
}
});
describe('Name Matcher', () => {
it('should match exact name references', () => {
// Create a mock context
const mockNodes: Node[] = [
{
id: 'func:test.ts:myFunction:10',
kind: 'function',
name: 'myFunction',
qualifiedName: 'test.ts::myFunction',
filePath: 'test.ts',
language: 'typescript',
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
];
const context: ResolutionContext = {
getNodesInFile: () => mockNodes,
getNodesByName: (name) => mockNodes.filter((n) => n.name === name),
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => ['test.ts'],
};
const ref = {
fromNodeId: 'caller:main.ts:caller:5',
referenceName: 'myFunction',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'main.ts',
language: 'typescript' as const,
};
const result = matchReference(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('func:test.ts:myFunction:10');
expect(result?.resolvedBy).toBe('exact-match');
});
it('should prefer same-module candidates over cross-module matches', () => {
// Simulates a Python monorepo where multiple apps define navigate()
const candidateA: Node = {
id: 'func:apps/app_a/src/server.py:navigate:10',
kind: 'function',
name: 'navigate',
qualifiedName: 'apps/app_a/src/server.py::navigate',
filePath: 'apps/app_a/src/server.py',
language: 'python',
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
const candidateB: Node = {
id: 'func:apps/app_b/src/server.py:navigate:15',
kind: 'function',
name: 'navigate',
qualifiedName: 'apps/app_b/src/server.py::navigate',
filePath: 'apps/app_b/src/server.py',
language: 'python',
startLine: 15,
endLine: 25,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: (name) => name === 'navigate' ? [candidateA, candidateB] : [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => [],
getNodesByLowerName: () => [],
getImportMappings: () => [],
};
// Reference from app_a should resolve to app_a's navigate, not app_b's
const ref = {
fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
referenceName: 'navigate',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'apps/app_a/src/handler.py',
language: 'python' as const,
};
const result = matchReference(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('func:apps/app_a/src/server.py:navigate:10');
expect(result?.resolvedBy).toBe('exact-match');
});
it('should lower confidence for cross-module exact matches', () => {
// Only one candidate but in a completely different module
const candidates: Node[] = [
{
id: 'func:apps/app_b/src/server.py:navigate:10',
kind: 'function',
name: 'navigate',
qualifiedName: 'apps/app_b/src/server.py::navigate',
filePath: 'apps/app_b/src/server.py',
language: 'python',
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
{
id: 'func:apps/app_c/src/server.py:navigate:10',
kind: 'function',
name: 'navigate',
qualifiedName: 'apps/app_c/src/server.py::navigate',
filePath: 'apps/app_c/src/server.py',
language: 'python',
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
];
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: (name) => name === 'navigate' ? candidates : [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => [],
getNodesByLowerName: () => [],
getImportMappings: () => [],
};
// Reference from app_a — neither candidate is in the same module
const ref = {
fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
referenceName: 'navigate',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'apps/app_a/src/handler.py',
language: 'python' as const,
};
const result = matchReference(ref, context);
// Should still resolve but with low confidence
expect(result).not.toBeNull();
expect(result?.confidence).toBeLessThanOrEqual(0.4);
});
it('should match qualified name references', () => {
const mockClassNode: Node = {
id: 'class:user.ts:User:5',
kind: 'class',
name: 'User',
qualifiedName: 'user.ts::User',
filePath: 'user.ts',
language: 'typescript',
startLine: 5,
endLine: 30,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
const mockMethodNode: Node = {
id: 'method:user.ts:User.save:15',
kind: 'method',
name: 'save',
qualifiedName: 'user.ts::User::save',
filePath: 'user.ts',
language: 'typescript',
startLine: 15,
endLine: 25,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
const context: ResolutionContext = {
getNodesInFile: (fp) => fp === 'user.ts' ? [mockClassNode, mockMethodNode] : [],
getNodesByName: (name) => {
if (name === 'User') return [mockClassNode];
if (name === 'save') return [mockMethodNode];
return [];
},
getNodesByQualifiedName: (qn) => {
if (qn === 'user.ts::User::save') return [mockMethodNode];
return [];
},
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => ['user.ts'],
};
const ref = {
fromNodeId: 'caller:main.ts:main:5',
referenceName: 'User.save',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'main.ts',
language: 'typescript' as const,
};
const result = matchReference(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('method:user.ts:User.save:15');
});
});
describe('Import Resolver', () => {
it('should resolve relative import paths', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: (p) => p === 'src/components/utils.ts' || p === 'src/components/utils/index.ts',
readFile: () => null,
getProjectRoot: () => '',
getAllFiles: () => ['src/components/utils.ts', 'src/components/utils/index.ts'],
};
const result = resolveImportPath(
'./utils',
'src/components/Button.ts',
'typescript',
context
);
expect(result).toBe('src/components/utils.ts');
});
it('should resolve parent directory imports', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: (p) => p === 'src/helpers.ts' || p === 'src/helpers/index.ts',
readFile: () => null,
getProjectRoot: () => '',
getAllFiles: () => ['src/helpers.ts', 'src/helpers/index.ts'],
};
const result = resolveImportPath(
'../helpers',
'src/components/Button.ts',
'typescript',
context
);
expect(result).toBe('src/helpers.ts');
});
it('should extract JS/TS import mappings', () => {
const content = `
import { foo } from './foo';
import bar from '../bar';
import * as utils from './utils';
import { baz, qux } from './baz';
`;
const mappings = extractImportMappings(
'src/index.ts',
content,
'typescript'
);
expect(mappings.length).toBeGreaterThan(0);
expect(mappings.some((m) => m.localName === 'foo')).toBe(true);
expect(mappings.some((m) => m.localName === 'bar')).toBe(true);
});
it('should extract Python import mappings', () => {
const content = `
from utils import helper
from .models import User
import os
from ..services import auth_service
`;
const mappings = extractImportMappings(
'src/main.py',
content,
'python'
);
expect(mappings.length).toBeGreaterThan(0);
expect(mappings.some((m) => m.localName === 'helper')).toBe(true);
expect(mappings.some((m) => m.localName === 'User')).toBe(true);
});
});
describe('JVM FQN Import Resolution', () => {
// Build a ResolutionContext stub whose getNodesByQualifiedName answers
// from a fixed table — the only context method resolveJvmImport touches.
const makeContext = (byQName: Record<string, Node[]>): ResolutionContext => ({
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: (q) => byQName[q] ?? [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: () => null,
getProjectRoot: () => '',
getAllFiles: () => [],
});
const node = (id: string, name: string, qualifiedName: string, kind: Node['kind'] = 'class', language: Node['language'] = 'kotlin'): Node => ({
id, kind, name, qualifiedName,
filePath: 'Models.kt', language,
startLine: 1, endLine: 1, startColumn: 0, endColumn: 0,
updatedAt: 0,
});
const importRef = (referenceName: string, language: Node['language'] = 'kotlin'): UnresolvedRef => ({
fromNodeId: 'caller',
referenceName,
referenceKind: 'imports',
line: 1, column: 0,
filePath: 'Caller.kt',
language,
});
it('resolves a Kotlin class import by FQN regardless of filename', () => {
const target = node('n1', 'Bar', 'com.example.foo::Bar');
const ctx = makeContext({ 'com.example.foo::Bar': [target] });
const result = resolveJvmImport(importRef('com.example.foo.Bar'), ctx);
expect(result?.targetNodeId).toBe('n1');
expect(result?.resolvedBy).toBe('import');
});
it('resolves a Kotlin top-level function import by FQN', () => {
const util = node('n2', 'util', 'com.example.foo::util', 'function');
const ctx = makeContext({ 'com.example.foo::util': [util] });
const result = resolveJvmImport(importRef('com.example.foo.util'), ctx);
expect(result?.targetNodeId).toBe('n2');
});
it('resolves a Java import by FQN', () => {
const target = node('n3', 'Bar', 'com.example.foo::Bar', 'class', 'java');
const ctx = makeContext({ 'com.example.foo::Bar': [target] });
const result = resolveJvmImport(importRef('com.example.foo.Bar', 'java'), ctx);
expect(result?.targetNodeId).toBe('n3');
});
it('resolves cross-language: Kotlin importing a Java class', () => {
// The Kotlin file declares `import com.example.JavaBar` — the target is
// a Java class node. JVM interop means the resolver doesn't care about
// the source language of the target, only that the FQN matches.
const target = node('n4', 'JavaBar', 'com.example::JavaBar', 'class', 'java');
const ctx = makeContext({ 'com.example::JavaBar': [target] });
const result = resolveJvmImport(importRef('com.example.JavaBar'), ctx);
expect(result?.targetNodeId).toBe('n4');
});
it('disambiguates a name collision across packages', () => {
// Two classes named `Bar` in different packages. Each import resolves
// to the one whose FQN matches — not to "whichever was found first".
const barA = node('n5a', 'Bar', 'com.example.alpha::Bar');
const barB = node('n5b', 'Bar', 'com.example.beta::Bar');
const ctx = makeContext({
'com.example.alpha::Bar': [barA],
'com.example.beta::Bar': [barB],
});
expect(resolveJvmImport(importRef('com.example.alpha.Bar'), ctx)?.targetNodeId).toBe('n5a');
expect(resolveJvmImport(importRef('com.example.beta.Bar'), ctx)?.targetNodeId).toBe('n5b');
});
it('returns null for wildcard imports', () => {
const ctx = makeContext({});
expect(resolveJvmImport(importRef('com.example.foo.*'), ctx)).toBeNull();
});
it('returns null for unqualified names', () => {
// A single-segment name has no package; nothing to look up by FQN.
const ctx = makeContext({ 'Bar': [node('n6', 'Bar', 'Bar')] });
expect(resolveJvmImport(importRef('Bar'), ctx)).toBeNull();
});
it('returns null for non-JVM languages', () => {
const target = node('n7', 'Bar', 'com.example::Bar');
const ctx = makeContext({ 'com.example::Bar': [target] });
expect(resolveJvmImport(importRef('com.example.Bar', 'typescript'), ctx)).toBeNull();
});
it('returns null for non-imports reference kinds', () => {
// The resolver intentionally only acts on `imports` refs; ordinary
// `calls`/`extends` refs fall through to the framework + name-matcher
// strategies.
const target = node('n8', 'Bar', 'com.example::Bar');
const ctx = makeContext({ 'com.example::Bar': [target] });
const ref: UnresolvedRef = {
fromNodeId: 'caller', referenceName: 'com.example.Bar',
referenceKind: 'calls', line: 1, column: 0,
filePath: 'Caller.kt', language: 'kotlin',
};
expect(resolveJvmImport(ref, ctx)).toBeNull();
});
it('returns null when the FQN is not in the index', () => {
const ctx = makeContext({});
expect(resolveJvmImport(importRef('com.example.Unknown'), ctx)).toBeNull();
});
});
describe('Framework Detection', () => {
it('should detect React framework', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: (p) => {
if (p === 'package.json') {
return JSON.stringify({
dependencies: { react: '^18.0.0' },
});
}
return null;
},
getProjectRoot: () => '/test',
getAllFiles: () => ['package.json', 'src/App.tsx'],
};
const frameworks = detectFrameworks(context);
expect(frameworks.some((f) => f.name === 'react')).toBe(true);
});
it('should detect Express framework', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: (p) => {
if (p === 'package.json') {
return JSON.stringify({
dependencies: { express: '^4.18.0' },
});
}
return null;
},
getProjectRoot: () => '/test',
getAllFiles: () => ['package.json', 'src/app.js'],
};
const frameworks = detectFrameworks(context);
expect(frameworks.some((f) => f.name === 'express')).toBe(true);
});
it('should detect Laravel framework', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: (p) => p === 'artisan',
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => ['artisan', 'app/Http/Kernel.php'],
};
const frameworks = detectFrameworks(context);
expect(frameworks.some((f) => f.name === 'laravel')).toBe(true);
});
it('should return all framework resolvers', () => {
const resolvers = getAllFrameworkResolvers();
expect(resolvers.length).toBeGreaterThan(0);
expect(resolvers.some((r) => r.name === 'react')).toBe(true);
expect(resolvers.some((r) => r.name === 'express')).toBe(true);
expect(resolvers.some((r) => r.name === 'laravel')).toBe(true);
});
});
describe('React Framework Resolver', () => {
it('should resolve React component references', () => {
const mockNodes: Node[] = [
{
id: 'component:src/Button.tsx:Button:5',
kind: 'component',
name: 'Button',
qualifiedName: 'src/Button.tsx::Button',
filePath: 'src/Button.tsx',
language: 'tsx',
startLine: 5,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
];
const context: ResolutionContext = {
getNodesInFile: (fp) => (fp === 'src/Button.tsx' ? mockNodes : []),
getNodesByName: () => mockNodes,
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: (p) => {
if (p === 'package.json') {
return JSON.stringify({ dependencies: { react: '^18.0.0' } });
}
return null;
},
getProjectRoot: () => '/test',
getAllFiles: () => ['package.json', 'src/Button.tsx', 'src/App.tsx'],
};
const frameworks = detectFrameworks(context);
const reactResolver = frameworks.find((f) => f.name === 'react');
expect(reactResolver).toBeDefined();
const ref = {
fromNodeId: 'component:src/App.tsx:App:1',
referenceName: 'Button',
referenceKind: 'renders' as const,
line: 10,
column: 5,
filePath: 'src/App.tsx',
language: 'typescript' as const,
};
const result = reactResolver!.resolve(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('component:src/Button.tsx:Button:5');
});
it('should resolve custom hook references', () => {
const mockNodes: Node[] = [
{
id: 'hook:src/hooks/useAuth.ts:useAuth:1',
kind: 'function',
name: 'useAuth',
qualifiedName: 'src/hooks/useAuth.ts::useAuth',
filePath: 'src/hooks/useAuth.ts',
language: 'typescript',
startLine: 1,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
];
const context: ResolutionContext = {
getNodesInFile: (fp) => (fp.includes('useAuth') ? mockNodes : []),
getNodesByName: () => mockNodes,
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: (p) => {
if (p === 'package.json') {
return JSON.stringify({ dependencies: { react: '^18.0.0' } });
}
return null;
},
getProjectRoot: () => '/test',
getAllFiles: () => ['package.json', 'src/hooks/useAuth.ts'],
};
const frameworks = detectFrameworks(context);
const reactResolver = frameworks.find((f) => f.name === 'react');
const ref = {
fromNodeId: 'component:src/App.tsx:App:1',
referenceName: 'useAuth',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'src/App.tsx',
language: 'typescript' as const,
};
const result = reactResolver!.resolve(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('hook:src/hooks/useAuth.ts:useAuth:1');
});
});
describe('Integration Tests', () => {
it('should create resolver from CodeGraph instance', async () => {
// Create a simple TypeScript project
fs.writeFileSync(
path.join(tempDir, 'package.json'),
JSON.stringify({ name: 'test', dependencies: { react: '^18.0.0' } })
);
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir);
// Create utility file
fs.writeFileSync(
path.join(srcDir, 'utils.ts'),
`export function formatDate(date: Date): string {
return date.toISOString();
}
export function parseDate(str: string): Date {
return new Date(str);
}`
);
// Create main file that uses utils
fs.writeFileSync(
path.join(srcDir, 'main.ts'),
`import { formatDate, parseDate } from './utils';
function processDate(input: string): string {
const date = parseDate(input);
return formatDate(date);
}`
);
// Initialize and index
cg = await CodeGraph.init(tempDir, { index: true });
// Check that resolver detected React framework
const frameworks = cg.getDetectedFrameworks();
expect(frameworks).toContain('react');
// Get stats to verify indexing worked
const stats = cg.getStats();
expect(stats.fileCount).toBe(2);
expect(stats.nodeCount).toBeGreaterThan(0);
});
it('should resolve references after indexing', async () => {
// Create a project with references
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(
path.join(srcDir, 'helper.ts'),
`export function helperFunction(): void {
console.log('helper');
}`
);
fs.writeFileSync(
path.join(srcDir, 'main.ts'),
`import { helperFunction } from './helper';
function main(): void {
helperFunction();
}`
);
cg = await CodeGraph.init(tempDir, { index: true });
// Run reference resolution
const result = cg.resolveReferences();
// Should have attempted resolution
expect(result.stats.total).toBeGreaterThanOrEqual(0);
});
it('promotes calls→instantiates when target resolves to a class (Python)', async () => {
// Python has no `new` keyword — `Foo()` is the standard
// instantiation syntax. Extraction can't tell that apart from
// a function call without symbol info, so it emits a `calls`
// ref. Resolution promotes it to `instantiates` once the
// target is known to be a class.
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(
path.join(srcDir, 'app.py'),
`class UserService:
def __init__(self):
self.db = None
def bootstrap():
return UserService()
`
);
cg = await CodeGraph.init(tempDir, { index: true });
cg.resolveReferences();
const bootstrap = cg
.getNodesByKind('function')
.find((n) => n.name === 'bootstrap');
expect(bootstrap).toBeDefined();
const outgoing = cg.getOutgoingEdges(bootstrap!.id);
const instantiates = outgoing.find((e) => e.kind === 'instantiates');
expect(instantiates).toBeDefined();
// Same edge must NOT also appear as a `calls` edge — promotion
// replaces the kind, doesn't duplicate.
const callsToUserService = outgoing.filter(
(e) => e.kind === 'calls' && e.target === instantiates!.target
);
expect(callsToUserService).toHaveLength(0);
});
it('resolves Go cross-package qualified calls via go.mod module path (#388)', async () => {
// Pre-#388, every `pkga.FuncX(...)` call in a Go monorepo was flagged
// external (isExternalImport returned true for any non-`/internal/`
// import without `.`-prefix) and resolution fell through to name-match
// with path proximity — recall on cross-package callers was ~<1%.
fs.writeFileSync(
path.join(tempDir, 'go.mod'),
'module github.com/example/myproject\n\ngo 1.21\n'
);
const pkgaDir = path.join(tempDir, 'pkga');
const pkgbDir = path.join(tempDir, 'pkgb');
const pkgcDir = path.join(tempDir, 'pkgc');
fs.mkdirSync(pkgaDir);
fs.mkdirSync(pkgbDir);
fs.mkdirSync(pkgcDir);
// Same-name exported function in two packages — only the imported one
// should resolve. Exercises disambiguation, not just connectivity.
fs.writeFileSync(
path.join(pkgaDir, 'conv.go'),
'package pkga\nfunc Convert(x int) int { return x * 2 }\n'
);
fs.writeFileSync(
path.join(pkgbDir, 'conv.go'),
'package pkgb\nfunc Convert(x int) int { return x + 1 }\n'
);
fs.writeFileSync(
path.join(pkgcDir, 'use.go'),
`package pkgc
import "github.com/example/myproject/pkga"
func UsePkga() {
pkga.Convert(5)
}
`
);
cg = await CodeGraph.init(tempDir, { index: true });
const usePkga = cg.getNodesByKind('function').filter((n) => n.name ==='UsePkga')[0];
expect(usePkga).toBeDefined();
const outgoing = cg.getOutgoingEdges(usePkga!.id);
const callEdges = outgoing.filter((e) => e.kind === 'calls');
expect(callEdges).toHaveLength(1);
const target = cg.getNode(callEdges[0]!.target);
expect(target?.name).toBe('Convert');
// Critical: the resolver must pick the imported pkga's Convert,
// not pkgb's. With the broken (pre-fix) resolver this lands on
// whichever Convert happens to be cheaper under path proximity.
expect(target?.filePath.replace(/\\/g, '/')).toBe('pkga/conv.go');
});
it('resolves Go aliased imports across packages (#388)', async () => {
fs.writeFileSync(
path.join(tempDir, 'go.mod'),
'module github.com/example/myproject\n\ngo 1.21\n'
);
fs.mkdirSync(path.join(tempDir, 'pkgb'));
fs.mkdirSync(path.join(tempDir, 'pkgd'));
fs.writeFileSync(
path.join(tempDir, 'pkgb', 'lib.go'),
'package pkgb\nfunc Compute(x int) int { return x }\n'
);
fs.writeFileSync(
path.join(tempDir, 'pkgd', 'use.go'),
`package pkgd
import (
"fmt"
alias "github.com/example/myproject/pkgb"
)
func UseAliased() {
fmt.Println("hi")
alias.Compute(3)
}
`
);
cg = await CodeGraph.init(tempDir, { index: true });
const useAliased = cg.getNodesByKind('function').filter((n) => n.name ==='UseAliased')[0];
expect(useAliased).toBeDefined();
const calls = cg.getOutgoingEdges(useAliased!.id).filter((e) => e.kind === 'calls');
// fmt.Println is stdlib — must stay external. alias.Compute must resolve.
expect(calls).toHaveLength(1);
const target = cg.getNode(calls[0]!.target);
expect(target?.name).toBe('Compute');
expect(target?.filePath.replace(/\\/g, '/')).toBe('pkgb/lib.go');
});
it('TS type_alias object-shape members resolve method calls (#359)', async () => {
// Pre-#359, `recorder.stop()` (recorder: RecorderHandle) attached
// to `StdioMcpClient.stop` in a sibling directory via path-proximity
// because the type_alias had no `stop` node — only the unrelated
// class did. Now type_alias produces member nodes (property/method),
// so the camelCase receiver↔type word overlap pulls the call to
// `RecorderHandle::stop` instead of the look-alike class.
fs.mkdirSync(path.join(tempDir, 'voice'));
fs.mkdirSync(path.join(tempDir, 'codegraph'));
fs.writeFileSync(
path.join(tempDir, 'voice', 'recorder.ts'),
`export type RecorderHandle = {
wavPath: string;
stop: () => Promise<{ ok: true }>;
};
`
);
fs.writeFileSync(
path.join(tempDir, 'voice', 'controller.ts'),
`import type { RecorderHandle } from "./recorder";
export async function finaliseRecording(recorder: RecorderHandle) {
return await recorder.stop();
}
`
);
fs.writeFileSync(
path.join(tempDir, 'codegraph', 'stdio-client.ts'),
`export class StdioMcpClient {
private stopped = false;
async stop(): Promise<void> { this.stopped = true; }
}
`
);
cg = await CodeGraph.init(tempDir, { index: true });
const handleStop = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName === 'RecorderHandle::stop');
expect(handleStop).toBeDefined();
const clientStop = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName === 'StdioMcpClient::stop');
expect(clientStop).toBeDefined();
const handleCallers = cg.getIncomingEdges(handleStop!.id).filter((e) => e.kind === 'calls');
const clientCallers = cg.getIncomingEdges(clientStop!.id).filter((e) => e.kind === 'calls');
expect(handleCallers.length).toBeGreaterThanOrEqual(1);
// The class method must have NO callers — voice/'s call must NOT
// mis-attribute. A non-empty list would mean the false-positive
// path is still firing.
expect(clientCallers).toHaveLength(0);
// Function-typed property surfaces as a `method` node, not `property`,
// because `stop()` semantics at the call site are method semantics.
expect(handleStop!.kind).toBe('method');
});
it('Java import disambiguates same-name classes across modules (#314)', async () => {
// Pre-#314 the import resolver had no Java branch at all, so a
// multi-module Maven repo where `dao/converter/FooConverter` and
// `service/converter/FooConverter` both export a `convert` method
// resolved by file-path proximity — picking whichever class was
// closer to the caller, which is wrong any time the caller lives
// in an equidistant cross-cutting module.
const daoDir = path.join(tempDir, 'dao/src/main/java/com/example/dao/converter');
const serviceDir = path.join(tempDir, 'service/src/main/java/com/example/service/converter');
const webDir = path.join(tempDir, 'web/src/main/java/com/example/web');
fs.mkdirSync(daoDir, { recursive: true });
fs.mkdirSync(serviceDir, { recursive: true });
fs.mkdirSync(webDir, { recursive: true });
fs.writeFileSync(
path.join(daoDir, 'FooConverter.java'),
`package com.example.dao.converter;
public class FooConverter { public String convert(String x) { return "dao:" + x; } }
`
);
fs.writeFileSync(
path.join(serviceDir, 'FooConverter.java'),
`package com.example.service.converter;
public class FooConverter { public String convert(String x) { return "svc:" + x; } }
`
);
// The caller imports the SERVICE version — even though dao is
// alphabetically/lexically first in the candidate list, the
// import must trump that order.
fs.writeFileSync(
path.join(webDir, 'Handler.java'),
`package com.example.web;
import com.example.service.converter.FooConverter;
public class Handler {
private FooConverter fooConverter;
public String use() { return fooConverter.convert("input"); }
}
`
);
cg = await CodeGraph.init(tempDir, { index: true });
const use = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName === 'com.example.web::Handler::use');
expect(use).toBeDefined();
const calls = cg.getOutgoingEdges(use!.id).filter((e) => e.kind === 'calls');
expect(calls.length).toBeGreaterThanOrEqual(1);
const target = cg.getNode(calls[0]!.target);
expect(target?.name).toBe('convert');
expect(target?.filePath.replace(/\\/g, '/')).toBe(
'service/src/main/java/com/example/service/converter/FooConverter.java'
);
});
it('C# extracts references from method/property/field types (#381)', async () => {
// Pre-#381, every C# project produced ZERO `references` edges:
// csharp.ts was missing returnField, and the type-leaf walker
// only recognized TS/Java's `type_identifier` nodes — C# uses
// `identifier`/`predefined_type`/`qualified_name`/`generic_name`.
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(
path.join(srcDir, 'Dtos.cs'),
`namespace MyApp;
public class SessionInfoDto { public string Id { get; set; } = ""; }
public class UserDto { public string Name { get; set; } = ""; }
`
);
fs.writeFileSync(
path.join(srcDir, 'Service.cs'),
`using System.Threading.Tasks;
namespace MyApp;
public class DataExporter
{
public SessionInfoDto Build(UserDto user, SessionInfoDto session) { return session; }
public Task<SessionInfoDto> BuildAsync(UserDto user) { return Task.FromResult(new SessionInfoDto()); }
public SessionInfoDto Latest { get; set; } = new();
private UserDto _cached;
}
`