resolution.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /**
  2. * Resolution Module Tests
  3. *
  4. * Tests for Phase 3: Reference Resolution
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { Node, UnresolvedReference } from '../src/types';
  12. import { ReferenceResolver, createResolver, ResolutionContext } from '../src/resolution';
  13. import { matchReference } from '../src/resolution/name-matcher';
  14. import { resolveImportPath, extractImportMappings } from '../src/resolution/import-resolver';
  15. import { detectFrameworks, getAllFrameworkResolvers } from '../src/resolution/frameworks';
  16. import { QueryBuilder } from '../src/db/queries';
  17. import { DatabaseConnection } from '../src/db';
  18. describe('Resolution Module', () => {
  19. let tempDir: string;
  20. let cg: CodeGraph;
  21. beforeEach(() => {
  22. // Create temp directory
  23. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-resolution-test-'));
  24. });
  25. afterEach(() => {
  26. // Clean up
  27. if (cg) {
  28. cg.destroy();
  29. } else if (fs.existsSync(tempDir)) {
  30. fs.rmSync(tempDir, { recursive: true });
  31. }
  32. });
  33. describe('Name Matcher', () => {
  34. it('should match exact name references', () => {
  35. // Create a mock context
  36. const mockNodes: Node[] = [
  37. {
  38. id: 'func:test.ts:myFunction:10',
  39. kind: 'function',
  40. name: 'myFunction',
  41. qualifiedName: 'test.ts::myFunction',
  42. filePath: 'test.ts',
  43. language: 'typescript',
  44. startLine: 10,
  45. endLine: 20,
  46. startColumn: 0,
  47. endColumn: 0,
  48. updatedAt: Date.now(),
  49. },
  50. ];
  51. const context: ResolutionContext = {
  52. getNodesInFile: () => mockNodes,
  53. getNodesByName: (name) => mockNodes.filter((n) => n.name === name),
  54. getNodesByQualifiedName: () => [],
  55. getNodesByKind: () => [],
  56. fileExists: () => true,
  57. readFile: () => null,
  58. getProjectRoot: () => '/test',
  59. getAllFiles: () => ['test.ts'],
  60. };
  61. const ref = {
  62. fromNodeId: 'caller:main.ts:caller:5',
  63. referenceName: 'myFunction',
  64. referenceKind: 'calls' as const,
  65. line: 5,
  66. column: 10,
  67. filePath: 'main.ts',
  68. language: 'typescript' as const,
  69. };
  70. const result = matchReference(ref, context);
  71. expect(result).not.toBeNull();
  72. expect(result?.targetNodeId).toBe('func:test.ts:myFunction:10');
  73. expect(result?.resolvedBy).toBe('exact-match');
  74. });
  75. it('should match qualified name references', () => {
  76. const mockClassNode: Node = {
  77. id: 'class:user.ts:User:5',
  78. kind: 'class',
  79. name: 'User',
  80. qualifiedName: 'user.ts::User',
  81. filePath: 'user.ts',
  82. language: 'typescript',
  83. startLine: 5,
  84. endLine: 30,
  85. startColumn: 0,
  86. endColumn: 0,
  87. updatedAt: Date.now(),
  88. };
  89. const mockMethodNode: Node = {
  90. id: 'method:user.ts:User.save:15',
  91. kind: 'method',
  92. name: 'save',
  93. qualifiedName: 'user.ts::User::save',
  94. filePath: 'user.ts',
  95. language: 'typescript',
  96. startLine: 15,
  97. endLine: 25,
  98. startColumn: 0,
  99. endColumn: 0,
  100. updatedAt: Date.now(),
  101. };
  102. const context: ResolutionContext = {
  103. getNodesInFile: (fp) => fp === 'user.ts' ? [mockClassNode, mockMethodNode] : [],
  104. getNodesByName: (name) => {
  105. if (name === 'User') return [mockClassNode];
  106. if (name === 'save') return [mockMethodNode];
  107. return [];
  108. },
  109. getNodesByQualifiedName: (qn) => {
  110. if (qn === 'user.ts::User::save') return [mockMethodNode];
  111. return [];
  112. },
  113. getNodesByKind: () => [],
  114. fileExists: () => true,
  115. readFile: () => null,
  116. getProjectRoot: () => '/test',
  117. getAllFiles: () => ['user.ts'],
  118. };
  119. const ref = {
  120. fromNodeId: 'caller:main.ts:main:5',
  121. referenceName: 'User.save',
  122. referenceKind: 'calls' as const,
  123. line: 5,
  124. column: 10,
  125. filePath: 'main.ts',
  126. language: 'typescript' as const,
  127. };
  128. const result = matchReference(ref, context);
  129. expect(result).not.toBeNull();
  130. expect(result?.targetNodeId).toBe('method:user.ts:User.save:15');
  131. });
  132. });
  133. describe('Import Resolver', () => {
  134. it('should resolve relative import paths', () => {
  135. const context: ResolutionContext = {
  136. getNodesInFile: () => [],
  137. getNodesByName: () => [],
  138. getNodesByQualifiedName: () => [],
  139. getNodesByKind: () => [],
  140. fileExists: (p) => p === 'src/components/utils.ts' || p === 'src/components/utils/index.ts',
  141. readFile: () => null,
  142. getProjectRoot: () => '',
  143. getAllFiles: () => ['src/components/utils.ts', 'src/components/utils/index.ts'],
  144. };
  145. const result = resolveImportPath(
  146. './utils',
  147. 'src/components/Button.ts',
  148. 'typescript',
  149. context
  150. );
  151. expect(result).toBe('src/components/utils.ts');
  152. });
  153. it('should resolve parent directory imports', () => {
  154. const context: ResolutionContext = {
  155. getNodesInFile: () => [],
  156. getNodesByName: () => [],
  157. getNodesByQualifiedName: () => [],
  158. getNodesByKind: () => [],
  159. fileExists: (p) => p === 'src/helpers.ts' || p === 'src/helpers/index.ts',
  160. readFile: () => null,
  161. getProjectRoot: () => '',
  162. getAllFiles: () => ['src/helpers.ts', 'src/helpers/index.ts'],
  163. };
  164. const result = resolveImportPath(
  165. '../helpers',
  166. 'src/components/Button.ts',
  167. 'typescript',
  168. context
  169. );
  170. expect(result).toBe('src/helpers.ts');
  171. });
  172. it('should extract JS/TS import mappings', () => {
  173. const content = `
  174. import { foo } from './foo';
  175. import bar from '../bar';
  176. import * as utils from './utils';
  177. import { baz, qux } from './baz';
  178. `;
  179. const mappings = extractImportMappings(
  180. 'src/index.ts',
  181. content,
  182. 'typescript'
  183. );
  184. expect(mappings.length).toBeGreaterThan(0);
  185. expect(mappings.some((m) => m.localName === 'foo')).toBe(true);
  186. expect(mappings.some((m) => m.localName === 'bar')).toBe(true);
  187. });
  188. it('should extract Python import mappings', () => {
  189. const content = `
  190. from utils import helper
  191. from .models import User
  192. import os
  193. from ..services import auth_service
  194. `;
  195. const mappings = extractImportMappings(
  196. 'src/main.py',
  197. content,
  198. 'python'
  199. );
  200. expect(mappings.length).toBeGreaterThan(0);
  201. expect(mappings.some((m) => m.localName === 'helper')).toBe(true);
  202. expect(mappings.some((m) => m.localName === 'User')).toBe(true);
  203. });
  204. });
  205. describe('Framework Detection', () => {
  206. it('should detect React framework', () => {
  207. const context: ResolutionContext = {
  208. getNodesInFile: () => [],
  209. getNodesByName: () => [],
  210. getNodesByQualifiedName: () => [],
  211. getNodesByKind: () => [],
  212. fileExists: () => false,
  213. readFile: (p) => {
  214. if (p === 'package.json') {
  215. return JSON.stringify({
  216. dependencies: { react: '^18.0.0' },
  217. });
  218. }
  219. return null;
  220. },
  221. getProjectRoot: () => '/test',
  222. getAllFiles: () => ['package.json', 'src/App.tsx'],
  223. };
  224. const frameworks = detectFrameworks(context);
  225. expect(frameworks.some((f) => f.name === 'react')).toBe(true);
  226. });
  227. it('should detect Express framework', () => {
  228. const context: ResolutionContext = {
  229. getNodesInFile: () => [],
  230. getNodesByName: () => [],
  231. getNodesByQualifiedName: () => [],
  232. getNodesByKind: () => [],
  233. fileExists: () => false,
  234. readFile: (p) => {
  235. if (p === 'package.json') {
  236. return JSON.stringify({
  237. dependencies: { express: '^4.18.0' },
  238. });
  239. }
  240. return null;
  241. },
  242. getProjectRoot: () => '/test',
  243. getAllFiles: () => ['package.json', 'src/app.js'],
  244. };
  245. const frameworks = detectFrameworks(context);
  246. expect(frameworks.some((f) => f.name === 'express')).toBe(true);
  247. });
  248. it('should detect Laravel framework', () => {
  249. const context: ResolutionContext = {
  250. getNodesInFile: () => [],
  251. getNodesByName: () => [],
  252. getNodesByQualifiedName: () => [],
  253. getNodesByKind: () => [],
  254. fileExists: (p) => p === 'artisan',
  255. readFile: () => null,
  256. getProjectRoot: () => '/test',
  257. getAllFiles: () => ['artisan', 'app/Http/Kernel.php'],
  258. };
  259. const frameworks = detectFrameworks(context);
  260. expect(frameworks.some((f) => f.name === 'laravel')).toBe(true);
  261. });
  262. it('should return all framework resolvers', () => {
  263. const resolvers = getAllFrameworkResolvers();
  264. expect(resolvers.length).toBeGreaterThan(0);
  265. expect(resolvers.some((r) => r.name === 'react')).toBe(true);
  266. expect(resolvers.some((r) => r.name === 'express')).toBe(true);
  267. expect(resolvers.some((r) => r.name === 'laravel')).toBe(true);
  268. });
  269. });
  270. describe('React Framework Resolver', () => {
  271. it('should resolve React component references', () => {
  272. const mockNodes: Node[] = [
  273. {
  274. id: 'component:src/Button.tsx:Button:5',
  275. kind: 'component',
  276. name: 'Button',
  277. qualifiedName: 'src/Button.tsx::Button',
  278. filePath: 'src/Button.tsx',
  279. language: 'tsx',
  280. startLine: 5,
  281. endLine: 20,
  282. startColumn: 0,
  283. endColumn: 0,
  284. updatedAt: Date.now(),
  285. },
  286. ];
  287. const context: ResolutionContext = {
  288. getNodesInFile: (fp) => (fp === 'src/Button.tsx' ? mockNodes : []),
  289. getNodesByName: () => mockNodes,
  290. getNodesByQualifiedName: () => [],
  291. getNodesByKind: () => [],
  292. fileExists: () => false,
  293. readFile: (p) => {
  294. if (p === 'package.json') {
  295. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  296. }
  297. return null;
  298. },
  299. getProjectRoot: () => '/test',
  300. getAllFiles: () => ['package.json', 'src/Button.tsx', 'src/App.tsx'],
  301. };
  302. const frameworks = detectFrameworks(context);
  303. const reactResolver = frameworks.find((f) => f.name === 'react');
  304. expect(reactResolver).toBeDefined();
  305. const ref = {
  306. fromNodeId: 'component:src/App.tsx:App:1',
  307. referenceName: 'Button',
  308. referenceKind: 'renders' as const,
  309. line: 10,
  310. column: 5,
  311. filePath: 'src/App.tsx',
  312. language: 'typescript' as const,
  313. };
  314. const result = reactResolver!.resolve(ref, context);
  315. expect(result).not.toBeNull();
  316. expect(result?.targetNodeId).toBe('component:src/Button.tsx:Button:5');
  317. });
  318. it('should resolve custom hook references', () => {
  319. const mockNodes: Node[] = [
  320. {
  321. id: 'hook:src/hooks/useAuth.ts:useAuth:1',
  322. kind: 'function',
  323. name: 'useAuth',
  324. qualifiedName: 'src/hooks/useAuth.ts::useAuth',
  325. filePath: 'src/hooks/useAuth.ts',
  326. language: 'typescript',
  327. startLine: 1,
  328. endLine: 20,
  329. startColumn: 0,
  330. endColumn: 0,
  331. updatedAt: Date.now(),
  332. },
  333. ];
  334. const context: ResolutionContext = {
  335. getNodesInFile: (fp) => (fp.includes('useAuth') ? mockNodes : []),
  336. getNodesByName: () => mockNodes,
  337. getNodesByQualifiedName: () => [],
  338. getNodesByKind: () => [],
  339. fileExists: () => false,
  340. readFile: (p) => {
  341. if (p === 'package.json') {
  342. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  343. }
  344. return null;
  345. },
  346. getProjectRoot: () => '/test',
  347. getAllFiles: () => ['package.json', 'src/hooks/useAuth.ts'],
  348. };
  349. const frameworks = detectFrameworks(context);
  350. const reactResolver = frameworks.find((f) => f.name === 'react');
  351. const ref = {
  352. fromNodeId: 'component:src/App.tsx:App:1',
  353. referenceName: 'useAuth',
  354. referenceKind: 'calls' as const,
  355. line: 5,
  356. column: 10,
  357. filePath: 'src/App.tsx',
  358. language: 'typescript' as const,
  359. };
  360. const result = reactResolver!.resolve(ref, context);
  361. expect(result).not.toBeNull();
  362. expect(result?.targetNodeId).toBe('hook:src/hooks/useAuth.ts:useAuth:1');
  363. });
  364. });
  365. describe('Integration Tests', () => {
  366. it('should create resolver from CodeGraph instance', async () => {
  367. // Create a simple TypeScript project
  368. fs.writeFileSync(
  369. path.join(tempDir, 'package.json'),
  370. JSON.stringify({ name: 'test', dependencies: { react: '^18.0.0' } })
  371. );
  372. const srcDir = path.join(tempDir, 'src');
  373. fs.mkdirSync(srcDir);
  374. // Create utility file
  375. fs.writeFileSync(
  376. path.join(srcDir, 'utils.ts'),
  377. `export function formatDate(date: Date): string {
  378. return date.toISOString();
  379. }
  380. export function parseDate(str: string): Date {
  381. return new Date(str);
  382. }`
  383. );
  384. // Create main file that uses utils
  385. fs.writeFileSync(
  386. path.join(srcDir, 'main.ts'),
  387. `import { formatDate, parseDate } from './utils';
  388. function processDate(input: string): string {
  389. const date = parseDate(input);
  390. return formatDate(date);
  391. }`
  392. );
  393. // Initialize and index
  394. cg = await CodeGraph.init(tempDir, { index: true });
  395. // Check that resolver detected React framework
  396. const frameworks = cg.getDetectedFrameworks();
  397. expect(frameworks).toContain('react');
  398. // Get stats to verify indexing worked
  399. const stats = cg.getStats();
  400. expect(stats.fileCount).toBe(2);
  401. expect(stats.nodeCount).toBeGreaterThan(0);
  402. });
  403. it('should resolve references after indexing', async () => {
  404. // Create a project with references
  405. const srcDir = path.join(tempDir, 'src');
  406. fs.mkdirSync(srcDir, { recursive: true });
  407. fs.writeFileSync(
  408. path.join(srcDir, 'helper.ts'),
  409. `export function helperFunction(): void {
  410. console.log('helper');
  411. }`
  412. );
  413. fs.writeFileSync(
  414. path.join(srcDir, 'main.ts'),
  415. `import { helperFunction } from './helper';
  416. function main(): void {
  417. helperFunction();
  418. }`
  419. );
  420. cg = await CodeGraph.init(tempDir, { index: true });
  421. // Run reference resolution
  422. const result = cg.resolveReferences();
  423. // Should have attempted resolution
  424. expect(result.stats.total).toBeGreaterThanOrEqual(0);
  425. });
  426. });
  427. });