extraction.test.ts 61 KB

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