extraction.test.ts 91 KB

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