extraction.test.ts 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. /**
  2. * Extraction Tests
  3. *
  4. * Tests for the tree-sitter extraction system.
  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 { extractFromSource } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages } from '../src/extraction/grammars';
  13. // Create a temporary directory for each test
  14. function createTempDir(): string {
  15. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  16. }
  17. // Clean up temporary directory
  18. function cleanupTempDir(dir: string): void {
  19. if (fs.existsSync(dir)) {
  20. fs.rmSync(dir, { recursive: true, force: true });
  21. }
  22. }
  23. describe('Language Detection', () => {
  24. it('should detect TypeScript files', () => {
  25. expect(detectLanguage('src/index.ts')).toBe('typescript');
  26. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  27. });
  28. it('should detect JavaScript files', () => {
  29. expect(detectLanguage('index.js')).toBe('javascript');
  30. expect(detectLanguage('App.jsx')).toBe('jsx');
  31. expect(detectLanguage('config.mjs')).toBe('javascript');
  32. });
  33. it('should detect Python files', () => {
  34. expect(detectLanguage('main.py')).toBe('python');
  35. });
  36. it('should detect Go files', () => {
  37. expect(detectLanguage('main.go')).toBe('go');
  38. });
  39. it('should detect Rust files', () => {
  40. expect(detectLanguage('lib.rs')).toBe('rust');
  41. });
  42. it('should detect Java files', () => {
  43. expect(detectLanguage('Main.java')).toBe('java');
  44. });
  45. it('should detect C files', () => {
  46. expect(detectLanguage('main.c')).toBe('c');
  47. expect(detectLanguage('utils.h')).toBe('c');
  48. });
  49. it('should detect C++ files', () => {
  50. expect(detectLanguage('main.cpp')).toBe('cpp');
  51. expect(detectLanguage('class.hpp')).toBe('cpp');
  52. });
  53. it('should detect C# files', () => {
  54. expect(detectLanguage('Program.cs')).toBe('csharp');
  55. });
  56. it('should detect PHP files', () => {
  57. expect(detectLanguage('index.php')).toBe('php');
  58. });
  59. it('should detect Ruby files', () => {
  60. expect(detectLanguage('app.rb')).toBe('ruby');
  61. });
  62. it('should detect Swift files', () => {
  63. expect(detectLanguage('ViewController.swift')).toBe('swift');
  64. });
  65. it('should detect Kotlin files', () => {
  66. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  67. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  68. });
  69. it('should detect Dart files', () => {
  70. expect(detectLanguage('main.dart')).toBe('dart');
  71. });
  72. it('should return unknown for unsupported extensions', () => {
  73. expect(detectLanguage('styles.css')).toBe('unknown');
  74. expect(detectLanguage('data.json')).toBe('unknown');
  75. });
  76. });
  77. describe('Language Support', () => {
  78. it('should report supported languages', () => {
  79. expect(isLanguageSupported('typescript')).toBe(true);
  80. expect(isLanguageSupported('python')).toBe(true);
  81. expect(isLanguageSupported('go')).toBe(true);
  82. expect(isLanguageSupported('unknown')).toBe(false);
  83. });
  84. it('should list all supported languages', () => {
  85. const languages = getSupportedLanguages();
  86. expect(languages).toContain('typescript');
  87. expect(languages).toContain('javascript');
  88. expect(languages).toContain('python');
  89. expect(languages).toContain('go');
  90. expect(languages).toContain('rust');
  91. expect(languages).toContain('java');
  92. expect(languages).toContain('csharp');
  93. expect(languages).toContain('php');
  94. expect(languages).toContain('ruby');
  95. expect(languages).toContain('swift');
  96. expect(languages).toContain('kotlin');
  97. expect(languages).toContain('dart');
  98. });
  99. });
  100. describe('TypeScript Extraction', () => {
  101. it('should extract function declarations', () => {
  102. const code = `
  103. export function processPayment(amount: number): Promise<Receipt> {
  104. return stripe.charge(amount);
  105. }
  106. `;
  107. const result = extractFromSource('payment.ts', code);
  108. expect(result.nodes).toHaveLength(1);
  109. expect(result.nodes[0]).toMatchObject({
  110. kind: 'function',
  111. name: 'processPayment',
  112. language: 'typescript',
  113. isExported: true,
  114. });
  115. expect(result.nodes[0]?.signature).toContain('amount: number');
  116. });
  117. it('should extract class declarations', () => {
  118. const code = `
  119. export class PaymentService {
  120. private stripe: StripeClient;
  121. constructor(apiKey: string) {
  122. this.stripe = new StripeClient(apiKey);
  123. }
  124. async charge(amount: number): Promise<Receipt> {
  125. return this.stripe.charge(amount);
  126. }
  127. }
  128. `;
  129. const result = extractFromSource('service.ts', code);
  130. const classNode = result.nodes.find((n) => n.kind === 'class');
  131. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  132. expect(classNode).toBeDefined();
  133. expect(classNode?.name).toBe('PaymentService');
  134. expect(classNode?.isExported).toBe(true);
  135. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  136. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  137. expect(chargeMethod).toBeDefined();
  138. });
  139. it('should extract interfaces', () => {
  140. const code = `
  141. export interface User {
  142. id: string;
  143. name: string;
  144. email: string;
  145. }
  146. `;
  147. const result = extractFromSource('types.ts', code);
  148. expect(result.nodes).toHaveLength(1);
  149. expect(result.nodes[0]).toMatchObject({
  150. kind: 'interface',
  151. name: 'User',
  152. isExported: true,
  153. });
  154. });
  155. it('should track function calls', () => {
  156. const code = `
  157. function main() {
  158. const result = processData();
  159. console.log(result);
  160. }
  161. `;
  162. const result = extractFromSource('main.ts', code);
  163. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  164. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  165. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  166. });
  167. });
  168. describe('Arrow Function Export Extraction', () => {
  169. it('should extract exported arrow functions assigned to const', () => {
  170. const code = `
  171. export const useAuth = (): AuthContextValue => {
  172. return useContext(AuthContext);
  173. };
  174. `;
  175. const result = extractFromSource('hooks.ts', code);
  176. expect(result.nodes).toHaveLength(1);
  177. expect(result.nodes[0]).toMatchObject({
  178. kind: 'function',
  179. name: 'useAuth',
  180. isExported: true,
  181. });
  182. });
  183. it('should extract exported function expressions assigned to const', () => {
  184. const code = `
  185. export const processData = function(input: string): string {
  186. return input.trim();
  187. };
  188. `;
  189. const result = extractFromSource('utils.ts', code);
  190. expect(result.nodes).toHaveLength(1);
  191. expect(result.nodes[0]).toMatchObject({
  192. kind: 'function',
  193. name: 'processData',
  194. isExported: true,
  195. });
  196. });
  197. it('should not extract non-exported arrow functions as exported', () => {
  198. const code = `
  199. const internalHelper = () => {
  200. return 42;
  201. };
  202. `;
  203. const result = extractFromSource('internal.ts', code);
  204. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  205. expect(helperNode).toBeDefined();
  206. expect(helperNode?.isExported).toBeFalsy();
  207. });
  208. it('should still skip truly anonymous arrow functions', () => {
  209. const code = `
  210. const items = [1, 2, 3].map((x) => x * 2);
  211. `;
  212. const result = extractFromSource('anon.ts', code);
  213. // The inline arrow function passed to .map() has no variable_declarator parent
  214. // and should remain anonymous (skipped)
  215. const anonFunctions = result.nodes.filter(
  216. (n) => n.kind === 'function' && n.name === '<anonymous>'
  217. );
  218. expect(anonFunctions).toHaveLength(0);
  219. });
  220. it('should extract multiple exported arrow functions from the same file', () => {
  221. const code = `
  222. export const add = (a: number, b: number): number => a + b;
  223. export const subtract = (a: number, b: number): number => a - b;
  224. const internal = () => 'not exported';
  225. `;
  226. const result = extractFromSource('math.ts', code);
  227. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  228. expect(exported).toHaveLength(2);
  229. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  230. const internalNode = result.nodes.find((n) => n.name === 'internal');
  231. expect(internalNode).toBeDefined();
  232. expect(internalNode?.isExported).toBeFalsy();
  233. });
  234. it('should extract arrow functions in JavaScript files', () => {
  235. const code = `
  236. export const fetchData = async () => {
  237. const response = await fetch('/api/data');
  238. return response.json();
  239. };
  240. `;
  241. const result = extractFromSource('api.js', code);
  242. expect(result.nodes).toHaveLength(1);
  243. expect(result.nodes[0]).toMatchObject({
  244. kind: 'function',
  245. name: 'fetchData',
  246. isExported: true,
  247. });
  248. });
  249. });
  250. describe('Type Alias Extraction', () => {
  251. it('should extract exported type aliases in TypeScript', () => {
  252. const code = `
  253. export type AuthContextValue = {
  254. user: User | null;
  255. login: () => void;
  256. logout: () => void;
  257. };
  258. `;
  259. const result = extractFromSource('types.ts', code);
  260. expect(result.nodes).toHaveLength(1);
  261. expect(result.nodes[0]).toMatchObject({
  262. kind: 'type_alias',
  263. name: 'AuthContextValue',
  264. isExported: true,
  265. });
  266. });
  267. it('should extract non-exported type aliases', () => {
  268. const code = `
  269. type InternalState = {
  270. loading: boolean;
  271. error: string | null;
  272. };
  273. `;
  274. const result = extractFromSource('internal.ts', code);
  275. expect(result.nodes).toHaveLength(1);
  276. expect(result.nodes[0]).toMatchObject({
  277. kind: 'type_alias',
  278. name: 'InternalState',
  279. isExported: false,
  280. });
  281. });
  282. it('should extract multiple type aliases from the same file', () => {
  283. const code = `
  284. export type UnitSystem = 'metric' | 'imperial';
  285. export type DateFormat = 'ISO' | 'US' | 'EU';
  286. type Internal = string;
  287. `;
  288. const result = extractFromSource('config.ts', code);
  289. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  290. expect(typeAliases).toHaveLength(3);
  291. const exported = typeAliases.filter((n) => n.isExported);
  292. expect(exported).toHaveLength(2);
  293. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  294. });
  295. });
  296. describe('Exported Variable Extraction', () => {
  297. it('should extract exported const with call expression (Zustand store)', () => {
  298. const code = `
  299. export const useUIStore = create<UIState>((set) => ({
  300. isOpen: false,
  301. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  302. }));
  303. `;
  304. const result = extractFromSource('store.ts', code);
  305. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'useUIStore');
  306. expect(varNode).toBeDefined();
  307. expect(varNode?.isExported).toBe(true);
  308. });
  309. it('should extract exported const with object literal', () => {
  310. const code = `
  311. export const config = {
  312. apiUrl: 'https://api.example.com',
  313. timeout: 5000,
  314. };
  315. `;
  316. const result = extractFromSource('config.ts', code);
  317. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'config');
  318. expect(varNode).toBeDefined();
  319. expect(varNode?.isExported).toBe(true);
  320. });
  321. it('should extract exported const with array literal', () => {
  322. const code = `
  323. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  324. `;
  325. const result = extractFromSource('constants.ts', code);
  326. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'SCREEN_NAMES');
  327. expect(varNode).toBeDefined();
  328. expect(varNode?.isExported).toBe(true);
  329. });
  330. it('should extract exported const with primitive value', () => {
  331. const code = `
  332. export const MAX_RETRIES = 3;
  333. export const API_VERSION = "v2";
  334. `;
  335. const result = extractFromSource('constants.ts', code);
  336. const variables = result.nodes.filter((n) => n.kind === 'variable');
  337. expect(variables).toHaveLength(2);
  338. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  339. });
  340. it('should NOT duplicate arrow functions as both function and variable', () => {
  341. const code = `
  342. export const useAuth = () => {
  343. return useContext(AuthContext);
  344. };
  345. `;
  346. const result = extractFromSource('hooks.ts', code);
  347. // Should be extracted as function (from arrow function handler), NOT as variable
  348. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  349. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  350. expect(funcNodes).toHaveLength(1);
  351. expect(varNodes).toHaveLength(0);
  352. });
  353. it('should not extract non-exported const as exported variable', () => {
  354. const code = `
  355. const internalConfig = {
  356. debug: true,
  357. };
  358. `;
  359. const result = extractFromSource('internal.ts', code);
  360. // Non-exported const should NOT create a variable node
  361. // (only export_statement triggers extractExportedVariables)
  362. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'internalConfig');
  363. expect(varNodes).toHaveLength(0);
  364. });
  365. it('should extract Zod schema exports', () => {
  366. const code = `
  367. export const userSchema = z.object({
  368. id: z.string(),
  369. name: z.string(),
  370. email: z.string().email(),
  371. });
  372. `;
  373. const result = extractFromSource('schemas.ts', code);
  374. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'userSchema');
  375. expect(varNode).toBeDefined();
  376. expect(varNode?.isExported).toBe(true);
  377. });
  378. it('should extract XState machine exports', () => {
  379. const code = `
  380. export const authMachine = createMachine({
  381. id: "auth",
  382. initial: "idle",
  383. states: {
  384. idle: {},
  385. authenticated: {},
  386. },
  387. });
  388. `;
  389. const result = extractFromSource('machine.ts', code);
  390. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'authMachine');
  391. expect(varNode).toBeDefined();
  392. expect(varNode?.isExported).toBe(true);
  393. });
  394. });
  395. describe('Python Extraction', () => {
  396. it('should extract function definitions', () => {
  397. const code = `
  398. def calculate_total(items: list, tax_rate: float) -> float:
  399. """Calculate total with tax."""
  400. subtotal = sum(item.price for item in items)
  401. return subtotal * (1 + tax_rate)
  402. `;
  403. const result = extractFromSource('calc.py', code);
  404. expect(result.nodes).toHaveLength(1);
  405. expect(result.nodes[0]).toMatchObject({
  406. kind: 'function',
  407. name: 'calculate_total',
  408. language: 'python',
  409. });
  410. });
  411. it('should extract class definitions', () => {
  412. const code = `
  413. class UserService:
  414. """Service for managing users."""
  415. def __init__(self, db):
  416. self.db = db
  417. def get_user(self, user_id: str) -> User:
  418. return self.db.find_user(user_id)
  419. `;
  420. const result = extractFromSource('service.py', code);
  421. const classNode = result.nodes.find((n) => n.kind === 'class');
  422. expect(classNode).toBeDefined();
  423. expect(classNode?.name).toBe('UserService');
  424. });
  425. });
  426. describe('Go Extraction', () => {
  427. it('should extract function declarations', () => {
  428. const code = `
  429. package main
  430. func ProcessOrder(order Order) (Receipt, error) {
  431. // Process the order
  432. return Receipt{}, nil
  433. }
  434. `;
  435. const result = extractFromSource('main.go', code);
  436. const funcNode = result.nodes.find((n) => n.kind === 'function');
  437. expect(funcNode).toBeDefined();
  438. expect(funcNode?.name).toBe('ProcessOrder');
  439. });
  440. it('should extract method declarations', () => {
  441. const code = `
  442. package main
  443. type Service struct {
  444. db *Database
  445. }
  446. func (s *Service) GetUser(id string) (*User, error) {
  447. return s.db.FindUser(id)
  448. }
  449. `;
  450. const result = extractFromSource('service.go', code);
  451. const methodNode = result.nodes.find((n) => n.kind === 'method');
  452. expect(methodNode).toBeDefined();
  453. expect(methodNode?.name).toBe('GetUser');
  454. });
  455. });
  456. describe('Rust Extraction', () => {
  457. it('should extract function declarations', () => {
  458. const code = `
  459. pub fn process_data(input: &str) -> Result<Output, Error> {
  460. // Process data
  461. Ok(Output::new())
  462. }
  463. `;
  464. const result = extractFromSource('lib.rs', code);
  465. const funcNode = result.nodes.find((n) => n.kind === 'function');
  466. expect(funcNode).toBeDefined();
  467. expect(funcNode?.name).toBe('process_data');
  468. expect(funcNode?.visibility).toBe('public');
  469. });
  470. it('should extract struct declarations', () => {
  471. const code = `
  472. pub struct User {
  473. pub id: String,
  474. pub name: String,
  475. email: String,
  476. }
  477. `;
  478. const result = extractFromSource('models.rs', code);
  479. const structNode = result.nodes.find((n) => n.kind === 'struct');
  480. expect(structNode).toBeDefined();
  481. expect(structNode?.name).toBe('User');
  482. });
  483. it('should extract trait declarations', () => {
  484. const code = `
  485. pub trait Repository {
  486. fn find(&self, id: &str) -> Option<Entity>;
  487. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  488. }
  489. `;
  490. const result = extractFromSource('traits.rs', code);
  491. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  492. expect(traitNode).toBeDefined();
  493. expect(traitNode?.name).toBe('Repository');
  494. });
  495. });
  496. describe('Java Extraction', () => {
  497. it('should extract class declarations', () => {
  498. const code = `
  499. public class UserService {
  500. private final UserRepository repository;
  501. public UserService(UserRepository repository) {
  502. this.repository = repository;
  503. }
  504. public User getUser(String id) {
  505. return repository.findById(id);
  506. }
  507. }
  508. `;
  509. const result = extractFromSource('UserService.java', code);
  510. const classNode = result.nodes.find((n) => n.kind === 'class');
  511. expect(classNode).toBeDefined();
  512. expect(classNode?.name).toBe('UserService');
  513. expect(classNode?.visibility).toBe('public');
  514. });
  515. it('should extract method declarations', () => {
  516. const code = `
  517. public class Calculator {
  518. public static int add(int a, int b) {
  519. return a + b;
  520. }
  521. }
  522. `;
  523. const result = extractFromSource('Calculator.java', code);
  524. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  525. expect(methodNode).toBeDefined();
  526. expect(methodNode?.isStatic).toBe(true);
  527. });
  528. });
  529. describe('C# Extraction', () => {
  530. it('should extract class declarations', () => {
  531. const code = `
  532. public class OrderService
  533. {
  534. private readonly IOrderRepository _repository;
  535. public OrderService(IOrderRepository repository)
  536. {
  537. _repository = repository;
  538. }
  539. public async Task<Order> GetOrderAsync(string id)
  540. {
  541. return await _repository.FindByIdAsync(id);
  542. }
  543. }
  544. `;
  545. const result = extractFromSource('OrderService.cs', code);
  546. const classNode = result.nodes.find((n) => n.kind === 'class');
  547. expect(classNode).toBeDefined();
  548. expect(classNode?.name).toBe('OrderService');
  549. expect(classNode?.visibility).toBe('public');
  550. });
  551. });
  552. describe('PHP Extraction', () => {
  553. it('should extract class declarations', () => {
  554. const code = `<?php
  555. class UserController
  556. {
  557. private UserService $userService;
  558. public function __construct(UserService $userService)
  559. {
  560. $this->userService = $userService;
  561. }
  562. public function show(string $id): User
  563. {
  564. return $this->userService->find($id);
  565. }
  566. }
  567. `;
  568. const result = extractFromSource('UserController.php', code);
  569. const classNode = result.nodes.find((n) => n.kind === 'class');
  570. expect(classNode).toBeDefined();
  571. expect(classNode?.name).toBe('UserController');
  572. });
  573. });
  574. describe('Swift Extraction', () => {
  575. it('should extract class declarations', () => {
  576. const code = `
  577. public class NetworkManager {
  578. private let session: URLSession
  579. public init(session: URLSession = .shared) {
  580. self.session = session
  581. }
  582. public func fetchData(from url: URL) async throws -> Data {
  583. let (data, _) = try await session.data(from: url)
  584. return data
  585. }
  586. }
  587. `;
  588. const result = extractFromSource('NetworkManager.swift', code);
  589. const classNode = result.nodes.find((n) => n.kind === 'class');
  590. expect(classNode).toBeDefined();
  591. expect(classNode?.name).toBe('NetworkManager');
  592. });
  593. it('should extract function declarations', () => {
  594. const code = `
  595. func calculateSum(_ numbers: [Int]) -> Int {
  596. return numbers.reduce(0, +)
  597. }
  598. public func formatCurrency(amount: Double) -> String {
  599. return String(format: "$%.2f", amount)
  600. }
  601. `;
  602. const result = extractFromSource('utils.swift', code);
  603. const functions = result.nodes.filter((n) => n.kind === 'function');
  604. expect(functions.length).toBeGreaterThanOrEqual(1);
  605. });
  606. it('should extract struct declarations', () => {
  607. const code = `
  608. public struct User {
  609. let id: UUID
  610. var name: String
  611. var email: String
  612. func displayName() -> String {
  613. return name
  614. }
  615. }
  616. `;
  617. const result = extractFromSource('User.swift', code);
  618. const structNode = result.nodes.find((n) => n.kind === 'struct');
  619. expect(structNode).toBeDefined();
  620. expect(structNode?.name).toBe('User');
  621. });
  622. it('should extract protocol declarations', () => {
  623. const code = `
  624. public protocol Repository {
  625. associatedtype Entity
  626. func find(id: String) async throws -> Entity?
  627. func save(_ entity: Entity) async throws
  628. }
  629. `;
  630. const result = extractFromSource('Repository.swift', code);
  631. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  632. expect(protocolNode).toBeDefined();
  633. expect(protocolNode?.name).toBe('Repository');
  634. });
  635. });
  636. describe('Kotlin Extraction', () => {
  637. it('should extract class declarations', () => {
  638. const code = `
  639. class UserRepository(private val database: Database) {
  640. fun findById(id: String): User? {
  641. return database.query("SELECT * FROM users WHERE id = ?", id)
  642. }
  643. suspend fun save(user: User) {
  644. database.insert(user)
  645. }
  646. }
  647. `;
  648. const result = extractFromSource('UserRepository.kt', code);
  649. const classNode = result.nodes.find((n) => n.kind === 'class');
  650. expect(classNode).toBeDefined();
  651. expect(classNode?.name).toBe('UserRepository');
  652. });
  653. it('should extract function declarations', () => {
  654. const code = `
  655. fun calculateTotal(items: List<Item>): Double {
  656. return items.sumOf { it.price }
  657. }
  658. suspend fun fetchUserData(userId: String): User {
  659. return api.getUser(userId)
  660. }
  661. `;
  662. const result = extractFromSource('utils.kt', code);
  663. const functions = result.nodes.filter((n) => n.kind === 'function');
  664. expect(functions.length).toBeGreaterThanOrEqual(1);
  665. });
  666. it('should detect suspend functions as async', () => {
  667. const code = `
  668. suspend fun loadData(): List<String> {
  669. delay(1000)
  670. return listOf("a", "b", "c")
  671. }
  672. `;
  673. const result = extractFromSource('loader.kt', code);
  674. const funcNode = result.nodes.find((n) => n.kind === 'function');
  675. expect(funcNode).toBeDefined();
  676. expect(funcNode?.isAsync).toBe(true);
  677. });
  678. });
  679. describe('Dart Extraction', () => {
  680. it('should extract class declarations', () => {
  681. const code = `
  682. class UserService {
  683. final Database _db;
  684. Future<User> findById(String id) async {
  685. return await _db.query(id);
  686. }
  687. void _privateMethod() {}
  688. }
  689. `;
  690. const result = extractFromSource('service.dart', code);
  691. const classNode = result.nodes.find((n) => n.kind === 'class');
  692. expect(classNode).toBeDefined();
  693. expect(classNode?.name).toBe('UserService');
  694. expect(classNode?.visibility).toBe('public');
  695. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  696. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  697. const findById = methodNodes.find((m) => m.name === 'findById');
  698. expect(findById).toBeDefined();
  699. expect(findById?.isAsync).toBe(true);
  700. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  701. expect(privateMethod).toBeDefined();
  702. expect(privateMethod?.visibility).toBe('private');
  703. });
  704. it('should extract top-level function declarations', () => {
  705. const code = `
  706. void topLevelFunction(String name) {
  707. print(name);
  708. }
  709. `;
  710. const result = extractFromSource('utils.dart', code);
  711. const funcNode = result.nodes.find((n) => n.kind === 'function');
  712. expect(funcNode).toBeDefined();
  713. expect(funcNode?.name).toBe('topLevelFunction');
  714. expect(funcNode?.language).toBe('dart');
  715. });
  716. it('should extract enum declarations', () => {
  717. const code = `
  718. enum Status { active, inactive, pending }
  719. `;
  720. const result = extractFromSource('models.dart', code);
  721. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  722. expect(enumNode).toBeDefined();
  723. expect(enumNode?.name).toBe('Status');
  724. });
  725. it('should extract mixin declarations', () => {
  726. const code = `
  727. mixin LoggerMixin {
  728. void log(String message) {}
  729. }
  730. `;
  731. const result = extractFromSource('mixins.dart', code);
  732. const classNode = result.nodes.find((n) => n.kind === 'class');
  733. expect(classNode).toBeDefined();
  734. expect(classNode?.name).toBe('LoggerMixin');
  735. const methodNode = result.nodes.find((n) => n.kind === 'method');
  736. expect(methodNode).toBeDefined();
  737. expect(methodNode?.name).toBe('log');
  738. });
  739. it('should extract extension declarations', () => {
  740. const code = `
  741. extension StringExt on String {
  742. bool get isBlank => trim().isEmpty;
  743. }
  744. `;
  745. const result = extractFromSource('extensions.dart', code);
  746. const classNode = result.nodes.find((n) => n.kind === 'class');
  747. expect(classNode).toBeDefined();
  748. expect(classNode?.name).toBe('StringExt');
  749. });
  750. it('should detect static methods', () => {
  751. const code = `
  752. class Utils {
  753. static void doWork() {}
  754. }
  755. `;
  756. const result = extractFromSource('utils.dart', code);
  757. const methodNode = result.nodes.find((n) => n.kind === 'method');
  758. expect(methodNode).toBeDefined();
  759. expect(methodNode?.name).toBe('doWork');
  760. expect(methodNode?.isStatic).toBe(true);
  761. });
  762. it('should detect async functions', () => {
  763. const code = `
  764. Future<String> fetchData() async {
  765. return await http.get('/data');
  766. }
  767. `;
  768. const result = extractFromSource('api.dart', code);
  769. const funcNode = result.nodes.find((n) => n.kind === 'function');
  770. expect(funcNode).toBeDefined();
  771. expect(funcNode?.name).toBe('fetchData');
  772. expect(funcNode?.isAsync).toBe(true);
  773. });
  774. it('should detect private visibility via underscore convention', () => {
  775. const code = `
  776. void _privateHelper() {}
  777. void publicFunction() {}
  778. `;
  779. const result = extractFromSource('helpers.dart', code);
  780. const functions = result.nodes.filter((n) => n.kind === 'function');
  781. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  782. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  783. expect(privateFunc?.visibility).toBe('private');
  784. expect(publicFunc?.visibility).toBe('public');
  785. });
  786. });
  787. describe('Import Extraction', () => {
  788. describe('TypeScript/JavaScript imports', () => {
  789. it('should extract default imports', () => {
  790. const code = `import React from 'react';`;
  791. const result = extractFromSource('app.tsx', code);
  792. const importNode = result.nodes.find((n) => n.kind === 'import');
  793. expect(importNode).toBeDefined();
  794. expect(importNode?.name).toBe('react');
  795. expect(importNode?.signature).toBe("import React from 'react';");
  796. });
  797. it('should extract named imports', () => {
  798. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  799. const result = extractFromSource('icons.tsx', code);
  800. const importNode = result.nodes.find((n) => n.kind === 'import');
  801. expect(importNode).toBeDefined();
  802. expect(importNode?.name).toBe('@phosphor-icons/react');
  803. expect(importNode?.signature).toContain('Bug');
  804. expect(importNode?.signature).toContain('Database');
  805. });
  806. it('should extract namespace imports', () => {
  807. const code = `import * as Icons from '@phosphor-icons/react';`;
  808. const result = extractFromSource('icons.tsx', code);
  809. const importNode = result.nodes.find((n) => n.kind === 'import');
  810. expect(importNode).toBeDefined();
  811. expect(importNode?.name).toBe('@phosphor-icons/react');
  812. expect(importNode?.signature).toContain('* as Icons');
  813. });
  814. it('should extract side-effect imports', () => {
  815. const code = `import './styles.css';`;
  816. const result = extractFromSource('app.tsx', code);
  817. const importNode = result.nodes.find((n) => n.kind === 'import');
  818. expect(importNode).toBeDefined();
  819. expect(importNode?.name).toBe('./styles.css');
  820. });
  821. it('should extract mixed imports (default + named)', () => {
  822. const code = `import React, { useState, useEffect } from 'react';`;
  823. const result = extractFromSource('app.tsx', code);
  824. const importNode = result.nodes.find((n) => n.kind === 'import');
  825. expect(importNode).toBeDefined();
  826. expect(importNode?.name).toBe('react');
  827. expect(importNode?.signature).toContain('React');
  828. expect(importNode?.signature).toContain('useState');
  829. expect(importNode?.signature).toContain('useEffect');
  830. });
  831. it('should extract multiple import statements', () => {
  832. const code = `
  833. import React from 'react';
  834. import { Button } from './components';
  835. import './styles.css';
  836. `;
  837. const result = extractFromSource('app.tsx', code);
  838. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  839. expect(importNodes.length).toBe(3);
  840. const names = importNodes.map((n) => n.name);
  841. expect(names).toContain('react');
  842. expect(names).toContain('./components');
  843. expect(names).toContain('./styles.css');
  844. });
  845. it('should extract type imports', () => {
  846. const code = `import type { FC, ReactNode } from 'react';`;
  847. const result = extractFromSource('types.ts', code);
  848. const importNode = result.nodes.find((n) => n.kind === 'import');
  849. expect(importNode).toBeDefined();
  850. expect(importNode?.name).toBe('react');
  851. expect(importNode?.signature).toContain('type');
  852. expect(importNode?.signature).toContain('FC');
  853. });
  854. it('should extract aliased named imports', () => {
  855. const code = `import { useState as useStateAlias } from 'react';`;
  856. const result = extractFromSource('hooks.ts', code);
  857. const importNode = result.nodes.find((n) => n.kind === 'import');
  858. expect(importNode).toBeDefined();
  859. expect(importNode?.name).toBe('react');
  860. expect(importNode?.signature).toContain('useState');
  861. expect(importNode?.signature).toContain('useStateAlias');
  862. });
  863. it('should extract relative path imports', () => {
  864. const code = `import { helper } from '../utils/helper';`;
  865. const result = extractFromSource('components/Button.tsx', code);
  866. const importNode = result.nodes.find((n) => n.kind === 'import');
  867. expect(importNode).toBeDefined();
  868. expect(importNode?.name).toBe('../utils/helper');
  869. expect(importNode?.signature).toContain('helper');
  870. });
  871. });
  872. describe('Python imports', () => {
  873. it('should extract simple import statement', () => {
  874. const code = `import json`;
  875. const result = extractFromSource('utils.py', code);
  876. const importNode = result.nodes.find((n) => n.kind === 'import');
  877. expect(importNode).toBeDefined();
  878. expect(importNode?.name).toBe('json');
  879. });
  880. it('should extract from import statement', () => {
  881. const code = `from os import path`;
  882. const result = extractFromSource('utils.py', code);
  883. const importNode = result.nodes.find((n) => n.kind === 'import');
  884. expect(importNode).toBeDefined();
  885. expect(importNode?.name).toBe('os');
  886. expect(importNode?.signature).toContain('path');
  887. });
  888. it('should extract multiple imports from same module', () => {
  889. const code = `from typing import List, Dict, Optional`;
  890. const result = extractFromSource('types.py', code);
  891. const importNode = result.nodes.find((n) => n.kind === 'import');
  892. expect(importNode).toBeDefined();
  893. expect(importNode?.name).toBe('typing');
  894. expect(importNode?.signature).toContain('List');
  895. expect(importNode?.signature).toContain('Dict');
  896. });
  897. it('should extract multiple import statements', () => {
  898. const code = `
  899. import os
  900. import sys
  901. `;
  902. const result = extractFromSource('main.py', code);
  903. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  904. expect(importNodes.length).toBe(2);
  905. const names = importNodes.map((n) => n.name);
  906. expect(names).toContain('os');
  907. expect(names).toContain('sys');
  908. });
  909. it('should extract aliased import', () => {
  910. const code = `import numpy as np`;
  911. const result = extractFromSource('data.py', code);
  912. const importNode = result.nodes.find((n) => n.kind === 'import');
  913. expect(importNode).toBeDefined();
  914. expect(importNode?.name).toBe('numpy');
  915. expect(importNode?.signature).toContain('as np');
  916. });
  917. it('should extract relative import', () => {
  918. const code = `from .utils import helper`;
  919. const result = extractFromSource('module.py', code);
  920. const importNode = result.nodes.find((n) => n.kind === 'import');
  921. expect(importNode).toBeDefined();
  922. expect(importNode?.name).toBe('.utils');
  923. expect(importNode?.signature).toContain('helper');
  924. });
  925. it('should extract wildcard import', () => {
  926. const code = `from typing import *`;
  927. const result = extractFromSource('types.py', code);
  928. const importNode = result.nodes.find((n) => n.kind === 'import');
  929. expect(importNode).toBeDefined();
  930. expect(importNode?.name).toBe('typing');
  931. expect(importNode?.signature).toContain('*');
  932. });
  933. });
  934. describe('Rust imports', () => {
  935. it('should extract simple use declaration', () => {
  936. const code = `use std::io;`;
  937. const result = extractFromSource('main.rs', code);
  938. const importNode = result.nodes.find((n) => n.kind === 'import');
  939. expect(importNode).toBeDefined();
  940. expect(importNode?.name).toBe('std');
  941. expect(importNode?.signature).toBe('use std::io;');
  942. });
  943. it('should extract scoped use list', () => {
  944. const code = `use std::{ffi::OsStr, io, path::Path};`;
  945. const result = extractFromSource('main.rs', code);
  946. const importNode = result.nodes.find((n) => n.kind === 'import');
  947. expect(importNode).toBeDefined();
  948. expect(importNode?.name).toBe('std');
  949. expect(importNode?.signature).toContain('ffi::OsStr');
  950. expect(importNode?.signature).toContain('path::Path');
  951. });
  952. it('should extract crate imports', () => {
  953. const code = `use crate::error::Error;`;
  954. const result = extractFromSource('lib.rs', code);
  955. const importNode = result.nodes.find((n) => n.kind === 'import');
  956. expect(importNode).toBeDefined();
  957. expect(importNode?.name).toBe('crate');
  958. });
  959. it('should extract super imports', () => {
  960. const code = `use super::utils;`;
  961. const result = extractFromSource('submod.rs', code);
  962. const importNode = result.nodes.find((n) => n.kind === 'import');
  963. expect(importNode).toBeDefined();
  964. expect(importNode?.name).toBe('super');
  965. });
  966. it('should extract external crate imports', () => {
  967. const code = `use serde::{Serialize, Deserialize};`;
  968. const result = extractFromSource('types.rs', code);
  969. const importNode = result.nodes.find((n) => n.kind === 'import');
  970. expect(importNode).toBeDefined();
  971. expect(importNode?.name).toBe('serde');
  972. expect(importNode?.signature).toContain('Serialize');
  973. expect(importNode?.signature).toContain('Deserialize');
  974. });
  975. });
  976. describe('Go imports', () => {
  977. it('should extract single import', () => {
  978. const code = `
  979. package main
  980. import "fmt"
  981. `;
  982. const result = extractFromSource('main.go', code);
  983. const importNode = result.nodes.find((n) => n.kind === 'import');
  984. expect(importNode).toBeDefined();
  985. expect(importNode?.name).toBe('fmt');
  986. });
  987. it('should extract grouped imports', () => {
  988. const code = `
  989. package main
  990. import (
  991. "fmt"
  992. "os"
  993. "encoding/json"
  994. )
  995. `;
  996. const result = extractFromSource('main.go', code);
  997. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  998. expect(importNodes.length).toBe(3);
  999. const names = importNodes.map((n) => n.name);
  1000. expect(names).toContain('fmt');
  1001. expect(names).toContain('os');
  1002. expect(names).toContain('encoding/json');
  1003. });
  1004. it('should extract aliased import', () => {
  1005. const code = `
  1006. package main
  1007. import f "fmt"
  1008. `;
  1009. const result = extractFromSource('main.go', code);
  1010. const importNode = result.nodes.find((n) => n.kind === 'import');
  1011. expect(importNode).toBeDefined();
  1012. expect(importNode?.name).toBe('fmt');
  1013. expect(importNode?.signature).toContain('f');
  1014. });
  1015. it('should extract dot import', () => {
  1016. const code = `
  1017. package main
  1018. import . "math"
  1019. `;
  1020. const result = extractFromSource('main.go', code);
  1021. const importNode = result.nodes.find((n) => n.kind === 'import');
  1022. expect(importNode).toBeDefined();
  1023. expect(importNode?.name).toBe('math');
  1024. expect(importNode?.signature).toContain('.');
  1025. });
  1026. it('should extract blank import', () => {
  1027. const code = `
  1028. package main
  1029. import _ "github.com/go-sql-driver/mysql"
  1030. `;
  1031. const result = extractFromSource('main.go', code);
  1032. const importNode = result.nodes.find((n) => n.kind === 'import');
  1033. expect(importNode).toBeDefined();
  1034. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1035. expect(importNode?.signature).toContain('_');
  1036. });
  1037. });
  1038. describe('Swift imports', () => {
  1039. it('should extract simple import', () => {
  1040. const code = `import Foundation`;
  1041. const result = extractFromSource('main.swift', code);
  1042. const importNode = result.nodes.find((n) => n.kind === 'import');
  1043. expect(importNode).toBeDefined();
  1044. expect(importNode?.name).toBe('Foundation');
  1045. expect(importNode?.signature).toBe('import Foundation');
  1046. });
  1047. it('should extract @testable import', () => {
  1048. const code = `@testable import Alamofire`;
  1049. const result = extractFromSource('Tests.swift', code);
  1050. const importNode = result.nodes.find((n) => n.kind === 'import');
  1051. expect(importNode).toBeDefined();
  1052. expect(importNode?.name).toBe('Alamofire');
  1053. expect(importNode?.signature).toContain('@testable');
  1054. });
  1055. it('should extract @preconcurrency import', () => {
  1056. const code = `@preconcurrency import Security`;
  1057. const result = extractFromSource('Auth.swift', code);
  1058. const importNode = result.nodes.find((n) => n.kind === 'import');
  1059. expect(importNode).toBeDefined();
  1060. expect(importNode?.name).toBe('Security');
  1061. });
  1062. it('should extract multiple imports', () => {
  1063. const code = `
  1064. import Foundation
  1065. import UIKit
  1066. import Alamofire
  1067. `;
  1068. const result = extractFromSource('App.swift', code);
  1069. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1070. expect(importNodes.length).toBe(3);
  1071. const names = importNodes.map((n) => n.name);
  1072. expect(names).toContain('Foundation');
  1073. expect(names).toContain('UIKit');
  1074. expect(names).toContain('Alamofire');
  1075. });
  1076. });
  1077. describe('Kotlin imports', () => {
  1078. it('should extract simple import', () => {
  1079. const code = `import java.io.IOException`;
  1080. const result = extractFromSource('Main.kt', code);
  1081. const importNode = result.nodes.find((n) => n.kind === 'import');
  1082. expect(importNode).toBeDefined();
  1083. expect(importNode?.name).toBe('java.io.IOException');
  1084. expect(importNode?.signature).toBe('import java.io.IOException');
  1085. });
  1086. it('should extract aliased import', () => {
  1087. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1088. const result = extractFromSource('Utils.kt', code);
  1089. const importNode = result.nodes.find((n) => n.kind === 'import');
  1090. expect(importNode).toBeDefined();
  1091. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1092. expect(importNode?.signature).toContain('as RequestBuilder');
  1093. });
  1094. it('should extract wildcard import', () => {
  1095. const code = `import java.util.concurrent.TimeUnit.*`;
  1096. const result = extractFromSource('Time.kt', code);
  1097. const importNode = result.nodes.find((n) => n.kind === 'import');
  1098. expect(importNode).toBeDefined();
  1099. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1100. expect(importNode?.signature).toContain('.*');
  1101. });
  1102. it('should extract multiple imports', () => {
  1103. const code = `
  1104. import java.io.IOException
  1105. import kotlin.test.assertFailsWith
  1106. import okhttp3.OkHttpClient
  1107. `;
  1108. const result = extractFromSource('Test.kt', code);
  1109. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1110. expect(importNodes.length).toBe(3);
  1111. const names = importNodes.map((n) => n.name);
  1112. expect(names).toContain('java.io.IOException');
  1113. expect(names).toContain('kotlin.test.assertFailsWith');
  1114. expect(names).toContain('okhttp3.OkHttpClient');
  1115. });
  1116. });
  1117. describe('Java imports', () => {
  1118. it('should extract simple import', () => {
  1119. const code = `import java.util.List;`;
  1120. const result = extractFromSource('Main.java', code);
  1121. const importNode = result.nodes.find((n) => n.kind === 'import');
  1122. expect(importNode).toBeDefined();
  1123. expect(importNode?.name).toBe('java.util.List');
  1124. expect(importNode?.signature).toBe('import java.util.List;');
  1125. });
  1126. it('should extract static import', () => {
  1127. const code = `import static java.util.Collections.emptyList;`;
  1128. const result = extractFromSource('Utils.java', code);
  1129. const importNode = result.nodes.find((n) => n.kind === 'import');
  1130. expect(importNode).toBeDefined();
  1131. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1132. expect(importNode?.signature).toContain('static');
  1133. });
  1134. it('should extract wildcard import', () => {
  1135. const code = `import java.util.*;`;
  1136. const result = extractFromSource('App.java', code);
  1137. const importNode = result.nodes.find((n) => n.kind === 'import');
  1138. expect(importNode).toBeDefined();
  1139. expect(importNode?.name).toBe('java.util');
  1140. expect(importNode?.signature).toContain('.*');
  1141. });
  1142. it('should extract nested class import', () => {
  1143. const code = `import java.util.Map.Entry;`;
  1144. const result = extractFromSource('MapUtil.java', code);
  1145. const importNode = result.nodes.find((n) => n.kind === 'import');
  1146. expect(importNode).toBeDefined();
  1147. expect(importNode?.name).toBe('java.util.Map.Entry');
  1148. });
  1149. it('should extract multiple imports', () => {
  1150. const code = `
  1151. import java.util.List;
  1152. import java.util.Map;
  1153. import java.io.IOException;
  1154. `;
  1155. const result = extractFromSource('Service.java', code);
  1156. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1157. expect(importNodes.length).toBe(3);
  1158. const names = importNodes.map((n) => n.name);
  1159. expect(names).toContain('java.util.List');
  1160. expect(names).toContain('java.util.Map');
  1161. expect(names).toContain('java.io.IOException');
  1162. });
  1163. });
  1164. describe('C# imports', () => {
  1165. it('should extract simple using', () => {
  1166. const code = `using System;`;
  1167. const result = extractFromSource('Program.cs', code);
  1168. const importNode = result.nodes.find((n) => n.kind === 'import');
  1169. expect(importNode).toBeDefined();
  1170. expect(importNode?.name).toBe('System');
  1171. expect(importNode?.signature).toBe('using System;');
  1172. });
  1173. it('should extract qualified using', () => {
  1174. const code = `using System.Collections.Generic;`;
  1175. const result = extractFromSource('Utils.cs', code);
  1176. const importNode = result.nodes.find((n) => n.kind === 'import');
  1177. expect(importNode).toBeDefined();
  1178. expect(importNode?.name).toBe('System.Collections.Generic');
  1179. });
  1180. it('should extract static using', () => {
  1181. const code = `using static System.Console;`;
  1182. const result = extractFromSource('App.cs', code);
  1183. const importNode = result.nodes.find((n) => n.kind === 'import');
  1184. expect(importNode).toBeDefined();
  1185. expect(importNode?.name).toBe('System.Console');
  1186. expect(importNode?.signature).toContain('static');
  1187. });
  1188. it('should extract alias using', () => {
  1189. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1190. const result = extractFromSource('Types.cs', code);
  1191. const importNode = result.nodes.find((n) => n.kind === 'import');
  1192. expect(importNode).toBeDefined();
  1193. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1194. expect(importNode?.signature).toContain('MyList =');
  1195. });
  1196. it('should extract multiple usings', () => {
  1197. const code = `
  1198. using System;
  1199. using System.Threading.Tasks;
  1200. using Microsoft.Extensions.DependencyInjection;
  1201. `;
  1202. const result = extractFromSource('Service.cs', code);
  1203. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1204. expect(importNodes.length).toBe(3);
  1205. const names = importNodes.map((n) => n.name);
  1206. expect(names).toContain('System');
  1207. expect(names).toContain('System.Threading.Tasks');
  1208. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1209. });
  1210. });
  1211. describe('PHP imports', () => {
  1212. it('should extract simple use', () => {
  1213. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1214. const result = extractFromSource('Test.php', code);
  1215. const importNode = result.nodes.find((n) => n.kind === 'import');
  1216. expect(importNode).toBeDefined();
  1217. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1218. });
  1219. it('should extract aliased use', () => {
  1220. const code = `<?php use Mockery as m;`;
  1221. const result = extractFromSource('Test.php', code);
  1222. const importNode = result.nodes.find((n) => n.kind === 'import');
  1223. expect(importNode).toBeDefined();
  1224. expect(importNode?.name).toBe('Mockery');
  1225. expect(importNode?.signature).toContain('as m');
  1226. });
  1227. it('should extract function use', () => {
  1228. const code = `<?php use function Illuminate\\Support\\env;`;
  1229. const result = extractFromSource('helpers.php', code);
  1230. const importNode = result.nodes.find((n) => n.kind === 'import');
  1231. expect(importNode).toBeDefined();
  1232. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1233. expect(importNode?.signature).toContain('function');
  1234. });
  1235. it('should extract grouped use', () => {
  1236. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1237. const result = extractFromSource('Models.php', code);
  1238. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1239. expect(importNodes.length).toBe(2);
  1240. const names = importNodes.map((n) => n.name);
  1241. expect(names).toContain('Illuminate\\Database\\Model');
  1242. expect(names).toContain('Illuminate\\Database\\Builder');
  1243. });
  1244. it('should extract multiple uses', () => {
  1245. const code = `<?php
  1246. use Illuminate\\Support\\Collection;
  1247. use Illuminate\\Support\\Str;
  1248. use Closure;
  1249. `;
  1250. const result = extractFromSource('Service.php', code);
  1251. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1252. expect(importNodes.length).toBe(3);
  1253. const names = importNodes.map((n) => n.name);
  1254. expect(names).toContain('Illuminate\\Support\\Collection');
  1255. expect(names).toContain('Illuminate\\Support\\Str');
  1256. expect(names).toContain('Closure');
  1257. });
  1258. });
  1259. describe('Ruby imports', () => {
  1260. it('should extract require', () => {
  1261. const code = `require 'json'`;
  1262. const result = extractFromSource('app.rb', code);
  1263. const importNode = result.nodes.find((n) => n.kind === 'import');
  1264. expect(importNode).toBeDefined();
  1265. expect(importNode?.name).toBe('json');
  1266. expect(importNode?.signature).toBe("require 'json'");
  1267. });
  1268. it('should extract require with path', () => {
  1269. const code = `require 'active_support/core_ext/string'`;
  1270. const result = extractFromSource('config.rb', code);
  1271. const importNode = result.nodes.find((n) => n.kind === 'import');
  1272. expect(importNode).toBeDefined();
  1273. expect(importNode?.name).toBe('active_support/core_ext/string');
  1274. });
  1275. it('should extract require_relative', () => {
  1276. const code = `require_relative '../test_helper'`;
  1277. const result = extractFromSource('test/my_test.rb', code);
  1278. const importNode = result.nodes.find((n) => n.kind === 'import');
  1279. expect(importNode).toBeDefined();
  1280. expect(importNode?.name).toBe('../test_helper');
  1281. expect(importNode?.signature).toContain('require_relative');
  1282. });
  1283. it('should not extract non-require calls', () => {
  1284. const code = `puts 'hello'`;
  1285. const result = extractFromSource('app.rb', code);
  1286. const importNode = result.nodes.find((n) => n.kind === 'import');
  1287. expect(importNode).toBeUndefined();
  1288. });
  1289. it('should extract multiple requires', () => {
  1290. const code = `
  1291. require 'json'
  1292. require 'yaml'
  1293. require_relative 'helper'
  1294. `;
  1295. const result = extractFromSource('lib.rb', code);
  1296. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1297. expect(importNodes.length).toBe(3);
  1298. const names = importNodes.map((n) => n.name);
  1299. expect(names).toContain('json');
  1300. expect(names).toContain('yaml');
  1301. expect(names).toContain('helper');
  1302. });
  1303. });
  1304. describe('C/C++ imports', () => {
  1305. it('should extract system include', () => {
  1306. const code = `#include <iostream>`;
  1307. const result = extractFromSource('main.cpp', code);
  1308. const importNode = result.nodes.find((n) => n.kind === 'import');
  1309. expect(importNode).toBeDefined();
  1310. expect(importNode?.name).toBe('iostream');
  1311. expect(importNode?.signature).toBe('#include <iostream>');
  1312. });
  1313. it('should extract system include with path', () => {
  1314. const code = `#include <nlohmann/json.hpp>`;
  1315. const result = extractFromSource('app.cpp', code);
  1316. const importNode = result.nodes.find((n) => n.kind === 'import');
  1317. expect(importNode).toBeDefined();
  1318. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1319. });
  1320. it('should extract local include', () => {
  1321. const code = `#include "myheader.h"`;
  1322. const result = extractFromSource('main.cpp', code);
  1323. const importNode = result.nodes.find((n) => n.kind === 'import');
  1324. expect(importNode).toBeDefined();
  1325. expect(importNode?.name).toBe('myheader.h');
  1326. });
  1327. it('should extract C header', () => {
  1328. const code = `#include <stdio.h>`;
  1329. const result = extractFromSource('main.c', code);
  1330. const importNode = result.nodes.find((n) => n.kind === 'import');
  1331. expect(importNode).toBeDefined();
  1332. expect(importNode?.name).toBe('stdio.h');
  1333. });
  1334. it('should extract multiple includes', () => {
  1335. const code = `
  1336. #include <iostream>
  1337. #include <vector>
  1338. #include "config.h"
  1339. `;
  1340. const result = extractFromSource('app.cpp', code);
  1341. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1342. expect(importNodes.length).toBe(3);
  1343. const names = importNodes.map((n) => n.name);
  1344. expect(names).toContain('iostream');
  1345. expect(names).toContain('vector');
  1346. expect(names).toContain('config.h');
  1347. });
  1348. });
  1349. describe('Dart imports', () => {
  1350. it('should extract dart: import', () => {
  1351. const code = `import 'dart:async';`;
  1352. const result = extractFromSource('main.dart', code);
  1353. const importNode = result.nodes.find((n) => n.kind === 'import');
  1354. expect(importNode).toBeDefined();
  1355. expect(importNode?.name).toBe('dart:async');
  1356. expect(importNode?.signature).toBe("import 'dart:async';");
  1357. });
  1358. it('should extract package import', () => {
  1359. const code = `import 'package:flutter/material.dart';`;
  1360. const result = extractFromSource('app.dart', code);
  1361. const importNode = result.nodes.find((n) => n.kind === 'import');
  1362. expect(importNode).toBeDefined();
  1363. expect(importNode?.name).toBe('package:flutter/material.dart');
  1364. });
  1365. it('should extract aliased import', () => {
  1366. const code = `import 'package:http/http.dart' as http;`;
  1367. const result = extractFromSource('api.dart', code);
  1368. const importNode = result.nodes.find((n) => n.kind === 'import');
  1369. expect(importNode).toBeDefined();
  1370. expect(importNode?.name).toBe('package:http/http.dart');
  1371. expect(importNode?.signature).toContain('as http');
  1372. });
  1373. it('should extract multiple imports', () => {
  1374. const code = `
  1375. import 'dart:async';
  1376. import 'dart:convert';
  1377. import 'package:flutter/material.dart';
  1378. `;
  1379. const result = extractFromSource('main.dart', code);
  1380. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1381. expect(importNodes.length).toBe(3);
  1382. const names = importNodes.map((n) => n.name);
  1383. expect(names).toContain('dart:async');
  1384. expect(names).toContain('dart:convert');
  1385. expect(names).toContain('package:flutter/material.dart');
  1386. });
  1387. it('should extract relative import', () => {
  1388. const code = `import '../utils/helpers.dart';`;
  1389. const result = extractFromSource('lib/main.dart', code);
  1390. const importNode = result.nodes.find((n) => n.kind === 'import');
  1391. expect(importNode).toBeDefined();
  1392. expect(importNode?.name).toBe('../utils/helpers.dart');
  1393. });
  1394. });
  1395. describe('Liquid imports', () => {
  1396. it('should extract render tag', () => {
  1397. const code = `{% render 'loading-spinner' %}`;
  1398. const result = extractFromSource('template.liquid', code);
  1399. const importNode = result.nodes.find((n) => n.kind === 'import');
  1400. expect(importNode).toBeDefined();
  1401. expect(importNode?.name).toBe('loading-spinner');
  1402. expect(importNode?.signature).toContain('render');
  1403. });
  1404. it('should extract section tag', () => {
  1405. const code = `{% section 'header' %}`;
  1406. const result = extractFromSource('layout/theme.liquid', code);
  1407. const importNode = result.nodes.find((n) => n.kind === 'import');
  1408. expect(importNode).toBeDefined();
  1409. expect(importNode?.name).toBe('header');
  1410. expect(importNode?.signature).toContain('section');
  1411. });
  1412. it('should extract include tag', () => {
  1413. const code = `{% include 'icon-cart' %}`;
  1414. const result = extractFromSource('snippets/header.liquid', code);
  1415. const importNode = result.nodes.find((n) => n.kind === 'import');
  1416. expect(importNode).toBeDefined();
  1417. expect(importNode?.name).toBe('icon-cart');
  1418. expect(importNode?.signature).toContain('include');
  1419. });
  1420. it('should extract render with whitespace control', () => {
  1421. const code = `{%- render 'price' -%}`;
  1422. const result = extractFromSource('snippets/product.liquid', code);
  1423. const importNode = result.nodes.find((n) => n.kind === 'import');
  1424. expect(importNode).toBeDefined();
  1425. expect(importNode?.name).toBe('price');
  1426. });
  1427. it('should extract multiple imports', () => {
  1428. const code = `
  1429. {% section 'header' %}
  1430. {% render 'loading-spinner' %}
  1431. {% render 'cart-drawer' %}
  1432. `;
  1433. const result = extractFromSource('layout/theme.liquid', code);
  1434. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1435. expect(importNodes.length).toBe(3);
  1436. const names = importNodes.map((n) => n.name);
  1437. expect(names).toContain('header');
  1438. expect(names).toContain('loading-spinner');
  1439. expect(names).toContain('cart-drawer');
  1440. });
  1441. });
  1442. });
  1443. describe('Full Indexing', () => {
  1444. let tempDir: string;
  1445. beforeEach(() => {
  1446. tempDir = createTempDir();
  1447. });
  1448. afterEach(() => {
  1449. cleanupTempDir(tempDir);
  1450. });
  1451. it('should index a TypeScript file', async () => {
  1452. // Create test file
  1453. const srcDir = path.join(tempDir, 'src');
  1454. fs.mkdirSync(srcDir);
  1455. fs.writeFileSync(
  1456. path.join(srcDir, 'utils.ts'),
  1457. `
  1458. export function add(a: number, b: number): number {
  1459. return a + b;
  1460. }
  1461. export function multiply(a: number, b: number): number {
  1462. return a * b;
  1463. }
  1464. `
  1465. );
  1466. // Initialize and index
  1467. const cg = CodeGraph.initSync(tempDir);
  1468. const result = await cg.indexAll();
  1469. expect(result.success).toBe(true);
  1470. expect(result.filesIndexed).toBe(1);
  1471. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  1472. // Check nodes were stored
  1473. const nodes = cg.getNodesInFile('src/utils.ts');
  1474. expect(nodes.length).toBeGreaterThanOrEqual(2);
  1475. const addFunc = nodes.find((n) => n.name === 'add');
  1476. expect(addFunc).toBeDefined();
  1477. expect(addFunc?.kind).toBe('function');
  1478. cg.close();
  1479. });
  1480. it('should index multiple files', async () => {
  1481. // Create test files
  1482. const srcDir = path.join(tempDir, 'src');
  1483. fs.mkdirSync(srcDir);
  1484. fs.writeFileSync(
  1485. path.join(srcDir, 'math.ts'),
  1486. `export function add(a: number, b: number) { return a + b; }`
  1487. );
  1488. fs.writeFileSync(
  1489. path.join(srcDir, 'string.ts'),
  1490. `export function capitalize(s: string) { return s.toUpperCase(); }`
  1491. );
  1492. // Initialize and index
  1493. const cg = CodeGraph.initSync(tempDir);
  1494. const result = await cg.indexAll();
  1495. expect(result.success).toBe(true);
  1496. expect(result.filesIndexed).toBe(2);
  1497. const files = cg.getFiles();
  1498. expect(files.length).toBe(2);
  1499. cg.close();
  1500. });
  1501. it('should track file hashes for incremental updates', async () => {
  1502. // Create initial file
  1503. const srcDir = path.join(tempDir, 'src');
  1504. fs.mkdirSync(srcDir);
  1505. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  1506. // Initialize and index
  1507. const cg = CodeGraph.initSync(tempDir);
  1508. await cg.indexAll();
  1509. // Check file is tracked
  1510. const file = cg.getFile('src/main.ts');
  1511. expect(file).toBeDefined();
  1512. expect(file?.contentHash).toBeDefined();
  1513. // Modify file
  1514. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  1515. // Check for changes
  1516. const changes = cg.getChangedFiles();
  1517. expect(changes.modified).toContain('src/main.ts');
  1518. cg.close();
  1519. });
  1520. it('should sync and detect changes', async () => {
  1521. // Create initial file
  1522. const srcDir = path.join(tempDir, 'src');
  1523. fs.mkdirSync(srcDir);
  1524. fs.writeFileSync(
  1525. path.join(srcDir, 'main.ts'),
  1526. `export function original() { return 1; }`
  1527. );
  1528. // Initialize and index
  1529. const cg = CodeGraph.initSync(tempDir);
  1530. await cg.indexAll();
  1531. const initialNodes = cg.getNodesInFile('src/main.ts');
  1532. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  1533. // Modify file
  1534. fs.writeFileSync(
  1535. path.join(srcDir, 'main.ts'),
  1536. `export function updated() { return 2; }`
  1537. );
  1538. // Sync
  1539. const syncResult = await cg.sync();
  1540. expect(syncResult.filesModified).toBe(1);
  1541. // Check nodes were updated
  1542. const updatedNodes = cg.getNodesInFile('src/main.ts');
  1543. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  1544. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  1545. cg.close();
  1546. });
  1547. });