extraction.test.ts 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807
  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. });
  554. describe('Java Extraction', () => {
  555. it('should extract class declarations', () => {
  556. const code = `
  557. public class UserService {
  558. private final UserRepository repository;
  559. public UserService(UserRepository repository) {
  560. this.repository = repository;
  561. }
  562. public User getUser(String id) {
  563. return repository.findById(id);
  564. }
  565. }
  566. `;
  567. const result = extractFromSource('UserService.java', code);
  568. const classNode = result.nodes.find((n) => n.kind === 'class');
  569. expect(classNode).toBeDefined();
  570. expect(classNode?.name).toBe('UserService');
  571. expect(classNode?.visibility).toBe('public');
  572. });
  573. it('should extract method declarations', () => {
  574. const code = `
  575. public class Calculator {
  576. public static int add(int a, int b) {
  577. return a + b;
  578. }
  579. }
  580. `;
  581. const result = extractFromSource('Calculator.java', code);
  582. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  583. expect(methodNode).toBeDefined();
  584. expect(methodNode?.isStatic).toBe(true);
  585. });
  586. });
  587. describe('C# Extraction', () => {
  588. it('should extract class declarations', () => {
  589. const code = `
  590. public class OrderService
  591. {
  592. private readonly IOrderRepository _repository;
  593. public OrderService(IOrderRepository repository)
  594. {
  595. _repository = repository;
  596. }
  597. public async Task<Order> GetOrderAsync(string id)
  598. {
  599. return await _repository.FindByIdAsync(id);
  600. }
  601. }
  602. `;
  603. const result = extractFromSource('OrderService.cs', code);
  604. const classNode = result.nodes.find((n) => n.kind === 'class');
  605. expect(classNode).toBeDefined();
  606. expect(classNode?.name).toBe('OrderService');
  607. expect(classNode?.visibility).toBe('public');
  608. });
  609. });
  610. describe('PHP Extraction', () => {
  611. it('should extract class declarations', () => {
  612. const code = `<?php
  613. class UserController
  614. {
  615. private UserService $userService;
  616. public function __construct(UserService $userService)
  617. {
  618. $this->userService = $userService;
  619. }
  620. public function show(string $id): User
  621. {
  622. return $this->userService->find($id);
  623. }
  624. }
  625. `;
  626. const result = extractFromSource('UserController.php', code);
  627. const classNode = result.nodes.find((n) => n.kind === 'class');
  628. expect(classNode).toBeDefined();
  629. expect(classNode?.name).toBe('UserController');
  630. });
  631. });
  632. describe('Swift Extraction', () => {
  633. it('should extract class declarations', () => {
  634. const code = `
  635. public class NetworkManager {
  636. private let session: URLSession
  637. public init(session: URLSession = .shared) {
  638. self.session = session
  639. }
  640. public func fetchData(from url: URL) async throws -> Data {
  641. let (data, _) = try await session.data(from: url)
  642. return data
  643. }
  644. }
  645. `;
  646. const result = extractFromSource('NetworkManager.swift', code);
  647. const classNode = result.nodes.find((n) => n.kind === 'class');
  648. expect(classNode).toBeDefined();
  649. expect(classNode?.name).toBe('NetworkManager');
  650. });
  651. it('should extract function declarations', () => {
  652. const code = `
  653. func calculateSum(_ numbers: [Int]) -> Int {
  654. return numbers.reduce(0, +)
  655. }
  656. public func formatCurrency(amount: Double) -> String {
  657. return String(format: "$%.2f", amount)
  658. }
  659. `;
  660. const result = extractFromSource('utils.swift', code);
  661. const functions = result.nodes.filter((n) => n.kind === 'function');
  662. expect(functions.length).toBeGreaterThanOrEqual(1);
  663. });
  664. it('should extract struct declarations', () => {
  665. const code = `
  666. public struct User {
  667. let id: UUID
  668. var name: String
  669. var email: String
  670. func displayName() -> String {
  671. return name
  672. }
  673. }
  674. `;
  675. const result = extractFromSource('User.swift', code);
  676. const structNode = result.nodes.find((n) => n.kind === 'struct');
  677. expect(structNode).toBeDefined();
  678. expect(structNode?.name).toBe('User');
  679. });
  680. it('should extract protocol declarations', () => {
  681. const code = `
  682. public protocol Repository {
  683. associatedtype Entity
  684. func find(id: String) async throws -> Entity?
  685. func save(_ entity: Entity) async throws
  686. }
  687. `;
  688. const result = extractFromSource('Repository.swift', code);
  689. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  690. expect(protocolNode).toBeDefined();
  691. expect(protocolNode?.name).toBe('Repository');
  692. });
  693. it('should extract class inheritance and protocol conformance', () => {
  694. const code = `
  695. class DataRequest: Request {
  696. func validate() {}
  697. }
  698. class UploadRequest: DataRequest, Sendable {
  699. func upload() {}
  700. }
  701. enum AFError: Error {
  702. case invalidURL
  703. }
  704. struct HTTPMethod: RawRepresentable {
  705. let rawValue: String
  706. }
  707. protocol UploadConvertible: URLRequestConvertible {
  708. func asURLRequest() throws -> URLRequest
  709. }
  710. `;
  711. const result = extractFromSource('Inheritance.swift', code);
  712. const extendsRefs = result.unresolvedReferences.filter(
  713. (r) => r.referenceKind === 'extends'
  714. );
  715. // DataRequest extends Request
  716. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  717. // UploadRequest extends DataRequest and Sendable
  718. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  719. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  720. // AFError extends Error
  721. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  722. // HTTPMethod extends RawRepresentable
  723. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  724. // UploadConvertible extends URLRequestConvertible
  725. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  726. });
  727. });
  728. describe('Kotlin Extraction', () => {
  729. it('should extract class declarations', () => {
  730. const code = `
  731. class UserRepository(private val database: Database) {
  732. fun findById(id: String): User? {
  733. return database.query("SELECT * FROM users WHERE id = ?", id)
  734. }
  735. suspend fun save(user: User) {
  736. database.insert(user)
  737. }
  738. }
  739. `;
  740. const result = extractFromSource('UserRepository.kt', code);
  741. const classNode = result.nodes.find((n) => n.kind === 'class');
  742. expect(classNode).toBeDefined();
  743. expect(classNode?.name).toBe('UserRepository');
  744. });
  745. it('should extract function declarations', () => {
  746. const code = `
  747. fun calculateTotal(items: List<Item>): Double {
  748. return items.sumOf { it.price }
  749. }
  750. suspend fun fetchUserData(userId: String): User {
  751. return api.getUser(userId)
  752. }
  753. `;
  754. const result = extractFromSource('utils.kt', code);
  755. const functions = result.nodes.filter((n) => n.kind === 'function');
  756. expect(functions.length).toBeGreaterThanOrEqual(1);
  757. });
  758. it('should detect suspend functions as async', () => {
  759. const code = `
  760. suspend fun loadData(): List<String> {
  761. delay(1000)
  762. return listOf("a", "b", "c")
  763. }
  764. `;
  765. const result = extractFromSource('loader.kt', code);
  766. const funcNode = result.nodes.find((n) => n.kind === 'function');
  767. expect(funcNode).toBeDefined();
  768. expect(funcNode?.isAsync).toBe(true);
  769. });
  770. });
  771. describe('Dart Extraction', () => {
  772. it('should extract class declarations', () => {
  773. const code = `
  774. class UserService {
  775. final Database _db;
  776. Future<User> findById(String id) async {
  777. return await _db.query(id);
  778. }
  779. void _privateMethod() {}
  780. }
  781. `;
  782. const result = extractFromSource('service.dart', code);
  783. const classNode = result.nodes.find((n) => n.kind === 'class');
  784. expect(classNode).toBeDefined();
  785. expect(classNode?.name).toBe('UserService');
  786. expect(classNode?.visibility).toBe('public');
  787. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  788. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  789. const findById = methodNodes.find((m) => m.name === 'findById');
  790. expect(findById).toBeDefined();
  791. expect(findById?.isAsync).toBe(true);
  792. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  793. expect(privateMethod).toBeDefined();
  794. expect(privateMethod?.visibility).toBe('private');
  795. });
  796. it('should extract top-level function declarations', () => {
  797. const code = `
  798. void topLevelFunction(String name) {
  799. print(name);
  800. }
  801. `;
  802. const result = extractFromSource('utils.dart', code);
  803. const funcNode = result.nodes.find((n) => n.kind === 'function');
  804. expect(funcNode).toBeDefined();
  805. expect(funcNode?.name).toBe('topLevelFunction');
  806. expect(funcNode?.language).toBe('dart');
  807. });
  808. it('should extract enum declarations', () => {
  809. const code = `
  810. enum Status { active, inactive, pending }
  811. `;
  812. const result = extractFromSource('models.dart', code);
  813. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  814. expect(enumNode).toBeDefined();
  815. expect(enumNode?.name).toBe('Status');
  816. });
  817. it('should extract mixin declarations', () => {
  818. const code = `
  819. mixin LoggerMixin {
  820. void log(String message) {}
  821. }
  822. `;
  823. const result = extractFromSource('mixins.dart', code);
  824. const classNode = result.nodes.find((n) => n.kind === 'class');
  825. expect(classNode).toBeDefined();
  826. expect(classNode?.name).toBe('LoggerMixin');
  827. const methodNode = result.nodes.find((n) => n.kind === 'method');
  828. expect(methodNode).toBeDefined();
  829. expect(methodNode?.name).toBe('log');
  830. });
  831. it('should extract extension declarations', () => {
  832. const code = `
  833. extension StringExt on String {
  834. bool get isBlank => trim().isEmpty;
  835. }
  836. `;
  837. const result = extractFromSource('extensions.dart', code);
  838. const classNode = result.nodes.find((n) => n.kind === 'class');
  839. expect(classNode).toBeDefined();
  840. expect(classNode?.name).toBe('StringExt');
  841. });
  842. it('should detect static methods', () => {
  843. const code = `
  844. class Utils {
  845. static void doWork() {}
  846. }
  847. `;
  848. const result = extractFromSource('utils.dart', code);
  849. const methodNode = result.nodes.find((n) => n.kind === 'method');
  850. expect(methodNode).toBeDefined();
  851. expect(methodNode?.name).toBe('doWork');
  852. expect(methodNode?.isStatic).toBe(true);
  853. });
  854. it('should detect async functions', () => {
  855. const code = `
  856. Future<String> fetchData() async {
  857. return await http.get('/data');
  858. }
  859. `;
  860. const result = extractFromSource('api.dart', code);
  861. const funcNode = result.nodes.find((n) => n.kind === 'function');
  862. expect(funcNode).toBeDefined();
  863. expect(funcNode?.name).toBe('fetchData');
  864. expect(funcNode?.isAsync).toBe(true);
  865. });
  866. it('should detect private visibility via underscore convention', () => {
  867. const code = `
  868. void _privateHelper() {}
  869. void publicFunction() {}
  870. `;
  871. const result = extractFromSource('helpers.dart', code);
  872. const functions = result.nodes.filter((n) => n.kind === 'function');
  873. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  874. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  875. expect(privateFunc?.visibility).toBe('private');
  876. expect(publicFunc?.visibility).toBe('public');
  877. });
  878. });
  879. describe('Import Extraction', () => {
  880. describe('TypeScript/JavaScript imports', () => {
  881. it('should extract default imports', () => {
  882. const code = `import React from 'react';`;
  883. const result = extractFromSource('app.tsx', code);
  884. const importNode = result.nodes.find((n) => n.kind === 'import');
  885. expect(importNode).toBeDefined();
  886. expect(importNode?.name).toBe('react');
  887. expect(importNode?.signature).toBe("import React from 'react';");
  888. });
  889. it('should extract named imports', () => {
  890. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  891. const result = extractFromSource('icons.tsx', code);
  892. const importNode = result.nodes.find((n) => n.kind === 'import');
  893. expect(importNode).toBeDefined();
  894. expect(importNode?.name).toBe('@phosphor-icons/react');
  895. expect(importNode?.signature).toContain('Bug');
  896. expect(importNode?.signature).toContain('Database');
  897. });
  898. it('should extract namespace imports', () => {
  899. const code = `import * as Icons from '@phosphor-icons/react';`;
  900. const result = extractFromSource('icons.tsx', code);
  901. const importNode = result.nodes.find((n) => n.kind === 'import');
  902. expect(importNode).toBeDefined();
  903. expect(importNode?.name).toBe('@phosphor-icons/react');
  904. expect(importNode?.signature).toContain('* as Icons');
  905. });
  906. it('should extract side-effect imports', () => {
  907. const code = `import './styles.css';`;
  908. const result = extractFromSource('app.tsx', code);
  909. const importNode = result.nodes.find((n) => n.kind === 'import');
  910. expect(importNode).toBeDefined();
  911. expect(importNode?.name).toBe('./styles.css');
  912. });
  913. it('should extract mixed imports (default + named)', () => {
  914. const code = `import React, { useState, useEffect } from 'react';`;
  915. const result = extractFromSource('app.tsx', code);
  916. const importNode = result.nodes.find((n) => n.kind === 'import');
  917. expect(importNode).toBeDefined();
  918. expect(importNode?.name).toBe('react');
  919. expect(importNode?.signature).toContain('React');
  920. expect(importNode?.signature).toContain('useState');
  921. expect(importNode?.signature).toContain('useEffect');
  922. });
  923. it('should extract multiple import statements', () => {
  924. const code = `
  925. import React from 'react';
  926. import { Button } from './components';
  927. import './styles.css';
  928. `;
  929. const result = extractFromSource('app.tsx', code);
  930. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  931. expect(importNodes.length).toBe(3);
  932. const names = importNodes.map((n) => n.name);
  933. expect(names).toContain('react');
  934. expect(names).toContain('./components');
  935. expect(names).toContain('./styles.css');
  936. });
  937. it('should extract type imports', () => {
  938. const code = `import type { FC, ReactNode } from 'react';`;
  939. const result = extractFromSource('types.ts', code);
  940. const importNode = result.nodes.find((n) => n.kind === 'import');
  941. expect(importNode).toBeDefined();
  942. expect(importNode?.name).toBe('react');
  943. expect(importNode?.signature).toContain('type');
  944. expect(importNode?.signature).toContain('FC');
  945. });
  946. it('should extract aliased named imports', () => {
  947. const code = `import { useState as useStateAlias } from 'react';`;
  948. const result = extractFromSource('hooks.ts', code);
  949. const importNode = result.nodes.find((n) => n.kind === 'import');
  950. expect(importNode).toBeDefined();
  951. expect(importNode?.name).toBe('react');
  952. expect(importNode?.signature).toContain('useState');
  953. expect(importNode?.signature).toContain('useStateAlias');
  954. });
  955. it('should extract relative path imports', () => {
  956. const code = `import { helper } from '../utils/helper';`;
  957. const result = extractFromSource('components/Button.tsx', code);
  958. const importNode = result.nodes.find((n) => n.kind === 'import');
  959. expect(importNode).toBeDefined();
  960. expect(importNode?.name).toBe('../utils/helper');
  961. expect(importNode?.signature).toContain('helper');
  962. });
  963. });
  964. describe('Python imports', () => {
  965. it('should extract simple import statement', () => {
  966. const code = `import json`;
  967. const result = extractFromSource('utils.py', code);
  968. const importNode = result.nodes.find((n) => n.kind === 'import');
  969. expect(importNode).toBeDefined();
  970. expect(importNode?.name).toBe('json');
  971. });
  972. it('should extract from import statement', () => {
  973. const code = `from os import path`;
  974. const result = extractFromSource('utils.py', code);
  975. const importNode = result.nodes.find((n) => n.kind === 'import');
  976. expect(importNode).toBeDefined();
  977. expect(importNode?.name).toBe('os');
  978. expect(importNode?.signature).toContain('path');
  979. });
  980. it('should extract multiple imports from same module', () => {
  981. const code = `from typing import List, Dict, Optional`;
  982. const result = extractFromSource('types.py', code);
  983. const importNode = result.nodes.find((n) => n.kind === 'import');
  984. expect(importNode).toBeDefined();
  985. expect(importNode?.name).toBe('typing');
  986. expect(importNode?.signature).toContain('List');
  987. expect(importNode?.signature).toContain('Dict');
  988. });
  989. it('should extract multiple import statements', () => {
  990. const code = `
  991. import os
  992. import sys
  993. `;
  994. const result = extractFromSource('main.py', code);
  995. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  996. expect(importNodes.length).toBe(2);
  997. const names = importNodes.map((n) => n.name);
  998. expect(names).toContain('os');
  999. expect(names).toContain('sys');
  1000. });
  1001. it('should extract aliased import', () => {
  1002. const code = `import numpy as np`;
  1003. const result = extractFromSource('data.py', code);
  1004. const importNode = result.nodes.find((n) => n.kind === 'import');
  1005. expect(importNode).toBeDefined();
  1006. expect(importNode?.name).toBe('numpy');
  1007. expect(importNode?.signature).toContain('as np');
  1008. });
  1009. it('should extract relative import', () => {
  1010. const code = `from .utils import helper`;
  1011. const result = extractFromSource('module.py', code);
  1012. const importNode = result.nodes.find((n) => n.kind === 'import');
  1013. expect(importNode).toBeDefined();
  1014. expect(importNode?.name).toBe('.utils');
  1015. expect(importNode?.signature).toContain('helper');
  1016. });
  1017. it('should extract wildcard import', () => {
  1018. const code = `from typing import *`;
  1019. const result = extractFromSource('types.py', code);
  1020. const importNode = result.nodes.find((n) => n.kind === 'import');
  1021. expect(importNode).toBeDefined();
  1022. expect(importNode?.name).toBe('typing');
  1023. expect(importNode?.signature).toContain('*');
  1024. });
  1025. });
  1026. describe('Rust imports', () => {
  1027. it('should extract simple use declaration', () => {
  1028. const code = `use std::io;`;
  1029. const result = extractFromSource('main.rs', code);
  1030. const importNode = result.nodes.find((n) => n.kind === 'import');
  1031. expect(importNode).toBeDefined();
  1032. expect(importNode?.name).toBe('std');
  1033. expect(importNode?.signature).toBe('use std::io;');
  1034. });
  1035. it('should extract scoped use list', () => {
  1036. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1037. const result = extractFromSource('main.rs', code);
  1038. const importNode = result.nodes.find((n) => n.kind === 'import');
  1039. expect(importNode).toBeDefined();
  1040. expect(importNode?.name).toBe('std');
  1041. expect(importNode?.signature).toContain('ffi::OsStr');
  1042. expect(importNode?.signature).toContain('path::Path');
  1043. });
  1044. it('should extract crate imports', () => {
  1045. const code = `use crate::error::Error;`;
  1046. const result = extractFromSource('lib.rs', code);
  1047. const importNode = result.nodes.find((n) => n.kind === 'import');
  1048. expect(importNode).toBeDefined();
  1049. expect(importNode?.name).toBe('crate');
  1050. });
  1051. it('should extract super imports', () => {
  1052. const code = `use super::utils;`;
  1053. const result = extractFromSource('submod.rs', code);
  1054. const importNode = result.nodes.find((n) => n.kind === 'import');
  1055. expect(importNode).toBeDefined();
  1056. expect(importNode?.name).toBe('super');
  1057. });
  1058. it('should extract external crate imports', () => {
  1059. const code = `use serde::{Serialize, Deserialize};`;
  1060. const result = extractFromSource('types.rs', code);
  1061. const importNode = result.nodes.find((n) => n.kind === 'import');
  1062. expect(importNode).toBeDefined();
  1063. expect(importNode?.name).toBe('serde');
  1064. expect(importNode?.signature).toContain('Serialize');
  1065. expect(importNode?.signature).toContain('Deserialize');
  1066. });
  1067. });
  1068. describe('Go imports', () => {
  1069. it('should extract single import', () => {
  1070. const code = `
  1071. package main
  1072. import "fmt"
  1073. `;
  1074. const result = extractFromSource('main.go', code);
  1075. const importNode = result.nodes.find((n) => n.kind === 'import');
  1076. expect(importNode).toBeDefined();
  1077. expect(importNode?.name).toBe('fmt');
  1078. });
  1079. it('should extract grouped imports', () => {
  1080. const code = `
  1081. package main
  1082. import (
  1083. "fmt"
  1084. "os"
  1085. "encoding/json"
  1086. )
  1087. `;
  1088. const result = extractFromSource('main.go', code);
  1089. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1090. expect(importNodes.length).toBe(3);
  1091. const names = importNodes.map((n) => n.name);
  1092. expect(names).toContain('fmt');
  1093. expect(names).toContain('os');
  1094. expect(names).toContain('encoding/json');
  1095. });
  1096. it('should extract aliased import', () => {
  1097. const code = `
  1098. package main
  1099. import f "fmt"
  1100. `;
  1101. const result = extractFromSource('main.go', code);
  1102. const importNode = result.nodes.find((n) => n.kind === 'import');
  1103. expect(importNode).toBeDefined();
  1104. expect(importNode?.name).toBe('fmt');
  1105. expect(importNode?.signature).toContain('f');
  1106. });
  1107. it('should extract dot import', () => {
  1108. const code = `
  1109. package main
  1110. import . "math"
  1111. `;
  1112. const result = extractFromSource('main.go', code);
  1113. const importNode = result.nodes.find((n) => n.kind === 'import');
  1114. expect(importNode).toBeDefined();
  1115. expect(importNode?.name).toBe('math');
  1116. expect(importNode?.signature).toContain('.');
  1117. });
  1118. it('should extract blank import', () => {
  1119. const code = `
  1120. package main
  1121. import _ "github.com/go-sql-driver/mysql"
  1122. `;
  1123. const result = extractFromSource('main.go', code);
  1124. const importNode = result.nodes.find((n) => n.kind === 'import');
  1125. expect(importNode).toBeDefined();
  1126. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1127. expect(importNode?.signature).toContain('_');
  1128. });
  1129. });
  1130. describe('Swift imports', () => {
  1131. it('should extract simple import', () => {
  1132. const code = `import Foundation`;
  1133. const result = extractFromSource('main.swift', code);
  1134. const importNode = result.nodes.find((n) => n.kind === 'import');
  1135. expect(importNode).toBeDefined();
  1136. expect(importNode?.name).toBe('Foundation');
  1137. expect(importNode?.signature).toBe('import Foundation');
  1138. });
  1139. it('should extract @testable import', () => {
  1140. const code = `@testable import Alamofire`;
  1141. const result = extractFromSource('Tests.swift', code);
  1142. const importNode = result.nodes.find((n) => n.kind === 'import');
  1143. expect(importNode).toBeDefined();
  1144. expect(importNode?.name).toBe('Alamofire');
  1145. expect(importNode?.signature).toContain('@testable');
  1146. });
  1147. it('should extract @preconcurrency import', () => {
  1148. const code = `@preconcurrency import Security`;
  1149. const result = extractFromSource('Auth.swift', code);
  1150. const importNode = result.nodes.find((n) => n.kind === 'import');
  1151. expect(importNode).toBeDefined();
  1152. expect(importNode?.name).toBe('Security');
  1153. });
  1154. it('should extract multiple imports', () => {
  1155. const code = `
  1156. import Foundation
  1157. import UIKit
  1158. import Alamofire
  1159. `;
  1160. const result = extractFromSource('App.swift', code);
  1161. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1162. expect(importNodes.length).toBe(3);
  1163. const names = importNodes.map((n) => n.name);
  1164. expect(names).toContain('Foundation');
  1165. expect(names).toContain('UIKit');
  1166. expect(names).toContain('Alamofire');
  1167. });
  1168. });
  1169. describe('Kotlin imports', () => {
  1170. it('should extract simple import', () => {
  1171. const code = `import java.io.IOException`;
  1172. const result = extractFromSource('Main.kt', code);
  1173. const importNode = result.nodes.find((n) => n.kind === 'import');
  1174. expect(importNode).toBeDefined();
  1175. expect(importNode?.name).toBe('java.io.IOException');
  1176. expect(importNode?.signature).toBe('import java.io.IOException');
  1177. });
  1178. it('should extract aliased import', () => {
  1179. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1180. const result = extractFromSource('Utils.kt', code);
  1181. const importNode = result.nodes.find((n) => n.kind === 'import');
  1182. expect(importNode).toBeDefined();
  1183. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1184. expect(importNode?.signature).toContain('as RequestBuilder');
  1185. });
  1186. it('should extract wildcard import', () => {
  1187. const code = `import java.util.concurrent.TimeUnit.*`;
  1188. const result = extractFromSource('Time.kt', code);
  1189. const importNode = result.nodes.find((n) => n.kind === 'import');
  1190. expect(importNode).toBeDefined();
  1191. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1192. expect(importNode?.signature).toContain('.*');
  1193. });
  1194. it('should extract multiple imports', () => {
  1195. const code = `
  1196. import java.io.IOException
  1197. import kotlin.test.assertFailsWith
  1198. import okhttp3.OkHttpClient
  1199. `;
  1200. const result = extractFromSource('Test.kt', code);
  1201. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1202. expect(importNodes.length).toBe(3);
  1203. const names = importNodes.map((n) => n.name);
  1204. expect(names).toContain('java.io.IOException');
  1205. expect(names).toContain('kotlin.test.assertFailsWith');
  1206. expect(names).toContain('okhttp3.OkHttpClient');
  1207. });
  1208. });
  1209. describe('Java imports', () => {
  1210. it('should extract simple import', () => {
  1211. const code = `import java.util.List;`;
  1212. const result = extractFromSource('Main.java', code);
  1213. const importNode = result.nodes.find((n) => n.kind === 'import');
  1214. expect(importNode).toBeDefined();
  1215. expect(importNode?.name).toBe('java.util.List');
  1216. expect(importNode?.signature).toBe('import java.util.List;');
  1217. });
  1218. it('should extract static import', () => {
  1219. const code = `import static java.util.Collections.emptyList;`;
  1220. const result = extractFromSource('Utils.java', code);
  1221. const importNode = result.nodes.find((n) => n.kind === 'import');
  1222. expect(importNode).toBeDefined();
  1223. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1224. expect(importNode?.signature).toContain('static');
  1225. });
  1226. it('should extract wildcard import', () => {
  1227. const code = `import java.util.*;`;
  1228. const result = extractFromSource('App.java', code);
  1229. const importNode = result.nodes.find((n) => n.kind === 'import');
  1230. expect(importNode).toBeDefined();
  1231. expect(importNode?.name).toBe('java.util');
  1232. expect(importNode?.signature).toContain('.*');
  1233. });
  1234. it('should extract nested class import', () => {
  1235. const code = `import java.util.Map.Entry;`;
  1236. const result = extractFromSource('MapUtil.java', code);
  1237. const importNode = result.nodes.find((n) => n.kind === 'import');
  1238. expect(importNode).toBeDefined();
  1239. expect(importNode?.name).toBe('java.util.Map.Entry');
  1240. });
  1241. it('should extract multiple imports', () => {
  1242. const code = `
  1243. import java.util.List;
  1244. import java.util.Map;
  1245. import java.io.IOException;
  1246. `;
  1247. const result = extractFromSource('Service.java', code);
  1248. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1249. expect(importNodes.length).toBe(3);
  1250. const names = importNodes.map((n) => n.name);
  1251. expect(names).toContain('java.util.List');
  1252. expect(names).toContain('java.util.Map');
  1253. expect(names).toContain('java.io.IOException');
  1254. });
  1255. });
  1256. describe('C# imports', () => {
  1257. it('should extract simple using', () => {
  1258. const code = `using System;`;
  1259. const result = extractFromSource('Program.cs', code);
  1260. const importNode = result.nodes.find((n) => n.kind === 'import');
  1261. expect(importNode).toBeDefined();
  1262. expect(importNode?.name).toBe('System');
  1263. expect(importNode?.signature).toBe('using System;');
  1264. });
  1265. it('should extract qualified using', () => {
  1266. const code = `using System.Collections.Generic;`;
  1267. const result = extractFromSource('Utils.cs', code);
  1268. const importNode = result.nodes.find((n) => n.kind === 'import');
  1269. expect(importNode).toBeDefined();
  1270. expect(importNode?.name).toBe('System.Collections.Generic');
  1271. });
  1272. it('should extract static using', () => {
  1273. const code = `using static System.Console;`;
  1274. const result = extractFromSource('App.cs', code);
  1275. const importNode = result.nodes.find((n) => n.kind === 'import');
  1276. expect(importNode).toBeDefined();
  1277. expect(importNode?.name).toBe('System.Console');
  1278. expect(importNode?.signature).toContain('static');
  1279. });
  1280. it('should extract alias using', () => {
  1281. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1282. const result = extractFromSource('Types.cs', code);
  1283. const importNode = result.nodes.find((n) => n.kind === 'import');
  1284. expect(importNode).toBeDefined();
  1285. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1286. expect(importNode?.signature).toContain('MyList =');
  1287. });
  1288. it('should extract multiple usings', () => {
  1289. const code = `
  1290. using System;
  1291. using System.Threading.Tasks;
  1292. using Microsoft.Extensions.DependencyInjection;
  1293. `;
  1294. const result = extractFromSource('Service.cs', code);
  1295. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1296. expect(importNodes.length).toBe(3);
  1297. const names = importNodes.map((n) => n.name);
  1298. expect(names).toContain('System');
  1299. expect(names).toContain('System.Threading.Tasks');
  1300. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1301. });
  1302. });
  1303. describe('PHP imports', () => {
  1304. it('should extract simple use', () => {
  1305. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1306. const result = extractFromSource('Test.php', code);
  1307. const importNode = result.nodes.find((n) => n.kind === 'import');
  1308. expect(importNode).toBeDefined();
  1309. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1310. });
  1311. it('should extract aliased use', () => {
  1312. const code = `<?php use Mockery as m;`;
  1313. const result = extractFromSource('Test.php', code);
  1314. const importNode = result.nodes.find((n) => n.kind === 'import');
  1315. expect(importNode).toBeDefined();
  1316. expect(importNode?.name).toBe('Mockery');
  1317. expect(importNode?.signature).toContain('as m');
  1318. });
  1319. it('should extract function use', () => {
  1320. const code = `<?php use function Illuminate\\Support\\env;`;
  1321. const result = extractFromSource('helpers.php', code);
  1322. const importNode = result.nodes.find((n) => n.kind === 'import');
  1323. expect(importNode).toBeDefined();
  1324. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1325. expect(importNode?.signature).toContain('function');
  1326. });
  1327. it('should extract grouped use', () => {
  1328. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1329. const result = extractFromSource('Models.php', code);
  1330. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1331. expect(importNodes.length).toBe(2);
  1332. const names = importNodes.map((n) => n.name);
  1333. expect(names).toContain('Illuminate\\Database\\Model');
  1334. expect(names).toContain('Illuminate\\Database\\Builder');
  1335. });
  1336. it('should extract multiple uses', () => {
  1337. const code = `<?php
  1338. use Illuminate\\Support\\Collection;
  1339. use Illuminate\\Support\\Str;
  1340. use Closure;
  1341. `;
  1342. const result = extractFromSource('Service.php', code);
  1343. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1344. expect(importNodes.length).toBe(3);
  1345. const names = importNodes.map((n) => n.name);
  1346. expect(names).toContain('Illuminate\\Support\\Collection');
  1347. expect(names).toContain('Illuminate\\Support\\Str');
  1348. expect(names).toContain('Closure');
  1349. });
  1350. });
  1351. describe('Ruby imports', () => {
  1352. it('should extract require', () => {
  1353. const code = `require 'json'`;
  1354. const result = extractFromSource('app.rb', code);
  1355. const importNode = result.nodes.find((n) => n.kind === 'import');
  1356. expect(importNode).toBeDefined();
  1357. expect(importNode?.name).toBe('json');
  1358. expect(importNode?.signature).toBe("require 'json'");
  1359. });
  1360. it('should extract require with path', () => {
  1361. const code = `require 'active_support/core_ext/string'`;
  1362. const result = extractFromSource('config.rb', code);
  1363. const importNode = result.nodes.find((n) => n.kind === 'import');
  1364. expect(importNode).toBeDefined();
  1365. expect(importNode?.name).toBe('active_support/core_ext/string');
  1366. });
  1367. it('should extract require_relative', () => {
  1368. const code = `require_relative '../test_helper'`;
  1369. const result = extractFromSource('test/my_test.rb', code);
  1370. const importNode = result.nodes.find((n) => n.kind === 'import');
  1371. expect(importNode).toBeDefined();
  1372. expect(importNode?.name).toBe('../test_helper');
  1373. expect(importNode?.signature).toContain('require_relative');
  1374. });
  1375. it('should not extract non-require calls', () => {
  1376. const code = `puts 'hello'`;
  1377. const result = extractFromSource('app.rb', code);
  1378. const importNode = result.nodes.find((n) => n.kind === 'import');
  1379. expect(importNode).toBeUndefined();
  1380. });
  1381. it('should extract multiple requires', () => {
  1382. const code = `
  1383. require 'json'
  1384. require 'yaml'
  1385. require_relative 'helper'
  1386. `;
  1387. const result = extractFromSource('lib.rb', code);
  1388. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1389. expect(importNodes.length).toBe(3);
  1390. const names = importNodes.map((n) => n.name);
  1391. expect(names).toContain('json');
  1392. expect(names).toContain('yaml');
  1393. expect(names).toContain('helper');
  1394. });
  1395. });
  1396. describe('C/C++ imports', () => {
  1397. it('should extract system include', () => {
  1398. const code = `#include <iostream>`;
  1399. const result = extractFromSource('main.cpp', code);
  1400. const importNode = result.nodes.find((n) => n.kind === 'import');
  1401. expect(importNode).toBeDefined();
  1402. expect(importNode?.name).toBe('iostream');
  1403. expect(importNode?.signature).toBe('#include <iostream>');
  1404. });
  1405. it('should extract system include with path', () => {
  1406. const code = `#include <nlohmann/json.hpp>`;
  1407. const result = extractFromSource('app.cpp', code);
  1408. const importNode = result.nodes.find((n) => n.kind === 'import');
  1409. expect(importNode).toBeDefined();
  1410. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1411. });
  1412. it('should extract local include', () => {
  1413. const code = `#include "myheader.h"`;
  1414. const result = extractFromSource('main.cpp', code);
  1415. const importNode = result.nodes.find((n) => n.kind === 'import');
  1416. expect(importNode).toBeDefined();
  1417. expect(importNode?.name).toBe('myheader.h');
  1418. });
  1419. it('should extract C header', () => {
  1420. const code = `#include <stdio.h>`;
  1421. const result = extractFromSource('main.c', code);
  1422. const importNode = result.nodes.find((n) => n.kind === 'import');
  1423. expect(importNode).toBeDefined();
  1424. expect(importNode?.name).toBe('stdio.h');
  1425. });
  1426. it('should extract multiple includes', () => {
  1427. const code = `
  1428. #include <iostream>
  1429. #include <vector>
  1430. #include "config.h"
  1431. `;
  1432. const result = extractFromSource('app.cpp', code);
  1433. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1434. expect(importNodes.length).toBe(3);
  1435. const names = importNodes.map((n) => n.name);
  1436. expect(names).toContain('iostream');
  1437. expect(names).toContain('vector');
  1438. expect(names).toContain('config.h');
  1439. });
  1440. });
  1441. describe('Dart imports', () => {
  1442. it('should extract dart: import', () => {
  1443. const code = `import 'dart:async';`;
  1444. const result = extractFromSource('main.dart', code);
  1445. const importNode = result.nodes.find((n) => n.kind === 'import');
  1446. expect(importNode).toBeDefined();
  1447. expect(importNode?.name).toBe('dart:async');
  1448. expect(importNode?.signature).toBe("import 'dart:async';");
  1449. });
  1450. it('should extract package import', () => {
  1451. const code = `import 'package:flutter/material.dart';`;
  1452. const result = extractFromSource('app.dart', code);
  1453. const importNode = result.nodes.find((n) => n.kind === 'import');
  1454. expect(importNode).toBeDefined();
  1455. expect(importNode?.name).toBe('package:flutter/material.dart');
  1456. });
  1457. it('should extract aliased import', () => {
  1458. const code = `import 'package:http/http.dart' as http;`;
  1459. const result = extractFromSource('api.dart', code);
  1460. const importNode = result.nodes.find((n) => n.kind === 'import');
  1461. expect(importNode).toBeDefined();
  1462. expect(importNode?.name).toBe('package:http/http.dart');
  1463. expect(importNode?.signature).toContain('as http');
  1464. });
  1465. it('should extract multiple imports', () => {
  1466. const code = `
  1467. import 'dart:async';
  1468. import 'dart:convert';
  1469. import 'package:flutter/material.dart';
  1470. `;
  1471. const result = extractFromSource('main.dart', code);
  1472. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1473. expect(importNodes.length).toBe(3);
  1474. const names = importNodes.map((n) => n.name);
  1475. expect(names).toContain('dart:async');
  1476. expect(names).toContain('dart:convert');
  1477. expect(names).toContain('package:flutter/material.dart');
  1478. });
  1479. it('should extract relative import', () => {
  1480. const code = `import '../utils/helpers.dart';`;
  1481. const result = extractFromSource('lib/main.dart', code);
  1482. const importNode = result.nodes.find((n) => n.kind === 'import');
  1483. expect(importNode).toBeDefined();
  1484. expect(importNode?.name).toBe('../utils/helpers.dart');
  1485. });
  1486. });
  1487. describe('Liquid imports', () => {
  1488. it('should extract render tag', () => {
  1489. const code = `{% render 'loading-spinner' %}`;
  1490. const result = extractFromSource('template.liquid', code);
  1491. const importNode = result.nodes.find((n) => n.kind === 'import');
  1492. expect(importNode).toBeDefined();
  1493. expect(importNode?.name).toBe('loading-spinner');
  1494. expect(importNode?.signature).toContain('render');
  1495. });
  1496. it('should extract section tag', () => {
  1497. const code = `{% section 'header' %}`;
  1498. const result = extractFromSource('layout/theme.liquid', code);
  1499. const importNode = result.nodes.find((n) => n.kind === 'import');
  1500. expect(importNode).toBeDefined();
  1501. expect(importNode?.name).toBe('header');
  1502. expect(importNode?.signature).toContain('section');
  1503. });
  1504. it('should extract include tag', () => {
  1505. const code = `{% include 'icon-cart' %}`;
  1506. const result = extractFromSource('snippets/header.liquid', code);
  1507. const importNode = result.nodes.find((n) => n.kind === 'import');
  1508. expect(importNode).toBeDefined();
  1509. expect(importNode?.name).toBe('icon-cart');
  1510. expect(importNode?.signature).toContain('include');
  1511. });
  1512. it('should extract render with whitespace control', () => {
  1513. const code = `{%- render 'price' -%}`;
  1514. const result = extractFromSource('snippets/product.liquid', code);
  1515. const importNode = result.nodes.find((n) => n.kind === 'import');
  1516. expect(importNode).toBeDefined();
  1517. expect(importNode?.name).toBe('price');
  1518. });
  1519. it('should extract multiple imports', () => {
  1520. const code = `
  1521. {% section 'header' %}
  1522. {% render 'loading-spinner' %}
  1523. {% render 'cart-drawer' %}
  1524. `;
  1525. const result = extractFromSource('layout/theme.liquid', code);
  1526. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1527. expect(importNodes.length).toBe(3);
  1528. const names = importNodes.map((n) => n.name);
  1529. expect(names).toContain('header');
  1530. expect(names).toContain('loading-spinner');
  1531. expect(names).toContain('cart-drawer');
  1532. });
  1533. });
  1534. });
  1535. // =============================================================================
  1536. // Pascal / Delphi Extraction
  1537. // =============================================================================
  1538. describe('Pascal / Delphi Extraction', () => {
  1539. describe('Language detection', () => {
  1540. it('should detect Pascal files', () => {
  1541. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  1542. expect(detectLanguage('App.dpr')).toBe('pascal');
  1543. expect(detectLanguage('Package.dpk')).toBe('pascal');
  1544. expect(detectLanguage('App.lpr')).toBe('pascal');
  1545. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  1546. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  1547. });
  1548. it('should report Pascal as supported', () => {
  1549. expect(isLanguageSupported('pascal')).toBe(true);
  1550. expect(getSupportedLanguages()).toContain('pascal');
  1551. });
  1552. });
  1553. describe('Unit extraction', () => {
  1554. it('should extract unit as module', () => {
  1555. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  1556. const result = extractFromSource('MyUnit.pas', code);
  1557. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1558. expect(moduleNode).toBeDefined();
  1559. expect(moduleNode?.name).toBe('MyUnit');
  1560. expect(moduleNode?.language).toBe('pascal');
  1561. });
  1562. it('should extract program as module', () => {
  1563. const code = `program MyApp;\nbegin\nend.`;
  1564. const result = extractFromSource('MyApp.dpr', code);
  1565. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1566. expect(moduleNode).toBeDefined();
  1567. expect(moduleNode?.name).toBe('MyApp');
  1568. });
  1569. it('should fallback to filename when module name is empty', () => {
  1570. // Some .dpr templates use "program;" without a name
  1571. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  1572. const result = extractFromSource('Console.dpr', code);
  1573. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1574. expect(moduleNode).toBeDefined();
  1575. expect(moduleNode?.name).toBe('Console');
  1576. });
  1577. });
  1578. describe('Uses clause (imports)', () => {
  1579. it('should extract uses as individual imports', () => {
  1580. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  1581. const result = extractFromSource('Test.pas', code);
  1582. const imports = result.nodes.filter((n) => n.kind === 'import');
  1583. expect(imports.length).toBe(2);
  1584. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  1585. expect(imports.map((n) => n.name)).toContain('System.Classes');
  1586. });
  1587. it('should create unresolved references for imports', () => {
  1588. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  1589. const result = extractFromSource('Test.pas', code);
  1590. const importRef = result.unresolvedReferences.find(
  1591. (r) => r.referenceKind === 'imports'
  1592. );
  1593. expect(importRef).toBeDefined();
  1594. expect(importRef?.referenceName).toBe('UAuth');
  1595. });
  1596. });
  1597. describe('Class extraction', () => {
  1598. it('should extract class declarations', () => {
  1599. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  1600. const result = extractFromSource('Test.pas', code);
  1601. const classNode = result.nodes.find((n) => n.kind === 'class');
  1602. expect(classNode).toBeDefined();
  1603. expect(classNode?.name).toBe('TMyClass');
  1604. });
  1605. it('should extract class with inheritance', () => {
  1606. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  1607. const result = extractFromSource('Test.pas', code);
  1608. const extendsRef = result.unresolvedReferences.find(
  1609. (r) => r.referenceKind === 'extends'
  1610. );
  1611. expect(extendsRef).toBeDefined();
  1612. expect(extendsRef?.referenceName).toBe('TParent');
  1613. });
  1614. it('should extract class with interface implementation', () => {
  1615. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  1616. const result = extractFromSource('Test.pas', code);
  1617. const extendsRef = result.unresolvedReferences.find(
  1618. (r) => r.referenceKind === 'extends'
  1619. );
  1620. const implementsRef = result.unresolvedReferences.find(
  1621. (r) => r.referenceKind === 'implements'
  1622. );
  1623. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1624. expect(implementsRef?.referenceName).toBe('ILogger');
  1625. });
  1626. });
  1627. describe('Record extraction', () => {
  1628. it('should extract records as class nodes', () => {
  1629. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  1630. const result = extractFromSource('Test.pas', code);
  1631. const classNode = result.nodes.find((n) => n.kind === 'class');
  1632. expect(classNode).toBeDefined();
  1633. expect(classNode?.name).toBe('TPoint');
  1634. const fields = result.nodes.filter((n) => n.kind === 'field');
  1635. expect(fields.length).toBe(2);
  1636. expect(fields.map((f) => f.name)).toContain('X');
  1637. expect(fields.map((f) => f.name)).toContain('Y');
  1638. });
  1639. });
  1640. describe('Interface extraction', () => {
  1641. it('should extract interface declarations', () => {
  1642. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  1643. const result = extractFromSource('Test.pas', code);
  1644. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1645. expect(ifaceNode).toBeDefined();
  1646. expect(ifaceNode?.name).toBe('ILogger');
  1647. });
  1648. });
  1649. describe('Method extraction', () => {
  1650. it('should extract methods with visibility', () => {
  1651. 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.`;
  1652. const result = extractFromSource('Test.pas', code);
  1653. const methods = result.nodes.filter((n) => n.kind === 'method');
  1654. expect(methods.length).toBe(2);
  1655. const createMethod = methods.find((m) => m.name === 'Create');
  1656. expect(createMethod?.visibility).toBe('public');
  1657. const getValue = methods.find((m) => m.name === 'GetValue');
  1658. expect(getValue?.visibility).toBe('public');
  1659. const fields = result.nodes.filter((n) => n.kind === 'field');
  1660. const fValue = fields.find((f) => f.name === 'FValue');
  1661. expect(fValue?.visibility).toBe('private');
  1662. });
  1663. it('should detect static methods (class methods)', () => {
  1664. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  1665. const result = extractFromSource('Test.pas', code);
  1666. const methods = result.nodes.filter((n) => n.kind === 'method');
  1667. const staticMethod = methods.find((m) => m.name === 'Create');
  1668. expect(staticMethod?.isStatic).toBe(true);
  1669. });
  1670. });
  1671. describe('Enum extraction', () => {
  1672. it('should extract enums with members', () => {
  1673. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  1674. const result = extractFromSource('Test.pas', code);
  1675. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1676. expect(enumNode).toBeDefined();
  1677. expect(enumNode?.name).toBe('TColor');
  1678. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1679. expect(members.length).toBe(3);
  1680. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  1681. });
  1682. });
  1683. describe('Property extraction', () => {
  1684. it('should extract properties', () => {
  1685. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  1686. const result = extractFromSource('Test.pas', code);
  1687. const propNode = result.nodes.find((n) => n.kind === 'property');
  1688. expect(propNode).toBeDefined();
  1689. expect(propNode?.name).toBe('Name');
  1690. expect(propNode?.visibility).toBe('public');
  1691. });
  1692. });
  1693. describe('Constant extraction', () => {
  1694. it('should extract constants', () => {
  1695. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  1696. const result = extractFromSource('Test.pas', code);
  1697. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1698. expect(constants.length).toBe(2);
  1699. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  1700. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  1701. });
  1702. });
  1703. describe('Type alias extraction', () => {
  1704. it('should extract type aliases', () => {
  1705. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  1706. const result = extractFromSource('Test.pas', code);
  1707. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  1708. expect(aliasNode).toBeDefined();
  1709. expect(aliasNode?.name).toBe('TUserName');
  1710. });
  1711. });
  1712. describe('Call extraction', () => {
  1713. it('should extract calls from implementation bodies', () => {
  1714. 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.`;
  1715. const result = extractFromSource('Test.pas', code);
  1716. const callRef = result.unresolvedReferences.find(
  1717. (r) => r.referenceKind === 'calls'
  1718. );
  1719. expect(callRef).toBeDefined();
  1720. expect(callRef?.referenceName).toBe('WriteLn');
  1721. });
  1722. });
  1723. describe('Containment edges', () => {
  1724. it('should create contains edges for class members', () => {
  1725. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  1726. const result = extractFromSource('Test.pas', code);
  1727. const classNode = result.nodes.find((n) => n.kind === 'class');
  1728. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1729. expect(classNode).toBeDefined();
  1730. expect(methodNode).toBeDefined();
  1731. const containsEdge = result.edges.find(
  1732. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  1733. );
  1734. expect(containsEdge).toBeDefined();
  1735. });
  1736. });
  1737. describe('Full fixture: UAuth.pas', () => {
  1738. const code = `unit UAuth;
  1739. interface
  1740. uses
  1741. System.SysUtils,
  1742. System.Classes;
  1743. type
  1744. ITokenValidator = interface
  1745. ['{11111111-1111-1111-1111-111111111111}']
  1746. function Validate(const AToken: string): Boolean;
  1747. end;
  1748. TAuthService = class(TInterfacedObject, ITokenValidator)
  1749. private
  1750. FToken: string;
  1751. FLoginCount: Integer;
  1752. procedure IncLoginCount;
  1753. protected
  1754. function GetToken: string;
  1755. public
  1756. constructor Create;
  1757. destructor Destroy; override;
  1758. function Validate(const AToken: string): Boolean;
  1759. function Login(const AUser, APass: string): string;
  1760. property Token: string read GetToken;
  1761. property LoginCount: Integer read FLoginCount;
  1762. end;
  1763. implementation
  1764. constructor TAuthService.Create;
  1765. begin
  1766. inherited Create;
  1767. FToken := '';
  1768. FLoginCount := 0;
  1769. end;
  1770. destructor TAuthService.Destroy;
  1771. begin
  1772. FToken := '';
  1773. inherited Destroy;
  1774. end;
  1775. procedure TAuthService.IncLoginCount;
  1776. begin
  1777. Inc(FLoginCount);
  1778. end;
  1779. function TAuthService.GetToken: string;
  1780. begin
  1781. Result := FToken;
  1782. end;
  1783. function TAuthService.Validate(const AToken: string): Boolean;
  1784. begin
  1785. Result := AToken <> '';
  1786. end;
  1787. function TAuthService.Login(const AUser, APass: string): string;
  1788. begin
  1789. IncLoginCount;
  1790. if Validate(AUser + ':' + APass) then
  1791. begin
  1792. FToken := AUser;
  1793. Result := 'ok';
  1794. end
  1795. else
  1796. Result := '';
  1797. end;
  1798. end.`;
  1799. it('should extract all expected nodes', () => {
  1800. const result = extractFromSource('UAuth.pas', code);
  1801. expect(result.errors).toHaveLength(0);
  1802. // Module
  1803. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1804. expect(moduleNode?.name).toBe('UAuth');
  1805. // Imports
  1806. const imports = result.nodes.filter((n) => n.kind === 'import');
  1807. expect(imports.length).toBe(2);
  1808. // Interface
  1809. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1810. expect(ifaceNode?.name).toBe('ITokenValidator');
  1811. // Class
  1812. const classNode = result.nodes.find((n) => n.kind === 'class');
  1813. expect(classNode?.name).toBe('TAuthService');
  1814. // Methods
  1815. const methods = result.nodes.filter((n) => n.kind === 'method');
  1816. expect(methods.length).toBeGreaterThanOrEqual(6);
  1817. expect(methods.map((m) => m.name)).toContain('Create');
  1818. expect(methods.map((m) => m.name)).toContain('Destroy');
  1819. expect(methods.map((m) => m.name)).toContain('Login');
  1820. // Fields
  1821. const fields = result.nodes.filter((n) => n.kind === 'field');
  1822. expect(fields.length).toBe(2);
  1823. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  1824. // Properties
  1825. const props = result.nodes.filter((n) => n.kind === 'property');
  1826. expect(props.length).toBe(2);
  1827. expect(props.map((p) => p.name)).toContain('Token');
  1828. expect(props.map((p) => p.name)).toContain('LoginCount');
  1829. });
  1830. it('should extract inheritance and interface implementation', () => {
  1831. const result = extractFromSource('UAuth.pas', code);
  1832. const extendsRef = result.unresolvedReferences.find(
  1833. (r) => r.referenceKind === 'extends'
  1834. );
  1835. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1836. const implementsRef = result.unresolvedReferences.find(
  1837. (r) => r.referenceKind === 'implements'
  1838. );
  1839. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  1840. });
  1841. it('should extract calls from implementation', () => {
  1842. const result = extractFromSource('UAuth.pas', code);
  1843. const callRefs = result.unresolvedReferences.filter(
  1844. (r) => r.referenceKind === 'calls'
  1845. );
  1846. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  1847. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  1848. });
  1849. });
  1850. describe('Full fixture: UTypes.pas', () => {
  1851. const code = `unit UTypes;
  1852. interface
  1853. uses
  1854. System.SysUtils;
  1855. const
  1856. C_MAX_RETRIES = 3;
  1857. C_DEFAULT_NAME = 'Guest';
  1858. type
  1859. TUserRole = (urAdmin, urEditor, urViewer);
  1860. TPoint2D = record
  1861. X: Double;
  1862. Y: Double;
  1863. end;
  1864. TUserName = string;
  1865. TUserInfo = class
  1866. public
  1867. type
  1868. TAddress = record
  1869. Street: string;
  1870. City: string;
  1871. Zip: string;
  1872. end;
  1873. private
  1874. FName: TUserName;
  1875. FRole: TUserRole;
  1876. FAddress: TAddress;
  1877. public
  1878. constructor Create(const AName: TUserName; ARole: TUserRole);
  1879. function GetDisplayName: string;
  1880. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  1881. property Name: TUserName read FName write FName;
  1882. property Role: TUserRole read FRole;
  1883. property Address: TAddress read FAddress write FAddress;
  1884. end;
  1885. implementation
  1886. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  1887. begin
  1888. FName := AName;
  1889. FRole := ARole;
  1890. end;
  1891. function TUserInfo.GetDisplayName: string;
  1892. begin
  1893. if FRole = urAdmin then
  1894. Result := '[Admin] ' + FName
  1895. else
  1896. Result := FName;
  1897. end;
  1898. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  1899. begin
  1900. Result := TUserInfo.Create(AName, urAdmin);
  1901. end;
  1902. end.`;
  1903. it('should extract enums with members', () => {
  1904. const result = extractFromSource('UTypes.pas', code);
  1905. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1906. expect(enumNode?.name).toBe('TUserRole');
  1907. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1908. expect(members.length).toBe(3);
  1909. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  1910. });
  1911. it('should extract constants', () => {
  1912. const result = extractFromSource('UTypes.pas', code);
  1913. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1914. expect(constants.length).toBe(2);
  1915. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  1916. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  1917. });
  1918. it('should extract type aliases', () => {
  1919. const result = extractFromSource('UTypes.pas', code);
  1920. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  1921. expect(aliases.map((a) => a.name)).toContain('TUserName');
  1922. });
  1923. it('should extract records as classes with fields', () => {
  1924. const result = extractFromSource('UTypes.pas', code);
  1925. const classes = result.nodes.filter((n) => n.kind === 'class');
  1926. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  1927. // TPoint2D fields
  1928. const fields = result.nodes.filter((n) => n.kind === 'field');
  1929. expect(fields.map((f) => f.name)).toContain('X');
  1930. expect(fields.map((f) => f.name)).toContain('Y');
  1931. });
  1932. it('should extract static class methods', () => {
  1933. const result = extractFromSource('UTypes.pas', code);
  1934. const methods = result.nodes.filter((n) => n.kind === 'method');
  1935. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  1936. expect(staticMethod).toBeDefined();
  1937. expect(staticMethod?.isStatic).toBe(true);
  1938. });
  1939. it('should extract nested types', () => {
  1940. const result = extractFromSource('UTypes.pas', code);
  1941. const classes = result.nodes.filter((n) => n.kind === 'class');
  1942. expect(classes.map((c) => c.name)).toContain('TAddress');
  1943. });
  1944. });
  1945. });
  1946. // =============================================================================
  1947. // DFM/FMX Extraction
  1948. // =============================================================================
  1949. describe('DFM/FMX Extraction', () => {
  1950. it('should extract components from DFM', () => {
  1951. const code = `object Form1: TForm1
  1952. Left = 0
  1953. Top = 0
  1954. Caption = 'My Form'
  1955. object Button1: TButton
  1956. Left = 10
  1957. Top = 10
  1958. Caption = 'Click Me'
  1959. end
  1960. end`;
  1961. const result = extractFromSource('Form1.dfm', code);
  1962. const components = result.nodes.filter((n) => n.kind === 'component');
  1963. expect(components.length).toBe(2);
  1964. expect(components.map((c) => c.name)).toContain('Form1');
  1965. expect(components.map((c) => c.name)).toContain('Button1');
  1966. const button = components.find((c) => c.name === 'Button1');
  1967. expect(button?.signature).toBe('TButton');
  1968. });
  1969. it('should extract nested component hierarchy', () => {
  1970. const code = `object Form1: TForm1
  1971. object Panel1: TPanel
  1972. object Label1: TLabel
  1973. Caption = 'Hello'
  1974. end
  1975. end
  1976. end`;
  1977. const result = extractFromSource('Form1.dfm', code);
  1978. const components = result.nodes.filter((n) => n.kind === 'component');
  1979. expect(components.length).toBe(3);
  1980. // Check nesting: Panel1 contains Label1
  1981. const panel = components.find((c) => c.name === 'Panel1');
  1982. const label = components.find((c) => c.name === 'Label1');
  1983. const containsEdge = result.edges.find(
  1984. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  1985. );
  1986. expect(containsEdge).toBeDefined();
  1987. });
  1988. it('should extract event handler references', () => {
  1989. const code = `object Form1: TForm1
  1990. OnCreate = FormCreate
  1991. OnDestroy = FormDestroy
  1992. object Button1: TButton
  1993. OnClick = Button1Click
  1994. end
  1995. end`;
  1996. const result = extractFromSource('Form1.dfm', code);
  1997. const refs = result.unresolvedReferences;
  1998. expect(refs.length).toBe(3);
  1999. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2000. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2001. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2002. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2003. });
  2004. it('should handle multi-line properties', () => {
  2005. const code = `object Form1: TForm1
  2006. SQL.Strings = (
  2007. 'SELECT * FROM users'
  2008. 'WHERE active = 1')
  2009. object Button1: TButton
  2010. OnClick = Button1Click
  2011. end
  2012. end`;
  2013. const result = extractFromSource('Form1.dfm', code);
  2014. const components = result.nodes.filter((n) => n.kind === 'component');
  2015. expect(components.length).toBe(2);
  2016. const refs = result.unresolvedReferences;
  2017. expect(refs.length).toBe(1);
  2018. expect(refs[0]?.referenceName).toBe('Button1Click');
  2019. });
  2020. it('should handle inherited keyword', () => {
  2021. const code = `inherited Form1: TForm1
  2022. Caption = 'Inherited Form'
  2023. object Button1: TButton
  2024. OnClick = Button1Click
  2025. end
  2026. end`;
  2027. const result = extractFromSource('Form1.dfm', code);
  2028. const components = result.nodes.filter((n) => n.kind === 'component');
  2029. expect(components.length).toBe(2);
  2030. expect(components.map((c) => c.name)).toContain('Form1');
  2031. });
  2032. it('should handle item collection properties', () => {
  2033. const code = `object Form1: TForm1
  2034. object StatusBar1: TStatusBar
  2035. Panels = <
  2036. item
  2037. Width = 200
  2038. end
  2039. item
  2040. Width = 200
  2041. end>
  2042. end
  2043. end`;
  2044. const result = extractFromSource('Form1.dfm', code);
  2045. const components = result.nodes.filter((n) => n.kind === 'component');
  2046. expect(components.length).toBe(2);
  2047. });
  2048. describe('Full fixture: MainForm.dfm', () => {
  2049. const code = `object frmMain: TfrmMain
  2050. Left = 0
  2051. Top = 0
  2052. Caption = 'CodeGraph DFM Fixture'
  2053. ClientHeight = 480
  2054. ClientWidth = 640
  2055. OnCreate = FormCreate
  2056. OnDestroy = FormDestroy
  2057. object pnlTop: TPanel
  2058. Left = 0
  2059. Top = 0
  2060. Width = 640
  2061. Height = 50
  2062. object lblTitle: TLabel
  2063. Left = 16
  2064. Top = 16
  2065. Caption = 'Authentication Service'
  2066. end
  2067. object btnLogin: TButton
  2068. Left = 540
  2069. Top = 12
  2070. OnClick = btnLoginClick
  2071. end
  2072. end
  2073. object pnlContent: TPanel
  2074. Left = 0
  2075. Top = 50
  2076. object edtUsername: TEdit
  2077. Left = 16
  2078. Top = 16
  2079. OnChange = edtUsernameChange
  2080. end
  2081. object edtPassword: TEdit
  2082. Left = 16
  2083. Top = 48
  2084. OnKeyPress = edtPasswordKeyPress
  2085. end
  2086. object mmoLog: TMemo
  2087. Left = 16
  2088. Top = 88
  2089. end
  2090. end
  2091. object pnlStatus: TStatusBar
  2092. Left = 0
  2093. Top = 440
  2094. Panels = <
  2095. item
  2096. Width = 200
  2097. end
  2098. item
  2099. Width = 200
  2100. end>
  2101. end
  2102. end`;
  2103. it('should extract all components', () => {
  2104. const result = extractFromSource('MainForm.dfm', code);
  2105. const components = result.nodes.filter((n) => n.kind === 'component');
  2106. expect(components.length).toBe(9);
  2107. expect(components.map((c) => c.name)).toEqual(
  2108. expect.arrayContaining([
  2109. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2110. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2111. ])
  2112. );
  2113. });
  2114. it('should extract all event handlers', () => {
  2115. const result = extractFromSource('MainForm.dfm', code);
  2116. const refs = result.unresolvedReferences;
  2117. expect(refs.length).toBe(5);
  2118. expect(refs.map((r) => r.referenceName)).toEqual(
  2119. expect.arrayContaining([
  2120. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2121. 'edtUsernameChange', 'edtPasswordKeyPress',
  2122. ])
  2123. );
  2124. });
  2125. });
  2126. });
  2127. describe('Full Indexing', () => {
  2128. let tempDir: string;
  2129. beforeEach(() => {
  2130. tempDir = createTempDir();
  2131. });
  2132. afterEach(() => {
  2133. cleanupTempDir(tempDir);
  2134. });
  2135. it('should index a TypeScript file', async () => {
  2136. // Create test file
  2137. const srcDir = path.join(tempDir, 'src');
  2138. fs.mkdirSync(srcDir);
  2139. fs.writeFileSync(
  2140. path.join(srcDir, 'utils.ts'),
  2141. `
  2142. export function add(a: number, b: number): number {
  2143. return a + b;
  2144. }
  2145. export function multiply(a: number, b: number): number {
  2146. return a * b;
  2147. }
  2148. `
  2149. );
  2150. // Initialize and index
  2151. const cg = CodeGraph.initSync(tempDir);
  2152. const result = await cg.indexAll();
  2153. expect(result.success).toBe(true);
  2154. expect(result.filesIndexed).toBe(1);
  2155. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2156. // Check nodes were stored
  2157. const nodes = cg.getNodesInFile('src/utils.ts');
  2158. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2159. const addFunc = nodes.find((n) => n.name === 'add');
  2160. expect(addFunc).toBeDefined();
  2161. expect(addFunc?.kind).toBe('function');
  2162. cg.close();
  2163. });
  2164. it('should index multiple files', async () => {
  2165. // Create test files
  2166. const srcDir = path.join(tempDir, 'src');
  2167. fs.mkdirSync(srcDir);
  2168. fs.writeFileSync(
  2169. path.join(srcDir, 'math.ts'),
  2170. `export function add(a: number, b: number) { return a + b; }`
  2171. );
  2172. fs.writeFileSync(
  2173. path.join(srcDir, 'string.ts'),
  2174. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2175. );
  2176. // Initialize and index
  2177. const cg = CodeGraph.initSync(tempDir);
  2178. const result = await cg.indexAll();
  2179. expect(result.success).toBe(true);
  2180. expect(result.filesIndexed).toBe(2);
  2181. const files = cg.getFiles();
  2182. expect(files.length).toBe(2);
  2183. cg.close();
  2184. });
  2185. it('should track file hashes for incremental updates', async () => {
  2186. // Create initial file
  2187. const srcDir = path.join(tempDir, 'src');
  2188. fs.mkdirSync(srcDir);
  2189. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2190. // Initialize and index
  2191. const cg = CodeGraph.initSync(tempDir);
  2192. await cg.indexAll();
  2193. // Check file is tracked
  2194. const file = cg.getFile('src/main.ts');
  2195. expect(file).toBeDefined();
  2196. expect(file?.contentHash).toBeDefined();
  2197. // Modify file
  2198. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2199. // Check for changes
  2200. const changes = cg.getChangedFiles();
  2201. expect(changes.modified).toContain('src/main.ts');
  2202. cg.close();
  2203. });
  2204. it('should sync and detect changes', async () => {
  2205. // Create initial file
  2206. const srcDir = path.join(tempDir, 'src');
  2207. fs.mkdirSync(srcDir);
  2208. fs.writeFileSync(
  2209. path.join(srcDir, 'main.ts'),
  2210. `export function original() { return 1; }`
  2211. );
  2212. // Initialize and index
  2213. const cg = CodeGraph.initSync(tempDir);
  2214. await cg.indexAll();
  2215. const initialNodes = cg.getNodesInFile('src/main.ts');
  2216. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2217. // Modify file
  2218. fs.writeFileSync(
  2219. path.join(srcDir, 'main.ts'),
  2220. `export function updated() { return 2; }`
  2221. );
  2222. // Sync
  2223. const syncResult = await cg.sync();
  2224. expect(syncResult.filesModified).toBe(1);
  2225. // Check nodes were updated
  2226. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2227. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2228. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2229. cg.close();
  2230. });
  2231. });
  2232. describe('Path Normalization', () => {
  2233. it('should convert backslashes to forward slashes', () => {
  2234. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  2235. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  2236. });
  2237. it('should leave forward-slash paths unchanged', () => {
  2238. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  2239. });
  2240. it('should handle empty string', () => {
  2241. expect(normalizePath('')).toBe('');
  2242. });
  2243. });
  2244. describe('Directory Exclusion', () => {
  2245. let tempDir: string;
  2246. beforeEach(() => {
  2247. tempDir = createTempDir();
  2248. });
  2249. afterEach(() => {
  2250. cleanupTempDir(tempDir);
  2251. });
  2252. it('should exclude node_modules directories', () => {
  2253. // Create structure: src/index.ts + node_modules/pkg/index.js
  2254. const srcDir = path.join(tempDir, 'src');
  2255. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  2256. fs.mkdirSync(srcDir, { recursive: true });
  2257. fs.mkdirSync(nmDir, { recursive: true });
  2258. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2259. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2260. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2261. const files = scanDirectory(tempDir, config);
  2262. expect(files).toContain('src/index.ts');
  2263. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2264. });
  2265. it('should exclude nested node_modules directories', () => {
  2266. // Create structure: packages/app/node_modules/pkg/index.js
  2267. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  2268. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  2269. fs.mkdirSync(srcDir, { recursive: true });
  2270. fs.mkdirSync(nmDir, { recursive: true });
  2271. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2272. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2273. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2274. const files = scanDirectory(tempDir, config);
  2275. expect(files).toContain('packages/app/src/index.ts');
  2276. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2277. });
  2278. it('should exclude .git directories', () => {
  2279. const srcDir = path.join(tempDir, 'src');
  2280. const gitDir = path.join(tempDir, '.git', 'objects');
  2281. fs.mkdirSync(srcDir, { recursive: true });
  2282. fs.mkdirSync(gitDir, { recursive: true });
  2283. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2284. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  2285. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2286. const files = scanDirectory(tempDir, config);
  2287. expect(files).toContain('src/index.ts');
  2288. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  2289. });
  2290. it('should return forward-slash paths on all platforms', () => {
  2291. const srcDir = path.join(tempDir, 'src', 'components');
  2292. fs.mkdirSync(srcDir, { recursive: true });
  2293. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  2294. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2295. const files = scanDirectory(tempDir, config);
  2296. expect(files.length).toBe(1);
  2297. expect(files[0]).toBe('src/components/Button.tsx');
  2298. expect(files[0]).not.toContain('\\');
  2299. });
  2300. it('should respect .codegraphignore marker', () => {
  2301. const srcDir = path.join(tempDir, 'src');
  2302. const vendorDir = path.join(tempDir, 'vendor');
  2303. fs.mkdirSync(srcDir, { recursive: true });
  2304. fs.mkdirSync(vendorDir, { recursive: true });
  2305. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2306. fs.writeFileSync(path.join(vendorDir, 'lib.ts'), 'export const y = 2;');
  2307. fs.writeFileSync(path.join(vendorDir, '.codegraphignore'), '');
  2308. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  2309. const files = scanDirectory(tempDir, config);
  2310. expect(files).toContain('src/index.ts');
  2311. expect(files.every((f) => !f.includes('vendor'))).toBe(true);
  2312. });
  2313. });