extraction.test.ts 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037
  1. /**
  2. * Extraction Tests
  3. *
  4. * Tests for the tree-sitter extraction system.
  5. */
  6. import { describe, it, expect, beforeAll, 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, scanDirectory, shouldIncludeFile } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages, initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  13. import { normalizePath } from '../src/utils';
  14. import { DEFAULT_CONFIG } from '../src/types';
  15. beforeAll(async () => {
  16. await initGrammars();
  17. await loadAllGrammars();
  18. });
  19. // Create a temporary directory for each test
  20. function createTempDir(): string {
  21. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  22. }
  23. // Clean up temporary directory
  24. function cleanupTempDir(dir: string): void {
  25. if (fs.existsSync(dir)) {
  26. fs.rmSync(dir, { recursive: true, force: true });
  27. }
  28. }
  29. describe('Language Detection', () => {
  30. it('should detect TypeScript files', () => {
  31. expect(detectLanguage('src/index.ts')).toBe('typescript');
  32. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  33. });
  34. it('should detect JavaScript files', () => {
  35. expect(detectLanguage('index.js')).toBe('javascript');
  36. expect(detectLanguage('App.jsx')).toBe('jsx');
  37. expect(detectLanguage('config.mjs')).toBe('javascript');
  38. });
  39. it('should detect Python files', () => {
  40. expect(detectLanguage('main.py')).toBe('python');
  41. });
  42. it('should detect Go files', () => {
  43. expect(detectLanguage('main.go')).toBe('go');
  44. });
  45. it('should detect Rust files', () => {
  46. expect(detectLanguage('lib.rs')).toBe('rust');
  47. });
  48. it('should detect Java files', () => {
  49. expect(detectLanguage('Main.java')).toBe('java');
  50. });
  51. it('should detect C files', () => {
  52. expect(detectLanguage('main.c')).toBe('c');
  53. expect(detectLanguage('utils.h')).toBe('c');
  54. });
  55. it('should detect C++ files', () => {
  56. expect(detectLanguage('main.cpp')).toBe('cpp');
  57. expect(detectLanguage('class.hpp')).toBe('cpp');
  58. });
  59. it('should detect C# files', () => {
  60. expect(detectLanguage('Program.cs')).toBe('csharp');
  61. });
  62. it('should detect PHP files', () => {
  63. expect(detectLanguage('index.php')).toBe('php');
  64. });
  65. it('should detect Ruby files', () => {
  66. expect(detectLanguage('app.rb')).toBe('ruby');
  67. });
  68. it('should detect Swift files', () => {
  69. expect(detectLanguage('ViewController.swift')).toBe('swift');
  70. });
  71. it('should detect Kotlin files', () => {
  72. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  73. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  74. });
  75. it('should detect Dart files', () => {
  76. expect(detectLanguage('main.dart')).toBe('dart');
  77. });
  78. it('should return unknown for unsupported extensions', () => {
  79. expect(detectLanguage('styles.css')).toBe('unknown');
  80. expect(detectLanguage('data.json')).toBe('unknown');
  81. });
  82. });
  83. describe('Language Support', () => {
  84. it('should report supported languages', () => {
  85. expect(isLanguageSupported('typescript')).toBe(true);
  86. expect(isLanguageSupported('python')).toBe(true);
  87. expect(isLanguageSupported('go')).toBe(true);
  88. expect(isLanguageSupported('unknown')).toBe(false);
  89. });
  90. it('should list all supported languages', () => {
  91. const languages = getSupportedLanguages();
  92. expect(languages).toContain('typescript');
  93. expect(languages).toContain('javascript');
  94. expect(languages).toContain('python');
  95. expect(languages).toContain('go');
  96. expect(languages).toContain('rust');
  97. expect(languages).toContain('java');
  98. expect(languages).toContain('csharp');
  99. expect(languages).toContain('php');
  100. expect(languages).toContain('ruby');
  101. expect(languages).toContain('swift');
  102. expect(languages).toContain('kotlin');
  103. expect(languages).toContain('dart');
  104. });
  105. });
  106. describe('TypeScript Extraction', () => {
  107. it('should extract function declarations', () => {
  108. const code = `
  109. export function processPayment(amount: number): Promise<Receipt> {
  110. return stripe.charge(amount);
  111. }
  112. `;
  113. const result = extractFromSource('payment.ts', code);
  114. // File node + function node
  115. const fileNode = result.nodes.find((n) => n.kind === 'file');
  116. expect(fileNode).toBeDefined();
  117. expect(fileNode?.name).toBe('payment.ts');
  118. const funcNode = result.nodes.find((n) => n.kind === 'function');
  119. expect(funcNode).toMatchObject({
  120. kind: 'function',
  121. name: 'processPayment',
  122. language: 'typescript',
  123. isExported: true,
  124. });
  125. expect(funcNode?.signature).toContain('amount: number');
  126. });
  127. it('should extract class declarations', () => {
  128. const code = `
  129. export class PaymentService {
  130. private stripe: StripeClient;
  131. constructor(apiKey: string) {
  132. this.stripe = new StripeClient(apiKey);
  133. }
  134. async charge(amount: number): Promise<Receipt> {
  135. return this.stripe.charge(amount);
  136. }
  137. }
  138. `;
  139. const result = extractFromSource('service.ts', code);
  140. const classNode = result.nodes.find((n) => n.kind === 'class');
  141. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  142. expect(classNode).toBeDefined();
  143. expect(classNode?.name).toBe('PaymentService');
  144. expect(classNode?.isExported).toBe(true);
  145. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  146. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  147. expect(chargeMethod).toBeDefined();
  148. });
  149. it('should extract interfaces', () => {
  150. const code = `
  151. export interface User {
  152. id: string;
  153. name: string;
  154. email: string;
  155. }
  156. `;
  157. const result = extractFromSource('types.ts', code);
  158. const fileNode = result.nodes.find((n) => n.kind === 'file');
  159. expect(fileNode).toBeDefined();
  160. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  161. expect(ifaceNode).toMatchObject({
  162. kind: 'interface',
  163. name: 'User',
  164. isExported: true,
  165. });
  166. });
  167. it('should track function calls', () => {
  168. const code = `
  169. function main() {
  170. const result = processData();
  171. console.log(result);
  172. }
  173. `;
  174. const result = extractFromSource('main.ts', code);
  175. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  176. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  177. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  178. });
  179. });
  180. describe('Arrow Function Export Extraction', () => {
  181. it('should extract exported arrow functions assigned to const', () => {
  182. const code = `
  183. export const useAuth = (): AuthContextValue => {
  184. return useContext(AuthContext);
  185. };
  186. `;
  187. const result = extractFromSource('hooks.ts', code);
  188. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  189. expect(funcNode).toBeDefined();
  190. expect(funcNode).toMatchObject({
  191. kind: 'function',
  192. name: 'useAuth',
  193. isExported: true,
  194. });
  195. });
  196. it('should extract exported function expressions assigned to const', () => {
  197. const code = `
  198. export const processData = function(input: string): string {
  199. return input.trim();
  200. };
  201. `;
  202. const result = extractFromSource('utils.ts', code);
  203. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  204. expect(funcNode).toBeDefined();
  205. expect(funcNode).toMatchObject({
  206. kind: 'function',
  207. name: 'processData',
  208. isExported: true,
  209. });
  210. });
  211. it('should not extract non-exported arrow functions as exported', () => {
  212. const code = `
  213. const internalHelper = () => {
  214. return 42;
  215. };
  216. `;
  217. const result = extractFromSource('internal.ts', code);
  218. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  219. expect(helperNode).toBeDefined();
  220. expect(helperNode?.isExported).toBeFalsy();
  221. });
  222. it('should still skip truly anonymous arrow functions', () => {
  223. const code = `
  224. const items = [1, 2, 3].map((x) => x * 2);
  225. `;
  226. const result = extractFromSource('anon.ts', code);
  227. // The inline arrow function passed to .map() has no variable_declarator parent
  228. // and should remain anonymous (skipped)
  229. const anonFunctions = result.nodes.filter(
  230. (n) => n.kind === 'function' && n.name === '<anonymous>'
  231. );
  232. expect(anonFunctions).toHaveLength(0);
  233. });
  234. it('should extract multiple exported arrow functions from the same file', () => {
  235. const code = `
  236. export const add = (a: number, b: number): number => a + b;
  237. export const subtract = (a: number, b: number): number => a - b;
  238. const internal = () => 'not exported';
  239. `;
  240. const result = extractFromSource('math.ts', code);
  241. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  242. expect(exported).toHaveLength(2);
  243. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  244. const internalNode = result.nodes.find((n) => n.name === 'internal');
  245. expect(internalNode).toBeDefined();
  246. expect(internalNode?.isExported).toBeFalsy();
  247. });
  248. it('should extract arrow functions in JavaScript files', () => {
  249. const code = `
  250. export const fetchData = async () => {
  251. const response = await fetch('/api/data');
  252. return response.json();
  253. };
  254. `;
  255. const result = extractFromSource('api.js', code);
  256. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  257. expect(funcNode).toBeDefined();
  258. expect(funcNode).toMatchObject({
  259. kind: 'function',
  260. name: 'fetchData',
  261. isExported: true,
  262. });
  263. });
  264. });
  265. describe('Type Alias Extraction', () => {
  266. it('should extract exported type aliases in TypeScript', () => {
  267. const code = `
  268. export type AuthContextValue = {
  269. user: User | null;
  270. login: () => void;
  271. logout: () => void;
  272. };
  273. `;
  274. const result = extractFromSource('types.ts', code);
  275. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  276. expect(typeNode).toMatchObject({
  277. kind: 'type_alias',
  278. name: 'AuthContextValue',
  279. isExported: true,
  280. });
  281. });
  282. it('should extract non-exported type aliases', () => {
  283. const code = `
  284. type InternalState = {
  285. loading: boolean;
  286. error: string | null;
  287. };
  288. `;
  289. const result = extractFromSource('internal.ts', code);
  290. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  291. expect(typeNode).toMatchObject({
  292. kind: 'type_alias',
  293. name: 'InternalState',
  294. isExported: false,
  295. });
  296. });
  297. it('should extract multiple type aliases from the same file', () => {
  298. const code = `
  299. export type UnitSystem = 'metric' | 'imperial';
  300. export type DateFormat = 'ISO' | 'US' | 'EU';
  301. type Internal = string;
  302. `;
  303. const result = extractFromSource('config.ts', code);
  304. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  305. expect(typeAliases).toHaveLength(3);
  306. const exported = typeAliases.filter((n) => n.isExported);
  307. expect(exported).toHaveLength(2);
  308. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  309. });
  310. });
  311. describe('Exported Variable Extraction', () => {
  312. it('should extract exported const with call expression (Zustand store)', () => {
  313. const code = `
  314. export const useUIStore = create<UIState>((set) => ({
  315. isOpen: false,
  316. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  317. }));
  318. `;
  319. const result = extractFromSource('store.ts', code);
  320. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'useUIStore');
  321. expect(varNode).toBeDefined();
  322. expect(varNode?.isExported).toBe(true);
  323. });
  324. it('should extract exported const with object literal', () => {
  325. const code = `
  326. export const config = {
  327. apiUrl: 'https://api.example.com',
  328. timeout: 5000,
  329. };
  330. `;
  331. const result = extractFromSource('config.ts', code);
  332. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'config');
  333. expect(varNode).toBeDefined();
  334. expect(varNode?.isExported).toBe(true);
  335. });
  336. it('should extract exported const with array literal', () => {
  337. const code = `
  338. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  339. `;
  340. const result = extractFromSource('constants.ts', code);
  341. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'SCREEN_NAMES');
  342. expect(varNode).toBeDefined();
  343. expect(varNode?.isExported).toBe(true);
  344. });
  345. it('should extract exported const with primitive value', () => {
  346. const code = `
  347. export const MAX_RETRIES = 3;
  348. export const API_VERSION = "v2";
  349. `;
  350. const result = extractFromSource('constants.ts', code);
  351. const variables = result.nodes.filter((n) => n.kind === 'variable');
  352. expect(variables).toHaveLength(2);
  353. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  354. });
  355. it('should NOT duplicate arrow functions as both function and variable', () => {
  356. const code = `
  357. export const useAuth = () => {
  358. return useContext(AuthContext);
  359. };
  360. `;
  361. const result = extractFromSource('hooks.ts', code);
  362. // Should be extracted as function (from arrow function handler), NOT as variable
  363. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  364. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  365. expect(funcNodes).toHaveLength(1);
  366. expect(varNodes).toHaveLength(0);
  367. });
  368. it('should extract non-exported const as non-exported variable', () => {
  369. const code = `
  370. const internalConfig = {
  371. debug: true,
  372. };
  373. `;
  374. const result = extractFromSource('internal.ts', code);
  375. // Non-exported const at file level should be extracted as a constant (not exported)
  376. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  377. expect(varNodes).toHaveLength(1);
  378. expect(varNodes[0]?.isExported).toBeFalsy();
  379. });
  380. it('should extract Zod schema exports', () => {
  381. const code = `
  382. export const userSchema = z.object({
  383. id: z.string(),
  384. name: z.string(),
  385. email: z.string().email(),
  386. });
  387. `;
  388. const result = extractFromSource('schemas.ts', code);
  389. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'userSchema');
  390. expect(varNode).toBeDefined();
  391. expect(varNode?.isExported).toBe(true);
  392. });
  393. it('should extract XState machine exports', () => {
  394. const code = `
  395. export const authMachine = createMachine({
  396. id: "auth",
  397. initial: "idle",
  398. states: {
  399. idle: {},
  400. authenticated: {},
  401. },
  402. });
  403. `;
  404. const result = extractFromSource('machine.ts', code);
  405. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'authMachine');
  406. expect(varNode).toBeDefined();
  407. expect(varNode?.isExported).toBe(true);
  408. });
  409. });
  410. describe('File Node Extraction', () => {
  411. it('should create a file-kind node for each parsed file', () => {
  412. const code = `
  413. export function greet(name: string): string {
  414. return "Hello " + name;
  415. }
  416. `;
  417. const result = extractFromSource('greeter.ts', code);
  418. const fileNode = result.nodes.find((n) => n.kind === 'file');
  419. expect(fileNode).toBeDefined();
  420. expect(fileNode?.name).toBe('greeter.ts');
  421. expect(fileNode?.filePath).toBe('greeter.ts');
  422. expect(fileNode?.language).toBe('typescript');
  423. expect(fileNode?.startLine).toBe(1);
  424. });
  425. it('should create file nodes for Python files', () => {
  426. const code = `
  427. def main():
  428. pass
  429. `;
  430. const result = extractFromSource('main.py', code);
  431. const fileNode = result.nodes.find((n) => n.kind === 'file');
  432. expect(fileNode).toBeDefined();
  433. expect(fileNode?.name).toBe('main.py');
  434. expect(fileNode?.language).toBe('python');
  435. });
  436. it('should create containment edges from file node to top-level declarations', () => {
  437. const code = `
  438. export function foo() {}
  439. export function bar() {}
  440. `;
  441. const result = extractFromSource('fns.ts', code);
  442. const fileNode = result.nodes.find((n) => n.kind === 'file');
  443. expect(fileNode).toBeDefined();
  444. // There should be contains edges from the file node to each function
  445. const containsEdges = result.edges.filter(
  446. (e) => e.source === fileNode?.id && e.kind === 'contains'
  447. );
  448. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  449. });
  450. });
  451. describe('Python Extraction', () => {
  452. it('should extract function definitions', () => {
  453. const code = `
  454. def calculate_total(items: list, tax_rate: float) -> float:
  455. """Calculate total with tax."""
  456. subtotal = sum(item.price for item in items)
  457. return subtotal * (1 + tax_rate)
  458. `;
  459. const result = extractFromSource('calc.py', code);
  460. const fileNode = result.nodes.find((n) => n.kind === 'file');
  461. expect(fileNode).toBeDefined();
  462. const funcNode = result.nodes.find((n) => n.kind === 'function');
  463. expect(funcNode).toMatchObject({
  464. kind: 'function',
  465. name: 'calculate_total',
  466. language: 'python',
  467. });
  468. });
  469. it('should extract class definitions', () => {
  470. const code = `
  471. class UserService:
  472. """Service for managing users."""
  473. def __init__(self, db):
  474. self.db = db
  475. def get_user(self, user_id: str) -> User:
  476. return self.db.find_user(user_id)
  477. `;
  478. const result = extractFromSource('service.py', code);
  479. const classNode = result.nodes.find((n) => n.kind === 'class');
  480. expect(classNode).toBeDefined();
  481. expect(classNode?.name).toBe('UserService');
  482. });
  483. });
  484. describe('Go Extraction', () => {
  485. it('should extract function declarations', () => {
  486. const code = `
  487. package main
  488. func ProcessOrder(order Order) (Receipt, error) {
  489. // Process the order
  490. return Receipt{}, nil
  491. }
  492. `;
  493. const result = extractFromSource('main.go', code);
  494. const funcNode = result.nodes.find((n) => n.kind === 'function');
  495. expect(funcNode).toBeDefined();
  496. expect(funcNode?.name).toBe('ProcessOrder');
  497. });
  498. it('should extract method declarations', () => {
  499. const code = `
  500. package main
  501. type Service struct {
  502. db *Database
  503. }
  504. func (s *Service) GetUser(id string) (*User, error) {
  505. return s.db.FindUser(id)
  506. }
  507. `;
  508. const result = extractFromSource('service.go', code);
  509. const methodNode = result.nodes.find((n) => n.kind === 'method');
  510. expect(methodNode).toBeDefined();
  511. expect(methodNode?.name).toBe('GetUser');
  512. });
  513. });
  514. describe('Rust Extraction', () => {
  515. it('should extract function declarations', () => {
  516. const code = `
  517. pub fn process_data(input: &str) -> Result<Output, Error> {
  518. // Process data
  519. Ok(Output::new())
  520. }
  521. `;
  522. const result = extractFromSource('lib.rs', code);
  523. const funcNode = result.nodes.find((n) => n.kind === 'function');
  524. expect(funcNode).toBeDefined();
  525. expect(funcNode?.name).toBe('process_data');
  526. expect(funcNode?.visibility).toBe('public');
  527. });
  528. it('should extract struct declarations', () => {
  529. const code = `
  530. pub struct User {
  531. pub id: String,
  532. pub name: String,
  533. email: String,
  534. }
  535. `;
  536. const result = extractFromSource('models.rs', code);
  537. const structNode = result.nodes.find((n) => n.kind === 'struct');
  538. expect(structNode).toBeDefined();
  539. expect(structNode?.name).toBe('User');
  540. });
  541. it('should extract trait declarations', () => {
  542. const code = `
  543. pub trait Repository {
  544. fn find(&self, id: &str) -> Option<Entity>;
  545. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  546. }
  547. `;
  548. const result = extractFromSource('traits.rs', code);
  549. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  550. expect(traitNode).toBeDefined();
  551. expect(traitNode?.name).toBe('Repository');
  552. });
  553. it('should extract impl Trait for Type as implements edges', () => {
  554. const code = `
  555. pub struct MyCache {}
  556. pub trait Cache {
  557. fn get(&self, key: &str) -> Option<String>;
  558. }
  559. impl Cache for MyCache {
  560. fn get(&self, key: &str) -> Option<String> {
  561. None
  562. }
  563. }
  564. `;
  565. const result = extractFromSource('cache.rs', code);
  566. // Should have an unresolved reference for implements
  567. const implRef = result.unresolvedReferences.find(
  568. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  569. );
  570. expect(implRef).toBeDefined();
  571. // The struct MyCache should be the source
  572. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  573. expect(myCacheNode).toBeDefined();
  574. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  575. });
  576. it('should extract trait supertraits as extends references', () => {
  577. const code = `
  578. pub trait Display {}
  579. pub trait Error: Display {
  580. fn description(&self) -> &str;
  581. }
  582. `;
  583. const result = extractFromSource('error.rs', code);
  584. const extendsRef = result.unresolvedReferences.find(
  585. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  586. );
  587. expect(extendsRef).toBeDefined();
  588. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  589. expect(errorTrait).toBeDefined();
  590. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  591. });
  592. it('should not create implements edges for plain impl blocks', () => {
  593. const code = `
  594. pub struct Counter {
  595. count: u32,
  596. }
  597. impl Counter {
  598. pub fn new() -> Counter {
  599. Counter { count: 0 }
  600. }
  601. pub fn increment(&mut self) {
  602. self.count += 1;
  603. }
  604. }
  605. `;
  606. const result = extractFromSource('counter.rs', code);
  607. // Should have no implements references (no trait involved)
  608. const implRefs = result.unresolvedReferences.filter(
  609. (r) => r.referenceKind === 'implements'
  610. );
  611. expect(implRefs).toHaveLength(0);
  612. });
  613. });
  614. describe('Java Extraction', () => {
  615. it('should extract class declarations', () => {
  616. const code = `
  617. public class UserService {
  618. private final UserRepository repository;
  619. public UserService(UserRepository repository) {
  620. this.repository = repository;
  621. }
  622. public User getUser(String id) {
  623. return repository.findById(id);
  624. }
  625. }
  626. `;
  627. const result = extractFromSource('UserService.java', code);
  628. const classNode = result.nodes.find((n) => n.kind === 'class');
  629. expect(classNode).toBeDefined();
  630. expect(classNode?.name).toBe('UserService');
  631. expect(classNode?.visibility).toBe('public');
  632. });
  633. it('should extract method declarations', () => {
  634. const code = `
  635. public class Calculator {
  636. public static int add(int a, int b) {
  637. return a + b;
  638. }
  639. }
  640. `;
  641. const result = extractFromSource('Calculator.java', code);
  642. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  643. expect(methodNode).toBeDefined();
  644. expect(methodNode?.isStatic).toBe(true);
  645. });
  646. });
  647. describe('C# Extraction', () => {
  648. it('should extract class declarations', () => {
  649. const code = `
  650. public class OrderService
  651. {
  652. private readonly IOrderRepository _repository;
  653. public OrderService(IOrderRepository repository)
  654. {
  655. _repository = repository;
  656. }
  657. public async Task<Order> GetOrderAsync(string id)
  658. {
  659. return await _repository.FindByIdAsync(id);
  660. }
  661. }
  662. `;
  663. const result = extractFromSource('OrderService.cs', code);
  664. const classNode = result.nodes.find((n) => n.kind === 'class');
  665. expect(classNode).toBeDefined();
  666. expect(classNode?.name).toBe('OrderService');
  667. expect(classNode?.visibility).toBe('public');
  668. });
  669. });
  670. describe('PHP Extraction', () => {
  671. it('should extract class declarations', () => {
  672. const code = `<?php
  673. class UserController
  674. {
  675. private UserService $userService;
  676. public function __construct(UserService $userService)
  677. {
  678. $this->userService = $userService;
  679. }
  680. public function show(string $id): User
  681. {
  682. return $this->userService->find($id);
  683. }
  684. }
  685. `;
  686. const result = extractFromSource('UserController.php', code);
  687. const classNode = result.nodes.find((n) => n.kind === 'class');
  688. expect(classNode).toBeDefined();
  689. expect(classNode?.name).toBe('UserController');
  690. });
  691. it('should extract class inheritance (extends) and interface implementation', () => {
  692. const code = `<?php
  693. class ChildController extends BaseController implements Serializable, JsonSerializable
  694. {
  695. public function serialize(): string
  696. {
  697. return json_encode($this);
  698. }
  699. }
  700. `;
  701. const result = extractFromSource('ChildController.php', code);
  702. const classNode = result.nodes.find((n) => n.kind === 'class');
  703. expect(classNode).toBeDefined();
  704. expect(classNode?.name).toBe('ChildController');
  705. const extendsRef = result.unresolvedReferences.find(
  706. (r) => r.referenceKind === 'extends'
  707. );
  708. expect(extendsRef).toBeDefined();
  709. expect(extendsRef?.referenceName).toBe('BaseController');
  710. const implementsRefs = result.unresolvedReferences.filter(
  711. (r) => r.referenceKind === 'implements'
  712. );
  713. expect(implementsRefs.length).toBe(2);
  714. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  715. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  716. });
  717. });
  718. describe('Swift Extraction', () => {
  719. it('should extract class declarations', () => {
  720. const code = `
  721. public class NetworkManager {
  722. private let session: URLSession
  723. public init(session: URLSession = .shared) {
  724. self.session = session
  725. }
  726. public func fetchData(from url: URL) async throws -> Data {
  727. let (data, _) = try await session.data(from: url)
  728. return data
  729. }
  730. }
  731. `;
  732. const result = extractFromSource('NetworkManager.swift', code);
  733. const classNode = result.nodes.find((n) => n.kind === 'class');
  734. expect(classNode).toBeDefined();
  735. expect(classNode?.name).toBe('NetworkManager');
  736. });
  737. it('should extract function declarations', () => {
  738. const code = `
  739. func calculateSum(_ numbers: [Int]) -> Int {
  740. return numbers.reduce(0, +)
  741. }
  742. public func formatCurrency(amount: Double) -> String {
  743. return String(format: "$%.2f", amount)
  744. }
  745. `;
  746. const result = extractFromSource('utils.swift', code);
  747. const functions = result.nodes.filter((n) => n.kind === 'function');
  748. expect(functions.length).toBeGreaterThanOrEqual(1);
  749. });
  750. it('should extract struct declarations', () => {
  751. const code = `
  752. public struct User {
  753. let id: UUID
  754. var name: String
  755. var email: String
  756. func displayName() -> String {
  757. return name
  758. }
  759. }
  760. `;
  761. const result = extractFromSource('User.swift', code);
  762. const structNode = result.nodes.find((n) => n.kind === 'struct');
  763. expect(structNode).toBeDefined();
  764. expect(structNode?.name).toBe('User');
  765. });
  766. it('should extract protocol declarations', () => {
  767. const code = `
  768. public protocol Repository {
  769. associatedtype Entity
  770. func find(id: String) async throws -> Entity?
  771. func save(_ entity: Entity) async throws
  772. }
  773. `;
  774. const result = extractFromSource('Repository.swift', code);
  775. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  776. expect(protocolNode).toBeDefined();
  777. expect(protocolNode?.name).toBe('Repository');
  778. });
  779. it('should extract class inheritance and protocol conformance', () => {
  780. const code = `
  781. class DataRequest: Request {
  782. func validate() {}
  783. }
  784. class UploadRequest: DataRequest, Sendable {
  785. func upload() {}
  786. }
  787. enum AFError: Error {
  788. case invalidURL
  789. }
  790. struct HTTPMethod: RawRepresentable {
  791. let rawValue: String
  792. }
  793. protocol UploadConvertible: URLRequestConvertible {
  794. func asURLRequest() throws -> URLRequest
  795. }
  796. `;
  797. const result = extractFromSource('Inheritance.swift', code);
  798. const extendsRefs = result.unresolvedReferences.filter(
  799. (r) => r.referenceKind === 'extends'
  800. );
  801. // DataRequest extends Request
  802. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  803. // UploadRequest extends DataRequest and Sendable
  804. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  805. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  806. // AFError extends Error
  807. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  808. // HTTPMethod extends RawRepresentable
  809. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  810. // UploadConvertible extends URLRequestConvertible
  811. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  812. });
  813. });
  814. describe('Kotlin Extraction', () => {
  815. it('should extract class declarations', () => {
  816. const code = `
  817. class UserRepository(private val database: Database) {
  818. fun findById(id: String): User? {
  819. return database.query("SELECT * FROM users WHERE id = ?", id)
  820. }
  821. suspend fun save(user: User) {
  822. database.insert(user)
  823. }
  824. }
  825. `;
  826. const result = extractFromSource('UserRepository.kt', code);
  827. const classNode = result.nodes.find((n) => n.kind === 'class');
  828. expect(classNode).toBeDefined();
  829. expect(classNode?.name).toBe('UserRepository');
  830. });
  831. it('should extract function declarations', () => {
  832. const code = `
  833. fun calculateTotal(items: List<Item>): Double {
  834. return items.sumOf { it.price }
  835. }
  836. suspend fun fetchUserData(userId: String): User {
  837. return api.getUser(userId)
  838. }
  839. `;
  840. const result = extractFromSource('utils.kt', code);
  841. const functions = result.nodes.filter((n) => n.kind === 'function');
  842. expect(functions.length).toBeGreaterThanOrEqual(1);
  843. });
  844. it('should detect suspend functions as async', () => {
  845. const code = `
  846. suspend fun loadData(): List<String> {
  847. delay(1000)
  848. return listOf("a", "b", "c")
  849. }
  850. `;
  851. const result = extractFromSource('loader.kt', code);
  852. const funcNode = result.nodes.find((n) => n.kind === 'function');
  853. expect(funcNode).toBeDefined();
  854. expect(funcNode?.isAsync).toBe(true);
  855. });
  856. it('should extract fun interface declarations', () => {
  857. const code = `
  858. fun interface OnObjectRetainedListener {
  859. fun onObjectRetained()
  860. }
  861. `;
  862. const result = extractFromSource('listener.kt', code);
  863. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  864. expect(ifaceNode).toBeDefined();
  865. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  866. const methodNode = result.nodes.find((n) => n.kind === 'method');
  867. expect(methodNode).toBeDefined();
  868. expect(methodNode?.name).toBe('onObjectRetained');
  869. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  870. });
  871. it('should extract complex fun interface with nested classes', () => {
  872. const code = `
  873. fun interface EventListener {
  874. fun onEvent(event: Event)
  875. sealed class Event {
  876. class DumpingHeap : Event()
  877. }
  878. }
  879. `;
  880. const result = extractFromSource('events.kt', code);
  881. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  882. expect(ifaceNode).toBeDefined();
  883. expect(ifaceNode?.name).toBe('EventListener');
  884. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  885. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  886. expect(eventClass).toBeDefined();
  887. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  888. expect(dumpingHeap).toBeDefined();
  889. });
  890. it('should not affect regular function declarations', () => {
  891. const code = `
  892. fun interface MyCallback {
  893. fun invoke(value: Int)
  894. }
  895. fun regularFunction(): String {
  896. return "hello"
  897. }
  898. `;
  899. const result = extractFromSource('mixed.kt', code);
  900. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  901. expect(ifaceNode).toBeDefined();
  902. expect(ifaceNode?.name).toBe('MyCallback');
  903. const funcNode = result.nodes.find((n) => n.kind === 'function');
  904. expect(funcNode).toBeDefined();
  905. expect(funcNode?.name).toBe('regularFunction');
  906. });
  907. });
  908. describe('Dart Extraction', () => {
  909. it('should extract class declarations', () => {
  910. const code = `
  911. class UserService {
  912. final Database _db;
  913. Future<User> findById(String id) async {
  914. return await _db.query(id);
  915. }
  916. void _privateMethod() {}
  917. }
  918. `;
  919. const result = extractFromSource('service.dart', code);
  920. const classNode = result.nodes.find((n) => n.kind === 'class');
  921. expect(classNode).toBeDefined();
  922. expect(classNode?.name).toBe('UserService');
  923. expect(classNode?.visibility).toBe('public');
  924. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  925. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  926. const findById = methodNodes.find((m) => m.name === 'findById');
  927. expect(findById).toBeDefined();
  928. expect(findById?.isAsync).toBe(true);
  929. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  930. expect(privateMethod).toBeDefined();
  931. expect(privateMethod?.visibility).toBe('private');
  932. });
  933. it('should extract top-level function declarations', () => {
  934. const code = `
  935. void topLevelFunction(String name) {
  936. print(name);
  937. }
  938. `;
  939. const result = extractFromSource('utils.dart', code);
  940. const funcNode = result.nodes.find((n) => n.kind === 'function');
  941. expect(funcNode).toBeDefined();
  942. expect(funcNode?.name).toBe('topLevelFunction');
  943. expect(funcNode?.language).toBe('dart');
  944. });
  945. it('should extract enum declarations', () => {
  946. const code = `
  947. enum Status { active, inactive, pending }
  948. `;
  949. const result = extractFromSource('models.dart', code);
  950. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  951. expect(enumNode).toBeDefined();
  952. expect(enumNode?.name).toBe('Status');
  953. });
  954. it('should extract mixin declarations', () => {
  955. const code = `
  956. mixin LoggerMixin {
  957. void log(String message) {}
  958. }
  959. `;
  960. const result = extractFromSource('mixins.dart', code);
  961. const classNode = result.nodes.find((n) => n.kind === 'class');
  962. expect(classNode).toBeDefined();
  963. expect(classNode?.name).toBe('LoggerMixin');
  964. const methodNode = result.nodes.find((n) => n.kind === 'method');
  965. expect(methodNode).toBeDefined();
  966. expect(methodNode?.name).toBe('log');
  967. });
  968. it('should extract extension declarations', () => {
  969. const code = `
  970. extension StringExt on String {
  971. bool get isBlank => trim().isEmpty;
  972. }
  973. `;
  974. const result = extractFromSource('extensions.dart', code);
  975. const classNode = result.nodes.find((n) => n.kind === 'class');
  976. expect(classNode).toBeDefined();
  977. expect(classNode?.name).toBe('StringExt');
  978. });
  979. it('should detect static methods', () => {
  980. const code = `
  981. class Utils {
  982. static void doWork() {}
  983. }
  984. `;
  985. const result = extractFromSource('utils.dart', code);
  986. const methodNode = result.nodes.find((n) => n.kind === 'method');
  987. expect(methodNode).toBeDefined();
  988. expect(methodNode?.name).toBe('doWork');
  989. expect(methodNode?.isStatic).toBe(true);
  990. });
  991. it('should detect async functions', () => {
  992. const code = `
  993. Future<String> fetchData() async {
  994. return await http.get('/data');
  995. }
  996. `;
  997. const result = extractFromSource('api.dart', code);
  998. const funcNode = result.nodes.find((n) => n.kind === 'function');
  999. expect(funcNode).toBeDefined();
  1000. expect(funcNode?.name).toBe('fetchData');
  1001. expect(funcNode?.isAsync).toBe(true);
  1002. });
  1003. it('should detect private visibility via underscore convention', () => {
  1004. const code = `
  1005. void _privateHelper() {}
  1006. void publicFunction() {}
  1007. `;
  1008. const result = extractFromSource('helpers.dart', code);
  1009. const functions = result.nodes.filter((n) => n.kind === 'function');
  1010. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1011. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1012. expect(privateFunc?.visibility).toBe('private');
  1013. expect(publicFunc?.visibility).toBe('public');
  1014. });
  1015. });
  1016. describe('Import Extraction', () => {
  1017. describe('TypeScript/JavaScript imports', () => {
  1018. it('should extract default imports', () => {
  1019. const code = `import React from 'react';`;
  1020. const result = extractFromSource('app.tsx', code);
  1021. const importNode = result.nodes.find((n) => n.kind === 'import');
  1022. expect(importNode).toBeDefined();
  1023. expect(importNode?.name).toBe('react');
  1024. expect(importNode?.signature).toBe("import React from 'react';");
  1025. });
  1026. it('should extract named imports', () => {
  1027. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1028. const result = extractFromSource('icons.tsx', code);
  1029. const importNode = result.nodes.find((n) => n.kind === 'import');
  1030. expect(importNode).toBeDefined();
  1031. expect(importNode?.name).toBe('@phosphor-icons/react');
  1032. expect(importNode?.signature).toContain('Bug');
  1033. expect(importNode?.signature).toContain('Database');
  1034. });
  1035. it('should extract namespace imports', () => {
  1036. const code = `import * as Icons from '@phosphor-icons/react';`;
  1037. const result = extractFromSource('icons.tsx', code);
  1038. const importNode = result.nodes.find((n) => n.kind === 'import');
  1039. expect(importNode).toBeDefined();
  1040. expect(importNode?.name).toBe('@phosphor-icons/react');
  1041. expect(importNode?.signature).toContain('* as Icons');
  1042. });
  1043. it('should extract side-effect imports', () => {
  1044. const code = `import './styles.css';`;
  1045. const result = extractFromSource('app.tsx', code);
  1046. const importNode = result.nodes.find((n) => n.kind === 'import');
  1047. expect(importNode).toBeDefined();
  1048. expect(importNode?.name).toBe('./styles.css');
  1049. });
  1050. it('should extract mixed imports (default + named)', () => {
  1051. const code = `import React, { useState, useEffect } from 'react';`;
  1052. const result = extractFromSource('app.tsx', code);
  1053. const importNode = result.nodes.find((n) => n.kind === 'import');
  1054. expect(importNode).toBeDefined();
  1055. expect(importNode?.name).toBe('react');
  1056. expect(importNode?.signature).toContain('React');
  1057. expect(importNode?.signature).toContain('useState');
  1058. expect(importNode?.signature).toContain('useEffect');
  1059. });
  1060. it('should extract multiple import statements', () => {
  1061. const code = `
  1062. import React from 'react';
  1063. import { Button } from './components';
  1064. import './styles.css';
  1065. `;
  1066. const result = extractFromSource('app.tsx', code);
  1067. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1068. expect(importNodes.length).toBe(3);
  1069. const names = importNodes.map((n) => n.name);
  1070. expect(names).toContain('react');
  1071. expect(names).toContain('./components');
  1072. expect(names).toContain('./styles.css');
  1073. });
  1074. it('should extract type imports', () => {
  1075. const code = `import type { FC, ReactNode } from 'react';`;
  1076. const result = extractFromSource('types.ts', code);
  1077. const importNode = result.nodes.find((n) => n.kind === 'import');
  1078. expect(importNode).toBeDefined();
  1079. expect(importNode?.name).toBe('react');
  1080. expect(importNode?.signature).toContain('type');
  1081. expect(importNode?.signature).toContain('FC');
  1082. });
  1083. it('should extract aliased named imports', () => {
  1084. const code = `import { useState as useStateAlias } from 'react';`;
  1085. const result = extractFromSource('hooks.ts', code);
  1086. const importNode = result.nodes.find((n) => n.kind === 'import');
  1087. expect(importNode).toBeDefined();
  1088. expect(importNode?.name).toBe('react');
  1089. expect(importNode?.signature).toContain('useState');
  1090. expect(importNode?.signature).toContain('useStateAlias');
  1091. });
  1092. it('should extract relative path imports', () => {
  1093. const code = `import { helper } from '../utils/helper';`;
  1094. const result = extractFromSource('components/Button.tsx', code);
  1095. const importNode = result.nodes.find((n) => n.kind === 'import');
  1096. expect(importNode).toBeDefined();
  1097. expect(importNode?.name).toBe('../utils/helper');
  1098. expect(importNode?.signature).toContain('helper');
  1099. });
  1100. });
  1101. describe('Python imports', () => {
  1102. it('should extract simple import statement', () => {
  1103. const code = `import json`;
  1104. const result = extractFromSource('utils.py', code);
  1105. const importNode = result.nodes.find((n) => n.kind === 'import');
  1106. expect(importNode).toBeDefined();
  1107. expect(importNode?.name).toBe('json');
  1108. });
  1109. it('should extract from import statement', () => {
  1110. const code = `from os import path`;
  1111. const result = extractFromSource('utils.py', code);
  1112. const importNode = result.nodes.find((n) => n.kind === 'import');
  1113. expect(importNode).toBeDefined();
  1114. expect(importNode?.name).toBe('os');
  1115. expect(importNode?.signature).toContain('path');
  1116. });
  1117. it('should extract multiple imports from same module', () => {
  1118. const code = `from typing import List, Dict, Optional`;
  1119. const result = extractFromSource('types.py', code);
  1120. const importNode = result.nodes.find((n) => n.kind === 'import');
  1121. expect(importNode).toBeDefined();
  1122. expect(importNode?.name).toBe('typing');
  1123. expect(importNode?.signature).toContain('List');
  1124. expect(importNode?.signature).toContain('Dict');
  1125. });
  1126. it('should extract multiple import statements', () => {
  1127. const code = `
  1128. import os
  1129. import sys
  1130. `;
  1131. const result = extractFromSource('main.py', code);
  1132. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1133. expect(importNodes.length).toBe(2);
  1134. const names = importNodes.map((n) => n.name);
  1135. expect(names).toContain('os');
  1136. expect(names).toContain('sys');
  1137. });
  1138. it('should extract aliased import', () => {
  1139. const code = `import numpy as np`;
  1140. const result = extractFromSource('data.py', code);
  1141. const importNode = result.nodes.find((n) => n.kind === 'import');
  1142. expect(importNode).toBeDefined();
  1143. expect(importNode?.name).toBe('numpy');
  1144. expect(importNode?.signature).toContain('as np');
  1145. });
  1146. it('should extract relative import', () => {
  1147. const code = `from .utils import helper`;
  1148. const result = extractFromSource('module.py', code);
  1149. const importNode = result.nodes.find((n) => n.kind === 'import');
  1150. expect(importNode).toBeDefined();
  1151. expect(importNode?.name).toBe('.utils');
  1152. expect(importNode?.signature).toContain('helper');
  1153. });
  1154. it('should extract wildcard import', () => {
  1155. const code = `from typing import *`;
  1156. const result = extractFromSource('types.py', code);
  1157. const importNode = result.nodes.find((n) => n.kind === 'import');
  1158. expect(importNode).toBeDefined();
  1159. expect(importNode?.name).toBe('typing');
  1160. expect(importNode?.signature).toContain('*');
  1161. });
  1162. });
  1163. describe('Rust imports', () => {
  1164. it('should extract simple use declaration', () => {
  1165. const code = `use std::io;`;
  1166. const result = extractFromSource('main.rs', code);
  1167. const importNode = result.nodes.find((n) => n.kind === 'import');
  1168. expect(importNode).toBeDefined();
  1169. expect(importNode?.name).toBe('std');
  1170. expect(importNode?.signature).toBe('use std::io;');
  1171. });
  1172. it('should extract scoped use list', () => {
  1173. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1174. const result = extractFromSource('main.rs', code);
  1175. const importNode = result.nodes.find((n) => n.kind === 'import');
  1176. expect(importNode).toBeDefined();
  1177. expect(importNode?.name).toBe('std');
  1178. expect(importNode?.signature).toContain('ffi::OsStr');
  1179. expect(importNode?.signature).toContain('path::Path');
  1180. });
  1181. it('should extract crate imports', () => {
  1182. const code = `use crate::error::Error;`;
  1183. const result = extractFromSource('lib.rs', code);
  1184. const importNode = result.nodes.find((n) => n.kind === 'import');
  1185. expect(importNode).toBeDefined();
  1186. expect(importNode?.name).toBe('crate');
  1187. });
  1188. it('should extract super imports', () => {
  1189. const code = `use super::utils;`;
  1190. const result = extractFromSource('submod.rs', code);
  1191. const importNode = result.nodes.find((n) => n.kind === 'import');
  1192. expect(importNode).toBeDefined();
  1193. expect(importNode?.name).toBe('super');
  1194. });
  1195. it('should extract external crate imports', () => {
  1196. const code = `use serde::{Serialize, Deserialize};`;
  1197. const result = extractFromSource('types.rs', code);
  1198. const importNode = result.nodes.find((n) => n.kind === 'import');
  1199. expect(importNode).toBeDefined();
  1200. expect(importNode?.name).toBe('serde');
  1201. expect(importNode?.signature).toContain('Serialize');
  1202. expect(importNode?.signature).toContain('Deserialize');
  1203. });
  1204. });
  1205. describe('Go imports', () => {
  1206. it('should extract single import', () => {
  1207. const code = `
  1208. package main
  1209. import "fmt"
  1210. `;
  1211. const result = extractFromSource('main.go', code);
  1212. const importNode = result.nodes.find((n) => n.kind === 'import');
  1213. expect(importNode).toBeDefined();
  1214. expect(importNode?.name).toBe('fmt');
  1215. });
  1216. it('should extract grouped imports', () => {
  1217. const code = `
  1218. package main
  1219. import (
  1220. "fmt"
  1221. "os"
  1222. "encoding/json"
  1223. )
  1224. `;
  1225. const result = extractFromSource('main.go', code);
  1226. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1227. expect(importNodes.length).toBe(3);
  1228. const names = importNodes.map((n) => n.name);
  1229. expect(names).toContain('fmt');
  1230. expect(names).toContain('os');
  1231. expect(names).toContain('encoding/json');
  1232. });
  1233. it('should extract aliased import', () => {
  1234. const code = `
  1235. package main
  1236. import f "fmt"
  1237. `;
  1238. const result = extractFromSource('main.go', code);
  1239. const importNode = result.nodes.find((n) => n.kind === 'import');
  1240. expect(importNode).toBeDefined();
  1241. expect(importNode?.name).toBe('fmt');
  1242. expect(importNode?.signature).toContain('f');
  1243. });
  1244. it('should extract dot import', () => {
  1245. const code = `
  1246. package main
  1247. import . "math"
  1248. `;
  1249. const result = extractFromSource('main.go', code);
  1250. const importNode = result.nodes.find((n) => n.kind === 'import');
  1251. expect(importNode).toBeDefined();
  1252. expect(importNode?.name).toBe('math');
  1253. expect(importNode?.signature).toContain('.');
  1254. });
  1255. it('should extract blank import', () => {
  1256. const code = `
  1257. package main
  1258. import _ "github.com/go-sql-driver/mysql"
  1259. `;
  1260. const result = extractFromSource('main.go', code);
  1261. const importNode = result.nodes.find((n) => n.kind === 'import');
  1262. expect(importNode).toBeDefined();
  1263. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1264. expect(importNode?.signature).toContain('_');
  1265. });
  1266. });
  1267. describe('Swift imports', () => {
  1268. it('should extract simple import', () => {
  1269. const code = `import Foundation`;
  1270. const result = extractFromSource('main.swift', code);
  1271. const importNode = result.nodes.find((n) => n.kind === 'import');
  1272. expect(importNode).toBeDefined();
  1273. expect(importNode?.name).toBe('Foundation');
  1274. expect(importNode?.signature).toBe('import Foundation');
  1275. });
  1276. it('should extract @testable import', () => {
  1277. const code = `@testable import Alamofire`;
  1278. const result = extractFromSource('Tests.swift', code);
  1279. const importNode = result.nodes.find((n) => n.kind === 'import');
  1280. expect(importNode).toBeDefined();
  1281. expect(importNode?.name).toBe('Alamofire');
  1282. expect(importNode?.signature).toContain('@testable');
  1283. });
  1284. it('should extract @preconcurrency import', () => {
  1285. const code = `@preconcurrency import Security`;
  1286. const result = extractFromSource('Auth.swift', code);
  1287. const importNode = result.nodes.find((n) => n.kind === 'import');
  1288. expect(importNode).toBeDefined();
  1289. expect(importNode?.name).toBe('Security');
  1290. });
  1291. it('should extract multiple imports', () => {
  1292. const code = `
  1293. import Foundation
  1294. import UIKit
  1295. import Alamofire
  1296. `;
  1297. const result = extractFromSource('App.swift', code);
  1298. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1299. expect(importNodes.length).toBe(3);
  1300. const names = importNodes.map((n) => n.name);
  1301. expect(names).toContain('Foundation');
  1302. expect(names).toContain('UIKit');
  1303. expect(names).toContain('Alamofire');
  1304. });
  1305. });
  1306. describe('Kotlin imports', () => {
  1307. it('should extract simple import', () => {
  1308. const code = `import java.io.IOException`;
  1309. const result = extractFromSource('Main.kt', code);
  1310. const importNode = result.nodes.find((n) => n.kind === 'import');
  1311. expect(importNode).toBeDefined();
  1312. expect(importNode?.name).toBe('java.io.IOException');
  1313. expect(importNode?.signature).toBe('import java.io.IOException');
  1314. });
  1315. it('should extract aliased import', () => {
  1316. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1317. const result = extractFromSource('Utils.kt', code);
  1318. const importNode = result.nodes.find((n) => n.kind === 'import');
  1319. expect(importNode).toBeDefined();
  1320. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1321. expect(importNode?.signature).toContain('as RequestBuilder');
  1322. });
  1323. it('should extract wildcard import', () => {
  1324. const code = `import java.util.concurrent.TimeUnit.*`;
  1325. const result = extractFromSource('Time.kt', code);
  1326. const importNode = result.nodes.find((n) => n.kind === 'import');
  1327. expect(importNode).toBeDefined();
  1328. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1329. expect(importNode?.signature).toContain('.*');
  1330. });
  1331. it('should extract multiple imports', () => {
  1332. const code = `
  1333. import java.io.IOException
  1334. import kotlin.test.assertFailsWith
  1335. import okhttp3.OkHttpClient
  1336. `;
  1337. const result = extractFromSource('Test.kt', code);
  1338. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1339. expect(importNodes.length).toBe(3);
  1340. const names = importNodes.map((n) => n.name);
  1341. expect(names).toContain('java.io.IOException');
  1342. expect(names).toContain('kotlin.test.assertFailsWith');
  1343. expect(names).toContain('okhttp3.OkHttpClient');
  1344. });
  1345. });
  1346. describe('Java imports', () => {
  1347. it('should extract simple import', () => {
  1348. const code = `import java.util.List;`;
  1349. const result = extractFromSource('Main.java', code);
  1350. const importNode = result.nodes.find((n) => n.kind === 'import');
  1351. expect(importNode).toBeDefined();
  1352. expect(importNode?.name).toBe('java.util.List');
  1353. expect(importNode?.signature).toBe('import java.util.List;');
  1354. });
  1355. it('should extract static import', () => {
  1356. const code = `import static java.util.Collections.emptyList;`;
  1357. const result = extractFromSource('Utils.java', code);
  1358. const importNode = result.nodes.find((n) => n.kind === 'import');
  1359. expect(importNode).toBeDefined();
  1360. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1361. expect(importNode?.signature).toContain('static');
  1362. });
  1363. it('should extract wildcard import', () => {
  1364. const code = `import java.util.*;`;
  1365. const result = extractFromSource('App.java', code);
  1366. const importNode = result.nodes.find((n) => n.kind === 'import');
  1367. expect(importNode).toBeDefined();
  1368. expect(importNode?.name).toBe('java.util');
  1369. expect(importNode?.signature).toContain('.*');
  1370. });
  1371. it('should extract nested class import', () => {
  1372. const code = `import java.util.Map.Entry;`;
  1373. const result = extractFromSource('MapUtil.java', code);
  1374. const importNode = result.nodes.find((n) => n.kind === 'import');
  1375. expect(importNode).toBeDefined();
  1376. expect(importNode?.name).toBe('java.util.Map.Entry');
  1377. });
  1378. it('should extract multiple imports', () => {
  1379. const code = `
  1380. import java.util.List;
  1381. import java.util.Map;
  1382. import java.io.IOException;
  1383. `;
  1384. const result = extractFromSource('Service.java', code);
  1385. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1386. expect(importNodes.length).toBe(3);
  1387. const names = importNodes.map((n) => n.name);
  1388. expect(names).toContain('java.util.List');
  1389. expect(names).toContain('java.util.Map');
  1390. expect(names).toContain('java.io.IOException');
  1391. });
  1392. });
  1393. describe('C# imports', () => {
  1394. it('should extract simple using', () => {
  1395. const code = `using System;`;
  1396. const result = extractFromSource('Program.cs', code);
  1397. const importNode = result.nodes.find((n) => n.kind === 'import');
  1398. expect(importNode).toBeDefined();
  1399. expect(importNode?.name).toBe('System');
  1400. expect(importNode?.signature).toBe('using System;');
  1401. });
  1402. it('should extract qualified using', () => {
  1403. const code = `using System.Collections.Generic;`;
  1404. const result = extractFromSource('Utils.cs', code);
  1405. const importNode = result.nodes.find((n) => n.kind === 'import');
  1406. expect(importNode).toBeDefined();
  1407. expect(importNode?.name).toBe('System.Collections.Generic');
  1408. });
  1409. it('should extract static using', () => {
  1410. const code = `using static System.Console;`;
  1411. const result = extractFromSource('App.cs', code);
  1412. const importNode = result.nodes.find((n) => n.kind === 'import');
  1413. expect(importNode).toBeDefined();
  1414. expect(importNode?.name).toBe('System.Console');
  1415. expect(importNode?.signature).toContain('static');
  1416. });
  1417. it('should extract alias using', () => {
  1418. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1419. const result = extractFromSource('Types.cs', code);
  1420. const importNode = result.nodes.find((n) => n.kind === 'import');
  1421. expect(importNode).toBeDefined();
  1422. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1423. expect(importNode?.signature).toContain('MyList =');
  1424. });
  1425. it('should extract multiple usings', () => {
  1426. const code = `
  1427. using System;
  1428. using System.Threading.Tasks;
  1429. using Microsoft.Extensions.DependencyInjection;
  1430. `;
  1431. const result = extractFromSource('Service.cs', code);
  1432. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1433. expect(importNodes.length).toBe(3);
  1434. const names = importNodes.map((n) => n.name);
  1435. expect(names).toContain('System');
  1436. expect(names).toContain('System.Threading.Tasks');
  1437. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1438. });
  1439. });
  1440. describe('PHP imports', () => {
  1441. it('should extract simple use', () => {
  1442. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1443. const result = extractFromSource('Test.php', code);
  1444. const importNode = result.nodes.find((n) => n.kind === 'import');
  1445. expect(importNode).toBeDefined();
  1446. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1447. });
  1448. it('should extract aliased use', () => {
  1449. const code = `<?php use Mockery as m;`;
  1450. const result = extractFromSource('Test.php', code);
  1451. const importNode = result.nodes.find((n) => n.kind === 'import');
  1452. expect(importNode).toBeDefined();
  1453. expect(importNode?.name).toBe('Mockery');
  1454. expect(importNode?.signature).toContain('as m');
  1455. });
  1456. it('should extract function use', () => {
  1457. const code = `<?php use function Illuminate\\Support\\env;`;
  1458. const result = extractFromSource('helpers.php', code);
  1459. const importNode = result.nodes.find((n) => n.kind === 'import');
  1460. expect(importNode).toBeDefined();
  1461. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1462. expect(importNode?.signature).toContain('function');
  1463. });
  1464. it('should extract grouped use', () => {
  1465. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1466. const result = extractFromSource('Models.php', code);
  1467. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1468. expect(importNodes.length).toBe(2);
  1469. const names = importNodes.map((n) => n.name);
  1470. expect(names).toContain('Illuminate\\Database\\Model');
  1471. expect(names).toContain('Illuminate\\Database\\Builder');
  1472. });
  1473. it('should extract multiple uses', () => {
  1474. const code = `<?php
  1475. use Illuminate\\Support\\Collection;
  1476. use Illuminate\\Support\\Str;
  1477. use Closure;
  1478. `;
  1479. const result = extractFromSource('Service.php', code);
  1480. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1481. expect(importNodes.length).toBe(3);
  1482. const names = importNodes.map((n) => n.name);
  1483. expect(names).toContain('Illuminate\\Support\\Collection');
  1484. expect(names).toContain('Illuminate\\Support\\Str');
  1485. expect(names).toContain('Closure');
  1486. });
  1487. });
  1488. describe('Ruby imports', () => {
  1489. it('should extract require', () => {
  1490. const code = `require 'json'`;
  1491. const result = extractFromSource('app.rb', code);
  1492. const importNode = result.nodes.find((n) => n.kind === 'import');
  1493. expect(importNode).toBeDefined();
  1494. expect(importNode?.name).toBe('json');
  1495. expect(importNode?.signature).toBe("require 'json'");
  1496. });
  1497. it('should extract require with path', () => {
  1498. const code = `require 'active_support/core_ext/string'`;
  1499. const result = extractFromSource('config.rb', code);
  1500. const importNode = result.nodes.find((n) => n.kind === 'import');
  1501. expect(importNode).toBeDefined();
  1502. expect(importNode?.name).toBe('active_support/core_ext/string');
  1503. });
  1504. it('should extract require_relative', () => {
  1505. const code = `require_relative '../test_helper'`;
  1506. const result = extractFromSource('test/my_test.rb', code);
  1507. const importNode = result.nodes.find((n) => n.kind === 'import');
  1508. expect(importNode).toBeDefined();
  1509. expect(importNode?.name).toBe('../test_helper');
  1510. expect(importNode?.signature).toContain('require_relative');
  1511. });
  1512. it('should not extract non-require calls', () => {
  1513. const code = `puts 'hello'`;
  1514. const result = extractFromSource('app.rb', code);
  1515. const importNode = result.nodes.find((n) => n.kind === 'import');
  1516. expect(importNode).toBeUndefined();
  1517. });
  1518. it('should extract multiple requires', () => {
  1519. const code = `
  1520. require 'json'
  1521. require 'yaml'
  1522. require_relative 'helper'
  1523. `;
  1524. const result = extractFromSource('lib.rb', code);
  1525. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1526. expect(importNodes.length).toBe(3);
  1527. const names = importNodes.map((n) => n.name);
  1528. expect(names).toContain('json');
  1529. expect(names).toContain('yaml');
  1530. expect(names).toContain('helper');
  1531. });
  1532. });
  1533. describe('Ruby modules', () => {
  1534. it('should extract module as module node with containment', () => {
  1535. const code = `
  1536. module CachedCounting
  1537. def self.disable
  1538. @enabled = false
  1539. end
  1540. def perform_increment!(key, count)
  1541. write_cache!(key, count)
  1542. end
  1543. end
  1544. `;
  1545. const result = extractFromSource('concerns/cached_counting.rb', code);
  1546. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1547. expect(moduleNode).toBeDefined();
  1548. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1549. // Methods inside module should have module-qualified names
  1550. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1551. expect(disableMethod).toBeDefined();
  1552. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1553. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1554. expect(incrementMethod).toBeDefined();
  1555. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1556. // Containment edge from module to methods
  1557. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1558. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1559. });
  1560. it('should handle nested modules with classes', () => {
  1561. const code = `
  1562. module Discourse
  1563. module Auth
  1564. class AuthProvider
  1565. def authenticate(params)
  1566. validate(params)
  1567. end
  1568. end
  1569. end
  1570. end
  1571. `;
  1572. const result = extractFromSource('lib/auth.rb', code);
  1573. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1574. expect(discourseModule).toBeDefined();
  1575. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1576. expect(authModule).toBeDefined();
  1577. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1578. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1579. expect(authProvider).toBeDefined();
  1580. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1581. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1582. expect(authMethod).toBeDefined();
  1583. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1584. });
  1585. });
  1586. describe('C/C++ imports', () => {
  1587. it('should extract system include', () => {
  1588. const code = `#include <iostream>`;
  1589. const result = extractFromSource('main.cpp', code);
  1590. const importNode = result.nodes.find((n) => n.kind === 'import');
  1591. expect(importNode).toBeDefined();
  1592. expect(importNode?.name).toBe('iostream');
  1593. expect(importNode?.signature).toBe('#include <iostream>');
  1594. });
  1595. it('should extract system include with path', () => {
  1596. const code = `#include <nlohmann/json.hpp>`;
  1597. const result = extractFromSource('app.cpp', code);
  1598. const importNode = result.nodes.find((n) => n.kind === 'import');
  1599. expect(importNode).toBeDefined();
  1600. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1601. });
  1602. it('should extract local include', () => {
  1603. const code = `#include "myheader.h"`;
  1604. const result = extractFromSource('main.cpp', code);
  1605. const importNode = result.nodes.find((n) => n.kind === 'import');
  1606. expect(importNode).toBeDefined();
  1607. expect(importNode?.name).toBe('myheader.h');
  1608. });
  1609. it('should extract C header', () => {
  1610. const code = `#include <stdio.h>`;
  1611. const result = extractFromSource('main.c', code);
  1612. const importNode = result.nodes.find((n) => n.kind === 'import');
  1613. expect(importNode).toBeDefined();
  1614. expect(importNode?.name).toBe('stdio.h');
  1615. });
  1616. it('should extract multiple includes', () => {
  1617. const code = `
  1618. #include <iostream>
  1619. #include <vector>
  1620. #include "config.h"
  1621. `;
  1622. const result = extractFromSource('app.cpp', code);
  1623. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1624. expect(importNodes.length).toBe(3);
  1625. const names = importNodes.map((n) => n.name);
  1626. expect(names).toContain('iostream');
  1627. expect(names).toContain('vector');
  1628. expect(names).toContain('config.h');
  1629. });
  1630. });
  1631. describe('Dart imports', () => {
  1632. it('should extract dart: import', () => {
  1633. const code = `import 'dart:async';`;
  1634. const result = extractFromSource('main.dart', code);
  1635. const importNode = result.nodes.find((n) => n.kind === 'import');
  1636. expect(importNode).toBeDefined();
  1637. expect(importNode?.name).toBe('dart:async');
  1638. expect(importNode?.signature).toBe("import 'dart:async';");
  1639. });
  1640. it('should extract package import', () => {
  1641. const code = `import 'package:flutter/material.dart';`;
  1642. const result = extractFromSource('app.dart', code);
  1643. const importNode = result.nodes.find((n) => n.kind === 'import');
  1644. expect(importNode).toBeDefined();
  1645. expect(importNode?.name).toBe('package:flutter/material.dart');
  1646. });
  1647. it('should extract aliased import', () => {
  1648. const code = `import 'package:http/http.dart' as http;`;
  1649. const result = extractFromSource('api.dart', code);
  1650. const importNode = result.nodes.find((n) => n.kind === 'import');
  1651. expect(importNode).toBeDefined();
  1652. expect(importNode?.name).toBe('package:http/http.dart');
  1653. expect(importNode?.signature).toContain('as http');
  1654. });
  1655. it('should extract multiple imports', () => {
  1656. const code = `
  1657. import 'dart:async';
  1658. import 'dart:convert';
  1659. import 'package:flutter/material.dart';
  1660. `;
  1661. const result = extractFromSource('main.dart', code);
  1662. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1663. expect(importNodes.length).toBe(3);
  1664. const names = importNodes.map((n) => n.name);
  1665. expect(names).toContain('dart:async');
  1666. expect(names).toContain('dart:convert');
  1667. expect(names).toContain('package:flutter/material.dart');
  1668. });
  1669. it('should extract relative import', () => {
  1670. const code = `import '../utils/helpers.dart';`;
  1671. const result = extractFromSource('lib/main.dart', code);
  1672. const importNode = result.nodes.find((n) => n.kind === 'import');
  1673. expect(importNode).toBeDefined();
  1674. expect(importNode?.name).toBe('../utils/helpers.dart');
  1675. });
  1676. });
  1677. describe('Liquid imports', () => {
  1678. it('should extract render tag', () => {
  1679. const code = `{% render 'loading-spinner' %}`;
  1680. const result = extractFromSource('template.liquid', code);
  1681. const importNode = result.nodes.find((n) => n.kind === 'import');
  1682. expect(importNode).toBeDefined();
  1683. expect(importNode?.name).toBe('loading-spinner');
  1684. expect(importNode?.signature).toContain('render');
  1685. });
  1686. it('should extract section tag', () => {
  1687. const code = `{% section 'header' %}`;
  1688. const result = extractFromSource('layout/theme.liquid', code);
  1689. const importNode = result.nodes.find((n) => n.kind === 'import');
  1690. expect(importNode).toBeDefined();
  1691. expect(importNode?.name).toBe('header');
  1692. expect(importNode?.signature).toContain('section');
  1693. });
  1694. it('should extract include tag', () => {
  1695. const code = `{% include 'icon-cart' %}`;
  1696. const result = extractFromSource('snippets/header.liquid', code);
  1697. const importNode = result.nodes.find((n) => n.kind === 'import');
  1698. expect(importNode).toBeDefined();
  1699. expect(importNode?.name).toBe('icon-cart');
  1700. expect(importNode?.signature).toContain('include');
  1701. });
  1702. it('should extract render with whitespace control', () => {
  1703. const code = `{%- render 'price' -%}`;
  1704. const result = extractFromSource('snippets/product.liquid', code);
  1705. const importNode = result.nodes.find((n) => n.kind === 'import');
  1706. expect(importNode).toBeDefined();
  1707. expect(importNode?.name).toBe('price');
  1708. });
  1709. it('should extract multiple imports', () => {
  1710. const code = `
  1711. {% section 'header' %}
  1712. {% render 'loading-spinner' %}
  1713. {% render 'cart-drawer' %}
  1714. `;
  1715. const result = extractFromSource('layout/theme.liquid', code);
  1716. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1717. expect(importNodes.length).toBe(3);
  1718. const names = importNodes.map((n) => n.name);
  1719. expect(names).toContain('header');
  1720. expect(names).toContain('loading-spinner');
  1721. expect(names).toContain('cart-drawer');
  1722. });
  1723. });
  1724. });
  1725. // =============================================================================
  1726. // Pascal / Delphi Extraction
  1727. // =============================================================================
  1728. describe('Pascal / Delphi Extraction', () => {
  1729. describe('Language detection', () => {
  1730. it('should detect Pascal files', () => {
  1731. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  1732. expect(detectLanguage('App.dpr')).toBe('pascal');
  1733. expect(detectLanguage('Package.dpk')).toBe('pascal');
  1734. expect(detectLanguage('App.lpr')).toBe('pascal');
  1735. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  1736. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  1737. });
  1738. it('should report Pascal as supported', () => {
  1739. expect(isLanguageSupported('pascal')).toBe(true);
  1740. expect(getSupportedLanguages()).toContain('pascal');
  1741. });
  1742. });
  1743. describe('Unit extraction', () => {
  1744. it('should extract unit as module', () => {
  1745. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  1746. const result = extractFromSource('MyUnit.pas', code);
  1747. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1748. expect(moduleNode).toBeDefined();
  1749. expect(moduleNode?.name).toBe('MyUnit');
  1750. expect(moduleNode?.language).toBe('pascal');
  1751. });
  1752. it('should extract program as module', () => {
  1753. const code = `program MyApp;\nbegin\nend.`;
  1754. const result = extractFromSource('MyApp.dpr', code);
  1755. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1756. expect(moduleNode).toBeDefined();
  1757. expect(moduleNode?.name).toBe('MyApp');
  1758. });
  1759. it('should fallback to filename when module name is empty', () => {
  1760. // Some .dpr templates use "program;" without a name
  1761. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  1762. const result = extractFromSource('Console.dpr', code);
  1763. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1764. expect(moduleNode).toBeDefined();
  1765. expect(moduleNode?.name).toBe('Console');
  1766. });
  1767. });
  1768. describe('Uses clause (imports)', () => {
  1769. it('should extract uses as individual imports', () => {
  1770. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  1771. const result = extractFromSource('Test.pas', code);
  1772. const imports = result.nodes.filter((n) => n.kind === 'import');
  1773. expect(imports.length).toBe(2);
  1774. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  1775. expect(imports.map((n) => n.name)).toContain('System.Classes');
  1776. });
  1777. it('should create unresolved references for imports', () => {
  1778. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  1779. const result = extractFromSource('Test.pas', code);
  1780. const importRef = result.unresolvedReferences.find(
  1781. (r) => r.referenceKind === 'imports'
  1782. );
  1783. expect(importRef).toBeDefined();
  1784. expect(importRef?.referenceName).toBe('UAuth');
  1785. });
  1786. });
  1787. describe('Class extraction', () => {
  1788. it('should extract class declarations', () => {
  1789. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  1790. const result = extractFromSource('Test.pas', code);
  1791. const classNode = result.nodes.find((n) => n.kind === 'class');
  1792. expect(classNode).toBeDefined();
  1793. expect(classNode?.name).toBe('TMyClass');
  1794. });
  1795. it('should extract class with inheritance', () => {
  1796. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  1797. const result = extractFromSource('Test.pas', code);
  1798. const extendsRef = result.unresolvedReferences.find(
  1799. (r) => r.referenceKind === 'extends'
  1800. );
  1801. expect(extendsRef).toBeDefined();
  1802. expect(extendsRef?.referenceName).toBe('TParent');
  1803. });
  1804. it('should extract class with interface implementation', () => {
  1805. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  1806. const result = extractFromSource('Test.pas', code);
  1807. const extendsRef = result.unresolvedReferences.find(
  1808. (r) => r.referenceKind === 'extends'
  1809. );
  1810. const implementsRef = result.unresolvedReferences.find(
  1811. (r) => r.referenceKind === 'implements'
  1812. );
  1813. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1814. expect(implementsRef?.referenceName).toBe('ILogger');
  1815. });
  1816. });
  1817. describe('Record extraction', () => {
  1818. it('should extract records as class nodes', () => {
  1819. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  1820. const result = extractFromSource('Test.pas', code);
  1821. const classNode = result.nodes.find((n) => n.kind === 'class');
  1822. expect(classNode).toBeDefined();
  1823. expect(classNode?.name).toBe('TPoint');
  1824. const fields = result.nodes.filter((n) => n.kind === 'field');
  1825. expect(fields.length).toBe(2);
  1826. expect(fields.map((f) => f.name)).toContain('X');
  1827. expect(fields.map((f) => f.name)).toContain('Y');
  1828. });
  1829. });
  1830. describe('Interface extraction', () => {
  1831. it('should extract interface declarations', () => {
  1832. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  1833. const result = extractFromSource('Test.pas', code);
  1834. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1835. expect(ifaceNode).toBeDefined();
  1836. expect(ifaceNode?.name).toBe('ILogger');
  1837. });
  1838. });
  1839. describe('Method extraction', () => {
  1840. it('should extract methods with visibility', () => {
  1841. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n private\n FValue: Integer;\n public\n constructor Create;\n function GetValue: Integer;\n end;\nimplementation\nend.`;
  1842. const result = extractFromSource('Test.pas', code);
  1843. const methods = result.nodes.filter((n) => n.kind === 'method');
  1844. expect(methods.length).toBe(2);
  1845. const createMethod = methods.find((m) => m.name === 'Create');
  1846. expect(createMethod?.visibility).toBe('public');
  1847. const getValue = methods.find((m) => m.name === 'GetValue');
  1848. expect(getValue?.visibility).toBe('public');
  1849. const fields = result.nodes.filter((n) => n.kind === 'field');
  1850. const fValue = fields.find((f) => f.name === 'FValue');
  1851. expect(fValue?.visibility).toBe('private');
  1852. });
  1853. it('should detect static methods (class methods)', () => {
  1854. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  1855. const result = extractFromSource('Test.pas', code);
  1856. const methods = result.nodes.filter((n) => n.kind === 'method');
  1857. const staticMethod = methods.find((m) => m.name === 'Create');
  1858. expect(staticMethod?.isStatic).toBe(true);
  1859. });
  1860. });
  1861. describe('Enum extraction', () => {
  1862. it('should extract enums with members', () => {
  1863. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  1864. const result = extractFromSource('Test.pas', code);
  1865. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1866. expect(enumNode).toBeDefined();
  1867. expect(enumNode?.name).toBe('TColor');
  1868. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1869. expect(members.length).toBe(3);
  1870. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  1871. });
  1872. });
  1873. describe('Property extraction', () => {
  1874. it('should extract properties', () => {
  1875. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  1876. const result = extractFromSource('Test.pas', code);
  1877. const propNode = result.nodes.find((n) => n.kind === 'property');
  1878. expect(propNode).toBeDefined();
  1879. expect(propNode?.name).toBe('Name');
  1880. expect(propNode?.visibility).toBe('public');
  1881. });
  1882. });
  1883. describe('Constant extraction', () => {
  1884. it('should extract constants', () => {
  1885. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  1886. const result = extractFromSource('Test.pas', code);
  1887. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1888. expect(constants.length).toBe(2);
  1889. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  1890. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  1891. });
  1892. });
  1893. describe('Type alias extraction', () => {
  1894. it('should extract type aliases', () => {
  1895. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  1896. const result = extractFromSource('Test.pas', code);
  1897. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  1898. expect(aliasNode).toBeDefined();
  1899. expect(aliasNode?.name).toBe('TUserName');
  1900. });
  1901. });
  1902. describe('Call extraction', () => {
  1903. it('should extract calls from implementation bodies', () => {
  1904. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure DoWork;\n end;\nimplementation\nprocedure TObj.DoWork;\nbegin\n WriteLn('hello');\nend;\nend.`;
  1905. const result = extractFromSource('Test.pas', code);
  1906. const callRef = result.unresolvedReferences.find(
  1907. (r) => r.referenceKind === 'calls'
  1908. );
  1909. expect(callRef).toBeDefined();
  1910. expect(callRef?.referenceName).toBe('WriteLn');
  1911. });
  1912. });
  1913. describe('Containment edges', () => {
  1914. it('should create contains edges for class members', () => {
  1915. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  1916. const result = extractFromSource('Test.pas', code);
  1917. const classNode = result.nodes.find((n) => n.kind === 'class');
  1918. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1919. expect(classNode).toBeDefined();
  1920. expect(methodNode).toBeDefined();
  1921. const containsEdge = result.edges.find(
  1922. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  1923. );
  1924. expect(containsEdge).toBeDefined();
  1925. });
  1926. });
  1927. describe('Full fixture: UAuth.pas', () => {
  1928. const code = `unit UAuth;
  1929. interface
  1930. uses
  1931. System.SysUtils,
  1932. System.Classes;
  1933. type
  1934. ITokenValidator = interface
  1935. ['{11111111-1111-1111-1111-111111111111}']
  1936. function Validate(const AToken: string): Boolean;
  1937. end;
  1938. TAuthService = class(TInterfacedObject, ITokenValidator)
  1939. private
  1940. FToken: string;
  1941. FLoginCount: Integer;
  1942. procedure IncLoginCount;
  1943. protected
  1944. function GetToken: string;
  1945. public
  1946. constructor Create;
  1947. destructor Destroy; override;
  1948. function Validate(const AToken: string): Boolean;
  1949. function Login(const AUser, APass: string): string;
  1950. property Token: string read GetToken;
  1951. property LoginCount: Integer read FLoginCount;
  1952. end;
  1953. implementation
  1954. constructor TAuthService.Create;
  1955. begin
  1956. inherited Create;
  1957. FToken := '';
  1958. FLoginCount := 0;
  1959. end;
  1960. destructor TAuthService.Destroy;
  1961. begin
  1962. FToken := '';
  1963. inherited Destroy;
  1964. end;
  1965. procedure TAuthService.IncLoginCount;
  1966. begin
  1967. Inc(FLoginCount);
  1968. end;
  1969. function TAuthService.GetToken: string;
  1970. begin
  1971. Result := FToken;
  1972. end;
  1973. function TAuthService.Validate(const AToken: string): Boolean;
  1974. begin
  1975. Result := AToken <> '';
  1976. end;
  1977. function TAuthService.Login(const AUser, APass: string): string;
  1978. begin
  1979. IncLoginCount;
  1980. if Validate(AUser + ':' + APass) then
  1981. begin
  1982. FToken := AUser;
  1983. Result := 'ok';
  1984. end
  1985. else
  1986. Result := '';
  1987. end;
  1988. end.`;
  1989. it('should extract all expected nodes', () => {
  1990. const result = extractFromSource('UAuth.pas', code);
  1991. expect(result.errors).toHaveLength(0);
  1992. // Module
  1993. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1994. expect(moduleNode?.name).toBe('UAuth');
  1995. // Imports
  1996. const imports = result.nodes.filter((n) => n.kind === 'import');
  1997. expect(imports.length).toBe(2);
  1998. // Interface
  1999. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2000. expect(ifaceNode?.name).toBe('ITokenValidator');
  2001. // Class
  2002. const classNode = result.nodes.find((n) => n.kind === 'class');
  2003. expect(classNode?.name).toBe('TAuthService');
  2004. // Methods
  2005. const methods = result.nodes.filter((n) => n.kind === 'method');
  2006. expect(methods.length).toBeGreaterThanOrEqual(6);
  2007. expect(methods.map((m) => m.name)).toContain('Create');
  2008. expect(methods.map((m) => m.name)).toContain('Destroy');
  2009. expect(methods.map((m) => m.name)).toContain('Login');
  2010. // Fields
  2011. const fields = result.nodes.filter((n) => n.kind === 'field');
  2012. expect(fields.length).toBe(2);
  2013. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2014. // Properties
  2015. const props = result.nodes.filter((n) => n.kind === 'property');
  2016. expect(props.length).toBe(2);
  2017. expect(props.map((p) => p.name)).toContain('Token');
  2018. expect(props.map((p) => p.name)).toContain('LoginCount');
  2019. });
  2020. it('should extract inheritance and interface implementation', () => {
  2021. const result = extractFromSource('UAuth.pas', code);
  2022. const extendsRef = result.unresolvedReferences.find(
  2023. (r) => r.referenceKind === 'extends'
  2024. );
  2025. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2026. const implementsRef = result.unresolvedReferences.find(
  2027. (r) => r.referenceKind === 'implements'
  2028. );
  2029. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2030. });
  2031. it('should extract calls from implementation', () => {
  2032. const result = extractFromSource('UAuth.pas', code);
  2033. const callRefs = result.unresolvedReferences.filter(
  2034. (r) => r.referenceKind === 'calls'
  2035. );
  2036. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2037. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2038. });
  2039. });
  2040. describe('Full fixture: UTypes.pas', () => {
  2041. const code = `unit UTypes;
  2042. interface
  2043. uses
  2044. System.SysUtils;
  2045. const
  2046. C_MAX_RETRIES = 3;
  2047. C_DEFAULT_NAME = 'Guest';
  2048. type
  2049. TUserRole = (urAdmin, urEditor, urViewer);
  2050. TPoint2D = record
  2051. X: Double;
  2052. Y: Double;
  2053. end;
  2054. TUserName = string;
  2055. TUserInfo = class
  2056. public
  2057. type
  2058. TAddress = record
  2059. Street: string;
  2060. City: string;
  2061. Zip: string;
  2062. end;
  2063. private
  2064. FName: TUserName;
  2065. FRole: TUserRole;
  2066. FAddress: TAddress;
  2067. public
  2068. constructor Create(const AName: TUserName; ARole: TUserRole);
  2069. function GetDisplayName: string;
  2070. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2071. property Name: TUserName read FName write FName;
  2072. property Role: TUserRole read FRole;
  2073. property Address: TAddress read FAddress write FAddress;
  2074. end;
  2075. implementation
  2076. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2077. begin
  2078. FName := AName;
  2079. FRole := ARole;
  2080. end;
  2081. function TUserInfo.GetDisplayName: string;
  2082. begin
  2083. if FRole = urAdmin then
  2084. Result := '[Admin] ' + FName
  2085. else
  2086. Result := FName;
  2087. end;
  2088. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2089. begin
  2090. Result := TUserInfo.Create(AName, urAdmin);
  2091. end;
  2092. end.`;
  2093. it('should extract enums with members', () => {
  2094. const result = extractFromSource('UTypes.pas', code);
  2095. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2096. expect(enumNode?.name).toBe('TUserRole');
  2097. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2098. expect(members.length).toBe(3);
  2099. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2100. });
  2101. it('should extract constants', () => {
  2102. const result = extractFromSource('UTypes.pas', code);
  2103. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2104. expect(constants.length).toBe(2);
  2105. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2106. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2107. });
  2108. it('should extract type aliases', () => {
  2109. const result = extractFromSource('UTypes.pas', code);
  2110. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2111. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2112. });
  2113. it('should extract records as classes with fields', () => {
  2114. const result = extractFromSource('UTypes.pas', code);
  2115. const classes = result.nodes.filter((n) => n.kind === 'class');
  2116. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2117. // TPoint2D fields
  2118. const fields = result.nodes.filter((n) => n.kind === 'field');
  2119. expect(fields.map((f) => f.name)).toContain('X');
  2120. expect(fields.map((f) => f.name)).toContain('Y');
  2121. });
  2122. it('should extract static class methods', () => {
  2123. const result = extractFromSource('UTypes.pas', code);
  2124. const methods = result.nodes.filter((n) => n.kind === 'method');
  2125. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2126. expect(staticMethod).toBeDefined();
  2127. expect(staticMethod?.isStatic).toBe(true);
  2128. });
  2129. it('should extract nested types', () => {
  2130. const result = extractFromSource('UTypes.pas', code);
  2131. const classes = result.nodes.filter((n) => n.kind === 'class');
  2132. expect(classes.map((c) => c.name)).toContain('TAddress');
  2133. });
  2134. });
  2135. });
  2136. // =============================================================================
  2137. // DFM/FMX Extraction
  2138. // =============================================================================
  2139. describe('DFM/FMX Extraction', () => {
  2140. it('should extract components from DFM', () => {
  2141. const code = `object Form1: TForm1
  2142. Left = 0
  2143. Top = 0
  2144. Caption = 'My Form'
  2145. object Button1: TButton
  2146. Left = 10
  2147. Top = 10
  2148. Caption = 'Click Me'
  2149. end
  2150. end`;
  2151. const result = extractFromSource('Form1.dfm', code);
  2152. const components = result.nodes.filter((n) => n.kind === 'component');
  2153. expect(components.length).toBe(2);
  2154. expect(components.map((c) => c.name)).toContain('Form1');
  2155. expect(components.map((c) => c.name)).toContain('Button1');
  2156. const button = components.find((c) => c.name === 'Button1');
  2157. expect(button?.signature).toBe('TButton');
  2158. });
  2159. it('should extract nested component hierarchy', () => {
  2160. const code = `object Form1: TForm1
  2161. object Panel1: TPanel
  2162. object Label1: TLabel
  2163. Caption = 'Hello'
  2164. end
  2165. end
  2166. end`;
  2167. const result = extractFromSource('Form1.dfm', code);
  2168. const components = result.nodes.filter((n) => n.kind === 'component');
  2169. expect(components.length).toBe(3);
  2170. // Check nesting: Panel1 contains Label1
  2171. const panel = components.find((c) => c.name === 'Panel1');
  2172. const label = components.find((c) => c.name === 'Label1');
  2173. const containsEdge = result.edges.find(
  2174. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2175. );
  2176. expect(containsEdge).toBeDefined();
  2177. });
  2178. it('should extract event handler references', () => {
  2179. const code = `object Form1: TForm1
  2180. OnCreate = FormCreate
  2181. OnDestroy = FormDestroy
  2182. object Button1: TButton
  2183. OnClick = Button1Click
  2184. end
  2185. end`;
  2186. const result = extractFromSource('Form1.dfm', code);
  2187. const refs = result.unresolvedReferences;
  2188. expect(refs.length).toBe(3);
  2189. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2190. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2191. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2192. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2193. });
  2194. it('should handle multi-line properties', () => {
  2195. const code = `object Form1: TForm1
  2196. SQL.Strings = (
  2197. 'SELECT * FROM users'
  2198. 'WHERE active = 1')
  2199. object Button1: TButton
  2200. OnClick = Button1Click
  2201. end
  2202. end`;
  2203. const result = extractFromSource('Form1.dfm', code);
  2204. const components = result.nodes.filter((n) => n.kind === 'component');
  2205. expect(components.length).toBe(2);
  2206. const refs = result.unresolvedReferences;
  2207. expect(refs.length).toBe(1);
  2208. expect(refs[0]?.referenceName).toBe('Button1Click');
  2209. });
  2210. it('should handle inherited keyword', () => {
  2211. const code = `inherited Form1: TForm1
  2212. Caption = 'Inherited Form'
  2213. object Button1: TButton
  2214. OnClick = Button1Click
  2215. end
  2216. end`;
  2217. const result = extractFromSource('Form1.dfm', code);
  2218. const components = result.nodes.filter((n) => n.kind === 'component');
  2219. expect(components.length).toBe(2);
  2220. expect(components.map((c) => c.name)).toContain('Form1');
  2221. });
  2222. it('should handle item collection properties', () => {
  2223. const code = `object Form1: TForm1
  2224. object StatusBar1: TStatusBar
  2225. Panels = <
  2226. item
  2227. Width = 200
  2228. end
  2229. item
  2230. Width = 200
  2231. end>
  2232. end
  2233. end`;
  2234. const result = extractFromSource('Form1.dfm', code);
  2235. const components = result.nodes.filter((n) => n.kind === 'component');
  2236. expect(components.length).toBe(2);
  2237. });
  2238. describe('Full fixture: MainForm.dfm', () => {
  2239. const code = `object frmMain: TfrmMain
  2240. Left = 0
  2241. Top = 0
  2242. Caption = 'CodeGraph DFM Fixture'
  2243. ClientHeight = 480
  2244. ClientWidth = 640
  2245. OnCreate = FormCreate
  2246. OnDestroy = FormDestroy
  2247. object pnlTop: TPanel
  2248. Left = 0
  2249. Top = 0
  2250. Width = 640
  2251. Height = 50
  2252. object lblTitle: TLabel
  2253. Left = 16
  2254. Top = 16
  2255. Caption = 'Authentication Service'
  2256. end
  2257. object btnLogin: TButton
  2258. Left = 540
  2259. Top = 12
  2260. OnClick = btnLoginClick
  2261. end
  2262. end
  2263. object pnlContent: TPanel
  2264. Left = 0
  2265. Top = 50
  2266. object edtUsername: TEdit
  2267. Left = 16
  2268. Top = 16
  2269. OnChange = edtUsernameChange
  2270. end
  2271. object edtPassword: TEdit
  2272. Left = 16
  2273. Top = 48
  2274. OnKeyPress = edtPasswordKeyPress
  2275. end
  2276. object mmoLog: TMemo
  2277. Left = 16
  2278. Top = 88
  2279. end
  2280. end
  2281. object pnlStatus: TStatusBar
  2282. Left = 0
  2283. Top = 440
  2284. Panels = <
  2285. item
  2286. Width = 200
  2287. end
  2288. item
  2289. Width = 200
  2290. end>
  2291. end
  2292. end`;
  2293. it('should extract all components', () => {
  2294. const result = extractFromSource('MainForm.dfm', code);
  2295. const components = result.nodes.filter((n) => n.kind === 'component');
  2296. expect(components.length).toBe(9);
  2297. expect(components.map((c) => c.name)).toEqual(
  2298. expect.arrayContaining([
  2299. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2300. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2301. ])
  2302. );
  2303. });
  2304. it('should extract all event handlers', () => {
  2305. const result = extractFromSource('MainForm.dfm', code);
  2306. const refs = result.unresolvedReferences;
  2307. expect(refs.length).toBe(5);
  2308. expect(refs.map((r) => r.referenceName)).toEqual(
  2309. expect.arrayContaining([
  2310. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2311. 'edtUsernameChange', 'edtPasswordKeyPress',
  2312. ])
  2313. );
  2314. });
  2315. });
  2316. });
  2317. describe('Full Indexing', () => {
  2318. let tempDir: string;
  2319. beforeEach(() => {
  2320. tempDir = createTempDir();
  2321. });
  2322. afterEach(() => {
  2323. cleanupTempDir(tempDir);
  2324. });
  2325. it('should index a TypeScript file', async () => {
  2326. // Create test file
  2327. const srcDir = path.join(tempDir, 'src');
  2328. fs.mkdirSync(srcDir);
  2329. fs.writeFileSync(
  2330. path.join(srcDir, 'utils.ts'),
  2331. `
  2332. export function add(a: number, b: number): number {
  2333. return a + b;
  2334. }
  2335. export function multiply(a: number, b: number): number {
  2336. return a * b;
  2337. }
  2338. `
  2339. );
  2340. // Initialize and index
  2341. const cg = CodeGraph.initSync(tempDir);
  2342. const result = await cg.indexAll();
  2343. expect(result.success).toBe(true);
  2344. expect(result.filesIndexed).toBe(1);
  2345. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2346. // Check nodes were stored
  2347. const nodes = cg.getNodesInFile('src/utils.ts');
  2348. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2349. const addFunc = nodes.find((n) => n.name === 'add');
  2350. expect(addFunc).toBeDefined();
  2351. expect(addFunc?.kind).toBe('function');
  2352. cg.close();
  2353. });
  2354. it('should index multiple files', async () => {
  2355. // Create test files
  2356. const srcDir = path.join(tempDir, 'src');
  2357. fs.mkdirSync(srcDir);
  2358. fs.writeFileSync(
  2359. path.join(srcDir, 'math.ts'),
  2360. `export function add(a: number, b: number) { return a + b; }`
  2361. );
  2362. fs.writeFileSync(
  2363. path.join(srcDir, 'string.ts'),
  2364. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2365. );
  2366. // Initialize and index
  2367. const cg = CodeGraph.initSync(tempDir);
  2368. const result = await cg.indexAll();
  2369. expect(result.success).toBe(true);
  2370. expect(result.filesIndexed).toBe(2);
  2371. const files = cg.getFiles();
  2372. expect(files.length).toBe(2);
  2373. cg.close();
  2374. });
  2375. it('should track file hashes for incremental updates', async () => {
  2376. // Create initial file
  2377. const srcDir = path.join(tempDir, 'src');
  2378. fs.mkdirSync(srcDir);
  2379. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2380. // Initialize and index
  2381. const cg = CodeGraph.initSync(tempDir);
  2382. await cg.indexAll();
  2383. // Check file is tracked
  2384. const file = cg.getFile('src/main.ts');
  2385. expect(file).toBeDefined();
  2386. expect(file?.contentHash).toBeDefined();
  2387. // Modify file
  2388. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2389. // Check for changes
  2390. const changes = cg.getChangedFiles();
  2391. expect(changes.modified).toContain('src/main.ts');
  2392. cg.close();
  2393. });
  2394. it('should sync and detect changes', async () => {
  2395. // Create initial file
  2396. const srcDir = path.join(tempDir, 'src');
  2397. fs.mkdirSync(srcDir);
  2398. fs.writeFileSync(
  2399. path.join(srcDir, 'main.ts'),
  2400. `export function original() { return 1; }`
  2401. );
  2402. // Initialize and index
  2403. const cg = CodeGraph.initSync(tempDir);
  2404. await cg.indexAll();
  2405. const initialNodes = cg.getNodesInFile('src/main.ts');
  2406. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2407. // Modify file
  2408. fs.writeFileSync(
  2409. path.join(srcDir, 'main.ts'),
  2410. `export function updated() { return 2; }`
  2411. );
  2412. // Sync
  2413. const syncResult = await cg.sync();
  2414. expect(syncResult.filesModified).toBe(1);
  2415. // Check nodes were updated
  2416. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2417. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2418. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2419. cg.close();
  2420. });
  2421. });
  2422. describe('Path Normalization', () => {
  2423. it('should convert backslashes to forward slashes', () => {
  2424. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  2425. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  2426. });
  2427. it('should leave forward-slash paths unchanged', () => {
  2428. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  2429. });
  2430. it('should handle empty string', () => {
  2431. expect(normalizePath('')).toBe('');
  2432. });
  2433. });
  2434. describe('Directory Exclusion', () => {
  2435. let tempDir: string;
  2436. beforeEach(() => {
  2437. tempDir = createTempDir();
  2438. });
  2439. afterEach(() => {
  2440. cleanupTempDir(tempDir);
  2441. });
  2442. it('should exclude node_modules directories', () => {
  2443. // Create structure: src/index.ts + node_modules/pkg/index.js
  2444. const srcDir = path.join(tempDir, 'src');
  2445. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  2446. fs.mkdirSync(srcDir, { recursive: true });
  2447. fs.mkdirSync(nmDir, { recursive: true });
  2448. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2449. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2450. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2451. const files = scanDirectory(tempDir, config);
  2452. expect(files).toContain('src/index.ts');
  2453. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2454. });
  2455. it('should exclude nested node_modules directories', () => {
  2456. // Create structure: packages/app/node_modules/pkg/index.js
  2457. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  2458. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  2459. fs.mkdirSync(srcDir, { recursive: true });
  2460. fs.mkdirSync(nmDir, { recursive: true });
  2461. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2462. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2463. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2464. const files = scanDirectory(tempDir, config);
  2465. expect(files).toContain('packages/app/src/index.ts');
  2466. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2467. });
  2468. it('should exclude .git directories', () => {
  2469. const srcDir = path.join(tempDir, 'src');
  2470. const gitDir = path.join(tempDir, '.git', 'objects');
  2471. fs.mkdirSync(srcDir, { recursive: true });
  2472. fs.mkdirSync(gitDir, { recursive: true });
  2473. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2474. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  2475. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2476. const files = scanDirectory(tempDir, config);
  2477. expect(files).toContain('src/index.ts');
  2478. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  2479. });
  2480. it('should return forward-slash paths on all platforms', () => {
  2481. const srcDir = path.join(tempDir, 'src', 'components');
  2482. fs.mkdirSync(srcDir, { recursive: true });
  2483. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  2484. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2485. const files = scanDirectory(tempDir, config);
  2486. expect(files.length).toBe(1);
  2487. expect(files[0]).toBe('src/components/Button.tsx');
  2488. expect(files[0]).not.toContain('\\');
  2489. });
  2490. it('should respect .codegraphignore marker', () => {
  2491. const srcDir = path.join(tempDir, 'src');
  2492. const vendorDir = path.join(tempDir, 'vendor');
  2493. fs.mkdirSync(srcDir, { recursive: true });
  2494. fs.mkdirSync(vendorDir, { recursive: true });
  2495. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2496. fs.writeFileSync(path.join(vendorDir, 'lib.ts'), 'export const y = 2;');
  2497. fs.writeFileSync(path.join(vendorDir, '.codegraphignore'), '');
  2498. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2499. const files = scanDirectory(tempDir, config);
  2500. expect(files).toContain('src/index.ts');
  2501. expect(files.every((f) => !f.includes('vendor'))).toBe(true);
  2502. });
  2503. });