1
0

extraction.test.ts 133 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153
  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 } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages, initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  13. import { normalizePath } from '../src/utils';
  14. beforeAll(async () => {
  15. await initGrammars();
  16. await loadAllGrammars();
  17. });
  18. // Create a temporary directory for each test
  19. function createTempDir(): string {
  20. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  21. }
  22. // Clean up temporary directory
  23. function cleanupTempDir(dir: string): void {
  24. if (fs.existsSync(dir)) {
  25. fs.rmSync(dir, { recursive: true, force: true });
  26. }
  27. }
  28. describe('Language Detection', () => {
  29. it('should detect TypeScript files', () => {
  30. expect(detectLanguage('src/index.ts')).toBe('typescript');
  31. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  32. });
  33. it('should detect JavaScript files', () => {
  34. expect(detectLanguage('index.js')).toBe('javascript');
  35. expect(detectLanguage('App.jsx')).toBe('jsx');
  36. expect(detectLanguage('config.mjs')).toBe('javascript');
  37. });
  38. it('should detect Python files', () => {
  39. expect(detectLanguage('main.py')).toBe('python');
  40. });
  41. it('should detect Go files', () => {
  42. expect(detectLanguage('main.go')).toBe('go');
  43. });
  44. it('should detect Rust files', () => {
  45. expect(detectLanguage('lib.rs')).toBe('rust');
  46. });
  47. it('should detect Java files', () => {
  48. expect(detectLanguage('Main.java')).toBe('java');
  49. });
  50. it('should detect C files', () => {
  51. expect(detectLanguage('main.c')).toBe('c');
  52. expect(detectLanguage('utils.h')).toBe('c');
  53. });
  54. it('should detect C++ files', () => {
  55. expect(detectLanguage('main.cpp')).toBe('cpp');
  56. expect(detectLanguage('class.hpp')).toBe('cpp');
  57. });
  58. it('should detect C# files', () => {
  59. expect(detectLanguage('Program.cs')).toBe('csharp');
  60. });
  61. it('should detect PHP files', () => {
  62. expect(detectLanguage('index.php')).toBe('php');
  63. });
  64. it('should detect Ruby files', () => {
  65. expect(detectLanguage('app.rb')).toBe('ruby');
  66. });
  67. it('should detect Swift files', () => {
  68. expect(detectLanguage('ViewController.swift')).toBe('swift');
  69. });
  70. it('should detect Kotlin files', () => {
  71. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  72. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  73. });
  74. it('should detect Dart files', () => {
  75. expect(detectLanguage('main.dart')).toBe('dart');
  76. });
  77. it('should detect Objective-C files', () => {
  78. expect(detectLanguage('AppDelegate.m')).toBe('objc');
  79. expect(detectLanguage('ViewController.mm')).toBe('objc');
  80. const objcHeader = '@interface Foo : NSObject\n@end\n';
  81. expect(detectLanguage('Foo.h', objcHeader)).toBe('objc');
  82. expect(detectLanguage('stdio.h', '#ifndef STDIO_H\nvoid printf();\n#endif\n')).toBe('c');
  83. });
  84. it('should return unknown for unsupported extensions', () => {
  85. expect(detectLanguage('styles.css')).toBe('unknown');
  86. expect(detectLanguage('data.json')).toBe('unknown');
  87. });
  88. });
  89. describe('Language Support', () => {
  90. it('should report supported languages', () => {
  91. expect(isLanguageSupported('typescript')).toBe(true);
  92. expect(isLanguageSupported('python')).toBe(true);
  93. expect(isLanguageSupported('go')).toBe(true);
  94. expect(isLanguageSupported('unknown')).toBe(false);
  95. });
  96. it('should list all supported languages', () => {
  97. const languages = getSupportedLanguages();
  98. expect(languages).toContain('typescript');
  99. expect(languages).toContain('javascript');
  100. expect(languages).toContain('python');
  101. expect(languages).toContain('go');
  102. expect(languages).toContain('rust');
  103. expect(languages).toContain('java');
  104. expect(languages).toContain('csharp');
  105. expect(languages).toContain('php');
  106. expect(languages).toContain('ruby');
  107. expect(languages).toContain('swift');
  108. expect(languages).toContain('kotlin');
  109. expect(languages).toContain('dart');
  110. });
  111. });
  112. describe('TypeScript Extraction', () => {
  113. it('should extract function declarations', () => {
  114. const code = `
  115. export function processPayment(amount: number): Promise<Receipt> {
  116. return stripe.charge(amount);
  117. }
  118. `;
  119. const result = extractFromSource('payment.ts', code);
  120. // File node + function node
  121. const fileNode = result.nodes.find((n) => n.kind === 'file');
  122. expect(fileNode).toBeDefined();
  123. expect(fileNode?.name).toBe('payment.ts');
  124. const funcNode = result.nodes.find((n) => n.kind === 'function');
  125. expect(funcNode).toMatchObject({
  126. kind: 'function',
  127. name: 'processPayment',
  128. language: 'typescript',
  129. isExported: true,
  130. });
  131. expect(funcNode?.signature).toContain('amount: number');
  132. });
  133. it('should extract class declarations', () => {
  134. const code = `
  135. export class PaymentService {
  136. private stripe: StripeClient;
  137. constructor(apiKey: string) {
  138. this.stripe = new StripeClient(apiKey);
  139. }
  140. async charge(amount: number): Promise<Receipt> {
  141. return this.stripe.charge(amount);
  142. }
  143. }
  144. `;
  145. const result = extractFromSource('service.ts', code);
  146. const classNode = result.nodes.find((n) => n.kind === 'class');
  147. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  148. expect(classNode).toBeDefined();
  149. expect(classNode?.name).toBe('PaymentService');
  150. expect(classNode?.isExported).toBe(true);
  151. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  152. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  153. expect(chargeMethod).toBeDefined();
  154. });
  155. it('should extract interfaces', () => {
  156. const code = `
  157. export interface User {
  158. id: string;
  159. name: string;
  160. email: string;
  161. }
  162. `;
  163. const result = extractFromSource('types.ts', code);
  164. const fileNode = result.nodes.find((n) => n.kind === 'file');
  165. expect(fileNode).toBeDefined();
  166. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  167. expect(ifaceNode).toMatchObject({
  168. kind: 'interface',
  169. name: 'User',
  170. isExported: true,
  171. });
  172. });
  173. it('should extract type references from interface property signatures', () => {
  174. const code = `
  175. import type { IPage } from '../PromoterList';
  176. import type { IOrderField } from '../types';
  177. interface Hprops {
  178. value?: Partial<IPage> & Partial<IOrderField>;
  179. }
  180. `;
  181. const result = extractFromSource('HeaderFilter.ts', code);
  182. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  183. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  184. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  185. });
  186. it('should extract type references from interface method signatures', () => {
  187. const code = `
  188. import type { IPage } from '../PromoterList';
  189. import type { IOrderField } from '../types';
  190. interface MethodForm {
  191. fetchPage(arg: IPage): IOrderField;
  192. }
  193. `;
  194. const result = extractFromSource('MethodForm.ts', code);
  195. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  196. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  197. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  198. });
  199. it('should track function calls', () => {
  200. const code = `
  201. function main() {
  202. const result = processData();
  203. console.log(result);
  204. }
  205. `;
  206. const result = extractFromSource('main.ts', code);
  207. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  208. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  209. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  210. });
  211. });
  212. describe('Arrow Function Export Extraction', () => {
  213. it('should extract exported arrow functions assigned to const', () => {
  214. const code = `
  215. export const useAuth = (): AuthContextValue => {
  216. return useContext(AuthContext);
  217. };
  218. `;
  219. const result = extractFromSource('hooks.ts', code);
  220. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  221. expect(funcNode).toBeDefined();
  222. expect(funcNode).toMatchObject({
  223. kind: 'function',
  224. name: 'useAuth',
  225. isExported: true,
  226. });
  227. });
  228. it('should extract exported function expressions assigned to const', () => {
  229. const code = `
  230. export const processData = function(input: string): string {
  231. return input.trim();
  232. };
  233. `;
  234. const result = extractFromSource('utils.ts', code);
  235. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  236. expect(funcNode).toBeDefined();
  237. expect(funcNode).toMatchObject({
  238. kind: 'function',
  239. name: 'processData',
  240. isExported: true,
  241. });
  242. });
  243. it('should not extract non-exported arrow functions as exported', () => {
  244. const code = `
  245. const internalHelper = () => {
  246. return 42;
  247. };
  248. `;
  249. const result = extractFromSource('internal.ts', code);
  250. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  251. expect(helperNode).toBeDefined();
  252. expect(helperNode?.isExported).toBeFalsy();
  253. });
  254. it('should still skip truly anonymous arrow functions', () => {
  255. const code = `
  256. const items = [1, 2, 3].map((x) => x * 2);
  257. `;
  258. const result = extractFromSource('anon.ts', code);
  259. // The inline arrow function passed to .map() has no variable_declarator parent
  260. // and should remain anonymous (skipped)
  261. const anonFunctions = result.nodes.filter(
  262. (n) => n.kind === 'function' && n.name === '<anonymous>'
  263. );
  264. expect(anonFunctions).toHaveLength(0);
  265. });
  266. it('should extract multiple exported arrow functions from the same file', () => {
  267. const code = `
  268. export const add = (a: number, b: number): number => a + b;
  269. export const subtract = (a: number, b: number): number => a - b;
  270. const internal = () => 'not exported';
  271. `;
  272. const result = extractFromSource('math.ts', code);
  273. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  274. expect(exported).toHaveLength(2);
  275. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  276. const internalNode = result.nodes.find((n) => n.name === 'internal');
  277. expect(internalNode).toBeDefined();
  278. expect(internalNode?.isExported).toBeFalsy();
  279. });
  280. it('should extract arrow functions in JavaScript files', () => {
  281. const code = `
  282. export const fetchData = async () => {
  283. const response = await fetch('/api/data');
  284. return response.json();
  285. };
  286. `;
  287. const result = extractFromSource('api.js', code);
  288. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  289. expect(funcNode).toBeDefined();
  290. expect(funcNode).toMatchObject({
  291. kind: 'function',
  292. name: 'fetchData',
  293. isExported: true,
  294. });
  295. });
  296. });
  297. describe('Type Alias Extraction', () => {
  298. it('should extract exported type aliases in TypeScript', () => {
  299. const code = `
  300. export type AuthContextValue = {
  301. user: User | null;
  302. login: () => void;
  303. logout: () => void;
  304. };
  305. `;
  306. const result = extractFromSource('types.ts', code);
  307. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  308. expect(typeNode).toMatchObject({
  309. kind: 'type_alias',
  310. name: 'AuthContextValue',
  311. isExported: true,
  312. });
  313. });
  314. it('should extract non-exported type aliases', () => {
  315. const code = `
  316. type InternalState = {
  317. loading: boolean;
  318. error: string | null;
  319. };
  320. `;
  321. const result = extractFromSource('internal.ts', code);
  322. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  323. expect(typeNode).toMatchObject({
  324. kind: 'type_alias',
  325. name: 'InternalState',
  326. isExported: false,
  327. });
  328. });
  329. it('should extract multiple type aliases from the same file', () => {
  330. const code = `
  331. export type UnitSystem = 'metric' | 'imperial';
  332. export type DateFormat = 'ISO' | 'US' | 'EU';
  333. type Internal = string;
  334. `;
  335. const result = extractFromSource('config.ts', code);
  336. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  337. expect(typeAliases).toHaveLength(3);
  338. const exported = typeAliases.filter((n) => n.isExported);
  339. expect(exported).toHaveLength(2);
  340. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  341. });
  342. });
  343. describe('Exported Variable Extraction', () => {
  344. it('should extract exported const with call expression (Zustand store)', () => {
  345. const code = `
  346. export const useUIStore = create<UIState>((set) => ({
  347. isOpen: false,
  348. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  349. }));
  350. `;
  351. const result = extractFromSource('store.ts', code);
  352. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  353. expect(varNode).toBeDefined();
  354. expect(varNode?.isExported).toBe(true);
  355. });
  356. it('should extract exported const with object literal', () => {
  357. const code = `
  358. export const config = {
  359. apiUrl: 'https://api.example.com',
  360. timeout: 5000,
  361. };
  362. `;
  363. const result = extractFromSource('config.ts', code);
  364. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  365. expect(varNode).toBeDefined();
  366. expect(varNode?.isExported).toBe(true);
  367. });
  368. it('should extract exported const with array literal', () => {
  369. const code = `
  370. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  371. `;
  372. const result = extractFromSource('constants.ts', code);
  373. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  374. expect(varNode).toBeDefined();
  375. expect(varNode?.isExported).toBe(true);
  376. });
  377. it('should extract exported const with primitive value', () => {
  378. const code = `
  379. export const MAX_RETRIES = 3;
  380. export const API_VERSION = "v2";
  381. `;
  382. const result = extractFromSource('constants.ts', code);
  383. const variables = result.nodes.filter((n) => n.kind === 'constant');
  384. expect(variables).toHaveLength(2);
  385. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  386. });
  387. it('should NOT duplicate arrow functions as both function and variable', () => {
  388. const code = `
  389. export const useAuth = () => {
  390. return useContext(AuthContext);
  391. };
  392. `;
  393. const result = extractFromSource('hooks.ts', code);
  394. // Should be extracted as function (from arrow function handler), NOT as variable
  395. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  396. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  397. expect(funcNodes).toHaveLength(1);
  398. expect(varNodes).toHaveLength(0);
  399. });
  400. it('should extract non-exported const as non-exported variable', () => {
  401. const code = `
  402. const internalConfig = {
  403. debug: true,
  404. };
  405. `;
  406. const result = extractFromSource('internal.ts', code);
  407. // Non-exported const at file level should be extracted as a constant (not exported)
  408. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  409. expect(varNodes).toHaveLength(1);
  410. expect(varNodes[0]?.isExported).toBeFalsy();
  411. });
  412. it('should extract Zod schema exports', () => {
  413. const code = `
  414. export const userSchema = z.object({
  415. id: z.string(),
  416. name: z.string(),
  417. email: z.string().email(),
  418. });
  419. `;
  420. const result = extractFromSource('schemas.ts', code);
  421. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  422. expect(varNode).toBeDefined();
  423. expect(varNode?.isExported).toBe(true);
  424. });
  425. it('should extract XState machine exports', () => {
  426. const code = `
  427. export const authMachine = createMachine({
  428. id: "auth",
  429. initial: "idle",
  430. states: {
  431. idle: {},
  432. authenticated: {},
  433. },
  434. });
  435. `;
  436. const result = extractFromSource('machine.ts', code);
  437. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  438. expect(varNode).toBeDefined();
  439. expect(varNode?.isExported).toBe(true);
  440. });
  441. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  442. const code = `
  443. import { getTokenMp } from './api/upload';
  444. const token = getTokenMp();
  445. `;
  446. const result = extractFromSource('app.ts', code);
  447. const call = result.unresolvedReferences.find(
  448. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  449. );
  450. expect(call).toBeDefined();
  451. });
  452. });
  453. describe('File Node Extraction', () => {
  454. it('should create a file-kind node for each parsed file', () => {
  455. const code = `
  456. export function greet(name: string): string {
  457. return "Hello " + name;
  458. }
  459. `;
  460. const result = extractFromSource('greeter.ts', code);
  461. const fileNode = result.nodes.find((n) => n.kind === 'file');
  462. expect(fileNode).toBeDefined();
  463. expect(fileNode?.name).toBe('greeter.ts');
  464. expect(fileNode?.filePath).toBe('greeter.ts');
  465. expect(fileNode?.language).toBe('typescript');
  466. expect(fileNode?.startLine).toBe(1);
  467. });
  468. it('should create file nodes for Python files', () => {
  469. const code = `
  470. def main():
  471. pass
  472. `;
  473. const result = extractFromSource('main.py', code);
  474. const fileNode = result.nodes.find((n) => n.kind === 'file');
  475. expect(fileNode).toBeDefined();
  476. expect(fileNode?.name).toBe('main.py');
  477. expect(fileNode?.language).toBe('python');
  478. });
  479. it('should create containment edges from file node to top-level declarations', () => {
  480. const code = `
  481. export function foo() {}
  482. export function bar() {}
  483. `;
  484. const result = extractFromSource('fns.ts', code);
  485. const fileNode = result.nodes.find((n) => n.kind === 'file');
  486. expect(fileNode).toBeDefined();
  487. // There should be contains edges from the file node to each function
  488. const containsEdges = result.edges.filter(
  489. (e) => e.source === fileNode?.id && e.kind === 'contains'
  490. );
  491. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  492. });
  493. });
  494. describe('Python Extraction', () => {
  495. it('should extract function definitions', () => {
  496. const code = `
  497. def calculate_total(items: list, tax_rate: float) -> float:
  498. """Calculate total with tax."""
  499. subtotal = sum(item.price for item in items)
  500. return subtotal * (1 + tax_rate)
  501. `;
  502. const result = extractFromSource('calc.py', code);
  503. const fileNode = result.nodes.find((n) => n.kind === 'file');
  504. expect(fileNode).toBeDefined();
  505. const funcNode = result.nodes.find((n) => n.kind === 'function');
  506. expect(funcNode).toMatchObject({
  507. kind: 'function',
  508. name: 'calculate_total',
  509. language: 'python',
  510. });
  511. });
  512. it('should extract class definitions', () => {
  513. const code = `
  514. class UserService:
  515. """Service for managing users."""
  516. def __init__(self, db):
  517. self.db = db
  518. def get_user(self, user_id: str) -> User:
  519. return self.db.find_user(user_id)
  520. `;
  521. const result = extractFromSource('service.py', code);
  522. const classNode = result.nodes.find((n) => n.kind === 'class');
  523. expect(classNode).toBeDefined();
  524. expect(classNode?.name).toBe('UserService');
  525. });
  526. });
  527. describe('Go Extraction', () => {
  528. it('should extract function declarations', () => {
  529. const code = `
  530. package main
  531. func ProcessOrder(order Order) (Receipt, error) {
  532. // Process the order
  533. return Receipt{}, nil
  534. }
  535. `;
  536. const result = extractFromSource('main.go', code);
  537. const funcNode = result.nodes.find((n) => n.kind === 'function');
  538. expect(funcNode).toBeDefined();
  539. expect(funcNode?.name).toBe('ProcessOrder');
  540. });
  541. it('should extract method declarations', () => {
  542. const code = `
  543. package main
  544. type Service struct {
  545. db *Database
  546. }
  547. func (s *Service) GetUser(id string) (*User, error) {
  548. return s.db.FindUser(id)
  549. }
  550. `;
  551. const result = extractFromSource('service.go', code);
  552. const methodNode = result.nodes.find((n) => n.kind === 'method');
  553. expect(methodNode).toBeDefined();
  554. expect(methodNode?.name).toBe('GetUser');
  555. });
  556. });
  557. describe('Rust Extraction', () => {
  558. it('should extract function declarations', () => {
  559. const code = `
  560. pub fn process_data(input: &str) -> Result<Output, Error> {
  561. // Process data
  562. Ok(Output::new())
  563. }
  564. `;
  565. const result = extractFromSource('lib.rs', code);
  566. const funcNode = result.nodes.find((n) => n.kind === 'function');
  567. expect(funcNode).toBeDefined();
  568. expect(funcNode?.name).toBe('process_data');
  569. expect(funcNode?.visibility).toBe('public');
  570. });
  571. it('should extract struct declarations', () => {
  572. const code = `
  573. pub struct User {
  574. pub id: String,
  575. pub name: String,
  576. email: String,
  577. }
  578. `;
  579. const result = extractFromSource('models.rs', code);
  580. const structNode = result.nodes.find((n) => n.kind === 'struct');
  581. expect(structNode).toBeDefined();
  582. expect(structNode?.name).toBe('User');
  583. });
  584. it('should extract trait declarations', () => {
  585. const code = `
  586. pub trait Repository {
  587. fn find(&self, id: &str) -> Option<Entity>;
  588. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  589. }
  590. `;
  591. const result = extractFromSource('traits.rs', code);
  592. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  593. expect(traitNode).toBeDefined();
  594. expect(traitNode?.name).toBe('Repository');
  595. });
  596. it('should extract impl Trait for Type as implements edges', () => {
  597. const code = `
  598. pub struct MyCache {}
  599. pub trait Cache {
  600. fn get(&self, key: &str) -> Option<String>;
  601. }
  602. impl Cache for MyCache {
  603. fn get(&self, key: &str) -> Option<String> {
  604. None
  605. }
  606. }
  607. `;
  608. const result = extractFromSource('cache.rs', code);
  609. // Should have an unresolved reference for implements
  610. const implRef = result.unresolvedReferences.find(
  611. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  612. );
  613. expect(implRef).toBeDefined();
  614. // The struct MyCache should be the source
  615. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  616. expect(myCacheNode).toBeDefined();
  617. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  618. });
  619. it('should extract trait supertraits as extends references', () => {
  620. const code = `
  621. pub trait Display {}
  622. pub trait Error: Display {
  623. fn description(&self) -> &str;
  624. }
  625. `;
  626. const result = extractFromSource('error.rs', code);
  627. const extendsRef = result.unresolvedReferences.find(
  628. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  629. );
  630. expect(extendsRef).toBeDefined();
  631. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  632. expect(errorTrait).toBeDefined();
  633. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  634. });
  635. it('should not create implements edges for plain impl blocks', () => {
  636. const code = `
  637. pub struct Counter {
  638. count: u32,
  639. }
  640. impl Counter {
  641. pub fn new() -> Counter {
  642. Counter { count: 0 }
  643. }
  644. pub fn increment(&mut self) {
  645. self.count += 1;
  646. }
  647. }
  648. `;
  649. const result = extractFromSource('counter.rs', code);
  650. // Should have no implements references (no trait involved)
  651. const implRefs = result.unresolvedReferences.filter(
  652. (r) => r.referenceKind === 'implements'
  653. );
  654. expect(implRefs).toHaveLength(0);
  655. });
  656. });
  657. describe('Java Extraction', () => {
  658. it('should extract class declarations', () => {
  659. const code = `
  660. public class UserService {
  661. private final UserRepository repository;
  662. public UserService(UserRepository repository) {
  663. this.repository = repository;
  664. }
  665. public User getUser(String id) {
  666. return repository.findById(id);
  667. }
  668. }
  669. `;
  670. const result = extractFromSource('UserService.java', code);
  671. const classNode = result.nodes.find((n) => n.kind === 'class');
  672. expect(classNode).toBeDefined();
  673. expect(classNode?.name).toBe('UserService');
  674. expect(classNode?.visibility).toBe('public');
  675. });
  676. it('should extract method declarations', () => {
  677. const code = `
  678. public class Calculator {
  679. public static int add(int a, int b) {
  680. return a + b;
  681. }
  682. }
  683. `;
  684. const result = extractFromSource('Calculator.java', code);
  685. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  686. expect(methodNode).toBeDefined();
  687. expect(methodNode?.isStatic).toBe(true);
  688. });
  689. });
  690. describe('C# Extraction', () => {
  691. it('should extract class declarations', () => {
  692. const code = `
  693. public class OrderService
  694. {
  695. private readonly IOrderRepository _repository;
  696. public OrderService(IOrderRepository repository)
  697. {
  698. _repository = repository;
  699. }
  700. public async Task<Order> GetOrderAsync(string id)
  701. {
  702. return await _repository.FindByIdAsync(id);
  703. }
  704. }
  705. `;
  706. const result = extractFromSource('OrderService.cs', code);
  707. const classNode = result.nodes.find((n) => n.kind === 'class');
  708. expect(classNode).toBeDefined();
  709. expect(classNode?.name).toBe('OrderService');
  710. expect(classNode?.visibility).toBe('public');
  711. });
  712. });
  713. describe('PHP Extraction', () => {
  714. it('should extract class declarations', () => {
  715. const code = `<?php
  716. class UserController
  717. {
  718. private UserService $userService;
  719. public function __construct(UserService $userService)
  720. {
  721. $this->userService = $userService;
  722. }
  723. public function show(string $id): User
  724. {
  725. return $this->userService->find($id);
  726. }
  727. }
  728. `;
  729. const result = extractFromSource('UserController.php', code);
  730. const classNode = result.nodes.find((n) => n.kind === 'class');
  731. expect(classNode).toBeDefined();
  732. expect(classNode?.name).toBe('UserController');
  733. });
  734. it('should extract class inheritance (extends) and interface implementation', () => {
  735. const code = `<?php
  736. class ChildController extends BaseController implements Serializable, JsonSerializable
  737. {
  738. public function serialize(): string
  739. {
  740. return json_encode($this);
  741. }
  742. }
  743. `;
  744. const result = extractFromSource('ChildController.php', code);
  745. const classNode = result.nodes.find((n) => n.kind === 'class');
  746. expect(classNode).toBeDefined();
  747. expect(classNode?.name).toBe('ChildController');
  748. const extendsRef = result.unresolvedReferences.find(
  749. (r) => r.referenceKind === 'extends'
  750. );
  751. expect(extendsRef).toBeDefined();
  752. expect(extendsRef?.referenceName).toBe('BaseController');
  753. const implementsRefs = result.unresolvedReferences.filter(
  754. (r) => r.referenceKind === 'implements'
  755. );
  756. expect(implementsRefs.length).toBe(2);
  757. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  758. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  759. });
  760. });
  761. describe('Swift Extraction', () => {
  762. it('should extract class declarations', () => {
  763. const code = `
  764. public class NetworkManager {
  765. private let session: URLSession
  766. public init(session: URLSession = .shared) {
  767. self.session = session
  768. }
  769. public func fetchData(from url: URL) async throws -> Data {
  770. let (data, _) = try await session.data(from: url)
  771. return data
  772. }
  773. }
  774. `;
  775. const result = extractFromSource('NetworkManager.swift', code);
  776. const classNode = result.nodes.find((n) => n.kind === 'class');
  777. expect(classNode).toBeDefined();
  778. expect(classNode?.name).toBe('NetworkManager');
  779. });
  780. it('should extract function declarations', () => {
  781. const code = `
  782. func calculateSum(_ numbers: [Int]) -> Int {
  783. return numbers.reduce(0, +)
  784. }
  785. public func formatCurrency(amount: Double) -> String {
  786. return String(format: "$%.2f", amount)
  787. }
  788. `;
  789. const result = extractFromSource('utils.swift', code);
  790. const functions = result.nodes.filter((n) => n.kind === 'function');
  791. expect(functions.length).toBeGreaterThanOrEqual(1);
  792. });
  793. it('should extract struct declarations', () => {
  794. const code = `
  795. public struct User {
  796. let id: UUID
  797. var name: String
  798. var email: String
  799. func displayName() -> String {
  800. return name
  801. }
  802. }
  803. `;
  804. const result = extractFromSource('User.swift', code);
  805. const structNode = result.nodes.find((n) => n.kind === 'struct');
  806. expect(structNode).toBeDefined();
  807. expect(structNode?.name).toBe('User');
  808. });
  809. it('should extract protocol declarations', () => {
  810. const code = `
  811. public protocol Repository {
  812. associatedtype Entity
  813. func find(id: String) async throws -> Entity?
  814. func save(_ entity: Entity) async throws
  815. }
  816. `;
  817. const result = extractFromSource('Repository.swift', code);
  818. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  819. expect(protocolNode).toBeDefined();
  820. expect(protocolNode?.name).toBe('Repository');
  821. });
  822. it('should extract class inheritance and protocol conformance', () => {
  823. const code = `
  824. class DataRequest: Request {
  825. func validate() {}
  826. }
  827. class UploadRequest: DataRequest, Sendable {
  828. func upload() {}
  829. }
  830. enum AFError: Error {
  831. case invalidURL
  832. }
  833. struct HTTPMethod: RawRepresentable {
  834. let rawValue: String
  835. }
  836. protocol UploadConvertible: URLRequestConvertible {
  837. func asURLRequest() throws -> URLRequest
  838. }
  839. `;
  840. const result = extractFromSource('Inheritance.swift', code);
  841. const extendsRefs = result.unresolvedReferences.filter(
  842. (r) => r.referenceKind === 'extends'
  843. );
  844. // DataRequest extends Request
  845. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  846. // UploadRequest extends DataRequest and Sendable
  847. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  848. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  849. // AFError extends Error
  850. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  851. // HTTPMethod extends RawRepresentable
  852. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  853. // UploadConvertible extends URLRequestConvertible
  854. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  855. });
  856. });
  857. describe('Kotlin Extraction', () => {
  858. it('should extract class declarations', () => {
  859. const code = `
  860. class UserRepository(private val database: Database) {
  861. fun findById(id: String): User? {
  862. return database.query("SELECT * FROM users WHERE id = ?", id)
  863. }
  864. suspend fun save(user: User) {
  865. database.insert(user)
  866. }
  867. }
  868. `;
  869. const result = extractFromSource('UserRepository.kt', code);
  870. const classNode = result.nodes.find((n) => n.kind === 'class');
  871. expect(classNode).toBeDefined();
  872. expect(classNode?.name).toBe('UserRepository');
  873. });
  874. it('should extract function declarations', () => {
  875. const code = `
  876. fun calculateTotal(items: List<Item>): Double {
  877. return items.sumOf { it.price }
  878. }
  879. suspend fun fetchUserData(userId: String): User {
  880. return api.getUser(userId)
  881. }
  882. `;
  883. const result = extractFromSource('utils.kt', code);
  884. const functions = result.nodes.filter((n) => n.kind === 'function');
  885. expect(functions.length).toBeGreaterThanOrEqual(1);
  886. });
  887. it('should detect suspend functions as async', () => {
  888. const code = `
  889. suspend fun loadData(): List<String> {
  890. delay(1000)
  891. return listOf("a", "b", "c")
  892. }
  893. `;
  894. const result = extractFromSource('loader.kt', code);
  895. const funcNode = result.nodes.find((n) => n.kind === 'function');
  896. expect(funcNode).toBeDefined();
  897. expect(funcNode?.isAsync).toBe(true);
  898. });
  899. it('should extract fun interface declarations', () => {
  900. const code = `
  901. fun interface OnObjectRetainedListener {
  902. fun onObjectRetained()
  903. }
  904. `;
  905. const result = extractFromSource('listener.kt', code);
  906. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  907. expect(ifaceNode).toBeDefined();
  908. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  909. const methodNode = result.nodes.find((n) => n.kind === 'method');
  910. expect(methodNode).toBeDefined();
  911. expect(methodNode?.name).toBe('onObjectRetained');
  912. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  913. });
  914. it('should extract complex fun interface with nested classes', () => {
  915. const code = `
  916. fun interface EventListener {
  917. fun onEvent(event: Event)
  918. sealed class Event {
  919. class DumpingHeap : Event()
  920. }
  921. }
  922. `;
  923. const result = extractFromSource('events.kt', code);
  924. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  925. expect(ifaceNode).toBeDefined();
  926. expect(ifaceNode?.name).toBe('EventListener');
  927. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  928. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  929. expect(eventClass).toBeDefined();
  930. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  931. expect(dumpingHeap).toBeDefined();
  932. });
  933. it('should not affect regular function declarations', () => {
  934. const code = `
  935. fun interface MyCallback {
  936. fun invoke(value: Int)
  937. }
  938. fun regularFunction(): String {
  939. return "hello"
  940. }
  941. `;
  942. const result = extractFromSource('mixed.kt', code);
  943. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  944. expect(ifaceNode).toBeDefined();
  945. expect(ifaceNode?.name).toBe('MyCallback');
  946. const funcNode = result.nodes.find((n) => n.kind === 'function');
  947. expect(funcNode).toBeDefined();
  948. expect(funcNode?.name).toBe('regularFunction');
  949. });
  950. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  951. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  952. // misparse: function_declaration > ERROR("interface Name {") instead of
  953. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  954. const code = `
  955. import java.io.IOException
  956. fun interface Interceptor {
  957. @Throws(IOException::class)
  958. fun intercept(chain: Chain): Response
  959. }
  960. `;
  961. const result = extractFromSource('interceptor.kt', code);
  962. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  963. expect(ifaceNode).toBeDefined();
  964. expect(ifaceNode?.name).toBe('Interceptor');
  965. });
  966. it('should extract methods from interface with nested fun interface', () => {
  967. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  968. // the parent body as ERROR. Methods inside should still be extracted.
  969. const code = `
  970. interface WebSocket {
  971. fun request(): Request
  972. fun send(text: String): Boolean
  973. fun cancel()
  974. fun interface Factory {
  975. fun newWebSocket(request: Request): WebSocket
  976. }
  977. }
  978. `;
  979. const result = extractFromSource('websocket.kt', code);
  980. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  981. expect(wsIface).toBeDefined();
  982. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  983. const methodNames = methods.map((m) => m.name);
  984. expect(methodNames).toContain('request');
  985. expect(methodNames).toContain('send');
  986. expect(methodNames).toContain('cancel');
  987. });
  988. });
  989. describe('Dart Extraction', () => {
  990. it('should extract class declarations', () => {
  991. const code = `
  992. class UserService {
  993. final Database _db;
  994. Future<User> findById(String id) async {
  995. return await _db.query(id);
  996. }
  997. void _privateMethod() {}
  998. }
  999. `;
  1000. const result = extractFromSource('service.dart', code);
  1001. const classNode = result.nodes.find((n) => n.kind === 'class');
  1002. expect(classNode).toBeDefined();
  1003. expect(classNode?.name).toBe('UserService');
  1004. expect(classNode?.visibility).toBe('public');
  1005. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1006. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1007. const findById = methodNodes.find((m) => m.name === 'findById');
  1008. expect(findById).toBeDefined();
  1009. expect(findById?.isAsync).toBe(true);
  1010. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1011. expect(privateMethod).toBeDefined();
  1012. expect(privateMethod?.visibility).toBe('private');
  1013. // Dart models a method body as a SIBLING of the signature, so the method
  1014. // node must be extended to span its body (not just the signature line) —
  1015. // required for body-level analysis (callees, the callback synthesizer).
  1016. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1017. });
  1018. it('should extract top-level function declarations', () => {
  1019. const code = `
  1020. void topLevelFunction(String name) {
  1021. print(name);
  1022. }
  1023. `;
  1024. const result = extractFromSource('utils.dart', code);
  1025. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1026. expect(funcNode).toBeDefined();
  1027. expect(funcNode?.name).toBe('topLevelFunction');
  1028. expect(funcNode?.language).toBe('dart');
  1029. });
  1030. it('should extract enum declarations', () => {
  1031. const code = `
  1032. enum Status { active, inactive, pending }
  1033. `;
  1034. const result = extractFromSource('models.dart', code);
  1035. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1036. expect(enumNode).toBeDefined();
  1037. expect(enumNode?.name).toBe('Status');
  1038. });
  1039. it('should extract mixin declarations', () => {
  1040. const code = `
  1041. mixin LoggerMixin {
  1042. void log(String message) {}
  1043. }
  1044. `;
  1045. const result = extractFromSource('mixins.dart', code);
  1046. const classNode = result.nodes.find((n) => n.kind === 'class');
  1047. expect(classNode).toBeDefined();
  1048. expect(classNode?.name).toBe('LoggerMixin');
  1049. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1050. expect(methodNode).toBeDefined();
  1051. expect(methodNode?.name).toBe('log');
  1052. });
  1053. it('should extract extension declarations', () => {
  1054. const code = `
  1055. extension StringExt on String {
  1056. bool get isBlank => trim().isEmpty;
  1057. }
  1058. `;
  1059. const result = extractFromSource('extensions.dart', code);
  1060. const classNode = result.nodes.find((n) => n.kind === 'class');
  1061. expect(classNode).toBeDefined();
  1062. expect(classNode?.name).toBe('StringExt');
  1063. });
  1064. it('should detect static methods', () => {
  1065. const code = `
  1066. class Utils {
  1067. static void doWork() {}
  1068. }
  1069. `;
  1070. const result = extractFromSource('utils.dart', code);
  1071. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1072. expect(methodNode).toBeDefined();
  1073. expect(methodNode?.name).toBe('doWork');
  1074. expect(methodNode?.isStatic).toBe(true);
  1075. });
  1076. it('should detect async functions', () => {
  1077. const code = `
  1078. Future<String> fetchData() async {
  1079. return await http.get('/data');
  1080. }
  1081. `;
  1082. const result = extractFromSource('api.dart', code);
  1083. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1084. expect(funcNode).toBeDefined();
  1085. expect(funcNode?.name).toBe('fetchData');
  1086. expect(funcNode?.isAsync).toBe(true);
  1087. });
  1088. it('should detect private visibility via underscore convention', () => {
  1089. const code = `
  1090. void _privateHelper() {}
  1091. void publicFunction() {}
  1092. `;
  1093. const result = extractFromSource('helpers.dart', code);
  1094. const functions = result.nodes.filter((n) => n.kind === 'function');
  1095. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1096. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1097. expect(privateFunc?.visibility).toBe('private');
  1098. expect(publicFunc?.visibility).toBe('public');
  1099. });
  1100. });
  1101. describe('Import Extraction', () => {
  1102. describe('TypeScript/JavaScript imports', () => {
  1103. it('should extract default imports', () => {
  1104. const code = `import React from 'react';`;
  1105. const result = extractFromSource('app.tsx', code);
  1106. const importNode = result.nodes.find((n) => n.kind === 'import');
  1107. expect(importNode).toBeDefined();
  1108. expect(importNode?.name).toBe('react');
  1109. expect(importNode?.signature).toBe("import React from 'react';");
  1110. });
  1111. it('should extract named imports', () => {
  1112. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1113. const result = extractFromSource('icons.tsx', code);
  1114. const importNode = result.nodes.find((n) => n.kind === 'import');
  1115. expect(importNode).toBeDefined();
  1116. expect(importNode?.name).toBe('@phosphor-icons/react');
  1117. expect(importNode?.signature).toContain('Bug');
  1118. expect(importNode?.signature).toContain('Database');
  1119. });
  1120. it('should extract namespace imports', () => {
  1121. const code = `import * as Icons from '@phosphor-icons/react';`;
  1122. const result = extractFromSource('icons.tsx', code);
  1123. const importNode = result.nodes.find((n) => n.kind === 'import');
  1124. expect(importNode).toBeDefined();
  1125. expect(importNode?.name).toBe('@phosphor-icons/react');
  1126. expect(importNode?.signature).toContain('* as Icons');
  1127. });
  1128. it('should extract side-effect imports', () => {
  1129. const code = `import './styles.css';`;
  1130. const result = extractFromSource('app.tsx', code);
  1131. const importNode = result.nodes.find((n) => n.kind === 'import');
  1132. expect(importNode).toBeDefined();
  1133. expect(importNode?.name).toBe('./styles.css');
  1134. });
  1135. it('should extract mixed imports (default + named)', () => {
  1136. const code = `import React, { useState, useEffect } from 'react';`;
  1137. const result = extractFromSource('app.tsx', code);
  1138. const importNode = result.nodes.find((n) => n.kind === 'import');
  1139. expect(importNode).toBeDefined();
  1140. expect(importNode?.name).toBe('react');
  1141. expect(importNode?.signature).toContain('React');
  1142. expect(importNode?.signature).toContain('useState');
  1143. expect(importNode?.signature).toContain('useEffect');
  1144. });
  1145. it('should extract multiple import statements', () => {
  1146. const code = `
  1147. import React from 'react';
  1148. import { Button } from './components';
  1149. import './styles.css';
  1150. `;
  1151. const result = extractFromSource('app.tsx', code);
  1152. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1153. expect(importNodes.length).toBe(3);
  1154. const names = importNodes.map((n) => n.name);
  1155. expect(names).toContain('react');
  1156. expect(names).toContain('./components');
  1157. expect(names).toContain('./styles.css');
  1158. });
  1159. it('should extract type imports', () => {
  1160. const code = `import type { FC, ReactNode } from 'react';`;
  1161. const result = extractFromSource('types.ts', code);
  1162. const importNode = result.nodes.find((n) => n.kind === 'import');
  1163. expect(importNode).toBeDefined();
  1164. expect(importNode?.name).toBe('react');
  1165. expect(importNode?.signature).toContain('type');
  1166. expect(importNode?.signature).toContain('FC');
  1167. });
  1168. it('should extract aliased named imports', () => {
  1169. const code = `import { useState as useStateAlias } from 'react';`;
  1170. const result = extractFromSource('hooks.ts', code);
  1171. const importNode = result.nodes.find((n) => n.kind === 'import');
  1172. expect(importNode).toBeDefined();
  1173. expect(importNode?.name).toBe('react');
  1174. expect(importNode?.signature).toContain('useState');
  1175. expect(importNode?.signature).toContain('useStateAlias');
  1176. });
  1177. it('should extract relative path imports', () => {
  1178. const code = `import { helper } from '../utils/helper';`;
  1179. const result = extractFromSource('components/Button.tsx', code);
  1180. const importNode = result.nodes.find((n) => n.kind === 'import');
  1181. expect(importNode).toBeDefined();
  1182. expect(importNode?.name).toBe('../utils/helper');
  1183. expect(importNode?.signature).toContain('helper');
  1184. });
  1185. });
  1186. describe('Python imports', () => {
  1187. it('should extract simple import statement', () => {
  1188. const code = `import json`;
  1189. const result = extractFromSource('utils.py', code);
  1190. const importNode = result.nodes.find((n) => n.kind === 'import');
  1191. expect(importNode).toBeDefined();
  1192. expect(importNode?.name).toBe('json');
  1193. });
  1194. it('should extract from import statement', () => {
  1195. const code = `from os import path`;
  1196. const result = extractFromSource('utils.py', code);
  1197. const importNode = result.nodes.find((n) => n.kind === 'import');
  1198. expect(importNode).toBeDefined();
  1199. expect(importNode?.name).toBe('os');
  1200. expect(importNode?.signature).toContain('path');
  1201. });
  1202. it('should extract multiple imports from same module', () => {
  1203. const code = `from typing import List, Dict, Optional`;
  1204. const result = extractFromSource('types.py', code);
  1205. const importNode = result.nodes.find((n) => n.kind === 'import');
  1206. expect(importNode).toBeDefined();
  1207. expect(importNode?.name).toBe('typing');
  1208. expect(importNode?.signature).toContain('List');
  1209. expect(importNode?.signature).toContain('Dict');
  1210. });
  1211. it('should extract multiple import statements', () => {
  1212. const code = `
  1213. import os
  1214. import sys
  1215. `;
  1216. const result = extractFromSource('main.py', code);
  1217. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1218. expect(importNodes.length).toBe(2);
  1219. const names = importNodes.map((n) => n.name);
  1220. expect(names).toContain('os');
  1221. expect(names).toContain('sys');
  1222. });
  1223. it('should extract aliased import', () => {
  1224. const code = `import numpy as np`;
  1225. const result = extractFromSource('data.py', code);
  1226. const importNode = result.nodes.find((n) => n.kind === 'import');
  1227. expect(importNode).toBeDefined();
  1228. expect(importNode?.name).toBe('numpy');
  1229. expect(importNode?.signature).toContain('as np');
  1230. });
  1231. it('should extract relative import', () => {
  1232. const code = `from .utils import helper`;
  1233. const result = extractFromSource('module.py', code);
  1234. const importNode = result.nodes.find((n) => n.kind === 'import');
  1235. expect(importNode).toBeDefined();
  1236. expect(importNode?.name).toBe('.utils');
  1237. expect(importNode?.signature).toContain('helper');
  1238. });
  1239. it('should extract wildcard import', () => {
  1240. const code = `from typing import *`;
  1241. const result = extractFromSource('types.py', code);
  1242. const importNode = result.nodes.find((n) => n.kind === 'import');
  1243. expect(importNode).toBeDefined();
  1244. expect(importNode?.name).toBe('typing');
  1245. expect(importNode?.signature).toContain('*');
  1246. });
  1247. });
  1248. describe('Rust imports', () => {
  1249. it('should extract simple use declaration', () => {
  1250. const code = `use std::io;`;
  1251. const result = extractFromSource('main.rs', code);
  1252. const importNode = result.nodes.find((n) => n.kind === 'import');
  1253. expect(importNode).toBeDefined();
  1254. expect(importNode?.name).toBe('std');
  1255. expect(importNode?.signature).toBe('use std::io;');
  1256. });
  1257. it('should extract scoped use list', () => {
  1258. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1259. const result = extractFromSource('main.rs', code);
  1260. const importNode = result.nodes.find((n) => n.kind === 'import');
  1261. expect(importNode).toBeDefined();
  1262. expect(importNode?.name).toBe('std');
  1263. expect(importNode?.signature).toContain('ffi::OsStr');
  1264. expect(importNode?.signature).toContain('path::Path');
  1265. });
  1266. it('should extract crate imports', () => {
  1267. const code = `use crate::error::Error;`;
  1268. const result = extractFromSource('lib.rs', code);
  1269. const importNode = result.nodes.find((n) => n.kind === 'import');
  1270. expect(importNode).toBeDefined();
  1271. expect(importNode?.name).toBe('crate');
  1272. });
  1273. it('should extract super imports', () => {
  1274. const code = `use super::utils;`;
  1275. const result = extractFromSource('submod.rs', code);
  1276. const importNode = result.nodes.find((n) => n.kind === 'import');
  1277. expect(importNode).toBeDefined();
  1278. expect(importNode?.name).toBe('super');
  1279. });
  1280. it('should extract external crate imports', () => {
  1281. const code = `use serde::{Serialize, Deserialize};`;
  1282. const result = extractFromSource('types.rs', code);
  1283. const importNode = result.nodes.find((n) => n.kind === 'import');
  1284. expect(importNode).toBeDefined();
  1285. expect(importNode?.name).toBe('serde');
  1286. expect(importNode?.signature).toContain('Serialize');
  1287. expect(importNode?.signature).toContain('Deserialize');
  1288. });
  1289. });
  1290. describe('Go imports', () => {
  1291. it('should extract single import', () => {
  1292. const code = `
  1293. package main
  1294. import "fmt"
  1295. `;
  1296. const result = extractFromSource('main.go', code);
  1297. const importNode = result.nodes.find((n) => n.kind === 'import');
  1298. expect(importNode).toBeDefined();
  1299. expect(importNode?.name).toBe('fmt');
  1300. });
  1301. it('should extract grouped imports', () => {
  1302. const code = `
  1303. package main
  1304. import (
  1305. "fmt"
  1306. "os"
  1307. "encoding/json"
  1308. )
  1309. `;
  1310. const result = extractFromSource('main.go', code);
  1311. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1312. expect(importNodes.length).toBe(3);
  1313. const names = importNodes.map((n) => n.name);
  1314. expect(names).toContain('fmt');
  1315. expect(names).toContain('os');
  1316. expect(names).toContain('encoding/json');
  1317. });
  1318. it('should extract aliased import', () => {
  1319. const code = `
  1320. package main
  1321. import f "fmt"
  1322. `;
  1323. const result = extractFromSource('main.go', code);
  1324. const importNode = result.nodes.find((n) => n.kind === 'import');
  1325. expect(importNode).toBeDefined();
  1326. expect(importNode?.name).toBe('fmt');
  1327. expect(importNode?.signature).toContain('f');
  1328. });
  1329. it('should extract dot import', () => {
  1330. const code = `
  1331. package main
  1332. import . "math"
  1333. `;
  1334. const result = extractFromSource('main.go', code);
  1335. const importNode = result.nodes.find((n) => n.kind === 'import');
  1336. expect(importNode).toBeDefined();
  1337. expect(importNode?.name).toBe('math');
  1338. expect(importNode?.signature).toContain('.');
  1339. });
  1340. it('should extract blank import', () => {
  1341. const code = `
  1342. package main
  1343. import _ "github.com/go-sql-driver/mysql"
  1344. `;
  1345. const result = extractFromSource('main.go', code);
  1346. const importNode = result.nodes.find((n) => n.kind === 'import');
  1347. expect(importNode).toBeDefined();
  1348. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1349. expect(importNode?.signature).toContain('_');
  1350. });
  1351. });
  1352. describe('Swift imports', () => {
  1353. it('should extract simple import', () => {
  1354. const code = `import Foundation`;
  1355. const result = extractFromSource('main.swift', code);
  1356. const importNode = result.nodes.find((n) => n.kind === 'import');
  1357. expect(importNode).toBeDefined();
  1358. expect(importNode?.name).toBe('Foundation');
  1359. expect(importNode?.signature).toBe('import Foundation');
  1360. });
  1361. it('should extract @testable import', () => {
  1362. const code = `@testable import Alamofire`;
  1363. const result = extractFromSource('Tests.swift', code);
  1364. const importNode = result.nodes.find((n) => n.kind === 'import');
  1365. expect(importNode).toBeDefined();
  1366. expect(importNode?.name).toBe('Alamofire');
  1367. expect(importNode?.signature).toContain('@testable');
  1368. });
  1369. it('should extract @preconcurrency import', () => {
  1370. const code = `@preconcurrency import Security`;
  1371. const result = extractFromSource('Auth.swift', code);
  1372. const importNode = result.nodes.find((n) => n.kind === 'import');
  1373. expect(importNode).toBeDefined();
  1374. expect(importNode?.name).toBe('Security');
  1375. });
  1376. it('should extract multiple imports', () => {
  1377. const code = `
  1378. import Foundation
  1379. import UIKit
  1380. import Alamofire
  1381. `;
  1382. const result = extractFromSource('App.swift', code);
  1383. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1384. expect(importNodes.length).toBe(3);
  1385. const names = importNodes.map((n) => n.name);
  1386. expect(names).toContain('Foundation');
  1387. expect(names).toContain('UIKit');
  1388. expect(names).toContain('Alamofire');
  1389. });
  1390. });
  1391. describe('Kotlin imports', () => {
  1392. it('should extract simple import', () => {
  1393. const code = `import java.io.IOException`;
  1394. const result = extractFromSource('Main.kt', code);
  1395. const importNode = result.nodes.find((n) => n.kind === 'import');
  1396. expect(importNode).toBeDefined();
  1397. expect(importNode?.name).toBe('java.io.IOException');
  1398. expect(importNode?.signature).toBe('import java.io.IOException');
  1399. });
  1400. it('should extract aliased import', () => {
  1401. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1402. const result = extractFromSource('Utils.kt', code);
  1403. const importNode = result.nodes.find((n) => n.kind === 'import');
  1404. expect(importNode).toBeDefined();
  1405. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1406. expect(importNode?.signature).toContain('as RequestBuilder');
  1407. });
  1408. it('should extract wildcard import', () => {
  1409. const code = `import java.util.concurrent.TimeUnit.*`;
  1410. const result = extractFromSource('Time.kt', code);
  1411. const importNode = result.nodes.find((n) => n.kind === 'import');
  1412. expect(importNode).toBeDefined();
  1413. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1414. expect(importNode?.signature).toContain('.*');
  1415. });
  1416. it('should extract multiple imports', () => {
  1417. const code = `
  1418. import java.io.IOException
  1419. import kotlin.test.assertFailsWith
  1420. import okhttp3.OkHttpClient
  1421. `;
  1422. const result = extractFromSource('Test.kt', code);
  1423. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1424. expect(importNodes.length).toBe(3);
  1425. const names = importNodes.map((n) => n.name);
  1426. expect(names).toContain('java.io.IOException');
  1427. expect(names).toContain('kotlin.test.assertFailsWith');
  1428. expect(names).toContain('okhttp3.OkHttpClient');
  1429. });
  1430. });
  1431. describe('Java imports', () => {
  1432. it('should extract simple import', () => {
  1433. const code = `import java.util.List;`;
  1434. const result = extractFromSource('Main.java', code);
  1435. const importNode = result.nodes.find((n) => n.kind === 'import');
  1436. expect(importNode).toBeDefined();
  1437. expect(importNode?.name).toBe('java.util.List');
  1438. expect(importNode?.signature).toBe('import java.util.List;');
  1439. });
  1440. it('should extract static import', () => {
  1441. const code = `import static java.util.Collections.emptyList;`;
  1442. const result = extractFromSource('Utils.java', code);
  1443. const importNode = result.nodes.find((n) => n.kind === 'import');
  1444. expect(importNode).toBeDefined();
  1445. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1446. expect(importNode?.signature).toContain('static');
  1447. });
  1448. it('should extract wildcard import', () => {
  1449. const code = `import java.util.*;`;
  1450. const result = extractFromSource('App.java', code);
  1451. const importNode = result.nodes.find((n) => n.kind === 'import');
  1452. expect(importNode).toBeDefined();
  1453. expect(importNode?.name).toBe('java.util');
  1454. expect(importNode?.signature).toContain('.*');
  1455. });
  1456. it('should extract nested class import', () => {
  1457. const code = `import java.util.Map.Entry;`;
  1458. const result = extractFromSource('MapUtil.java', code);
  1459. const importNode = result.nodes.find((n) => n.kind === 'import');
  1460. expect(importNode).toBeDefined();
  1461. expect(importNode?.name).toBe('java.util.Map.Entry');
  1462. });
  1463. it('should extract multiple imports', () => {
  1464. const code = `
  1465. import java.util.List;
  1466. import java.util.Map;
  1467. import java.io.IOException;
  1468. `;
  1469. const result = extractFromSource('Service.java', code);
  1470. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1471. expect(importNodes.length).toBe(3);
  1472. const names = importNodes.map((n) => n.name);
  1473. expect(names).toContain('java.util.List');
  1474. expect(names).toContain('java.util.Map');
  1475. expect(names).toContain('java.io.IOException');
  1476. });
  1477. });
  1478. describe('C# imports', () => {
  1479. it('should extract simple using', () => {
  1480. const code = `using System;`;
  1481. const result = extractFromSource('Program.cs', code);
  1482. const importNode = result.nodes.find((n) => n.kind === 'import');
  1483. expect(importNode).toBeDefined();
  1484. expect(importNode?.name).toBe('System');
  1485. expect(importNode?.signature).toBe('using System;');
  1486. });
  1487. it('should extract qualified using', () => {
  1488. const code = `using System.Collections.Generic;`;
  1489. const result = extractFromSource('Utils.cs', code);
  1490. const importNode = result.nodes.find((n) => n.kind === 'import');
  1491. expect(importNode).toBeDefined();
  1492. expect(importNode?.name).toBe('System.Collections.Generic');
  1493. });
  1494. it('should extract static using', () => {
  1495. const code = `using static System.Console;`;
  1496. const result = extractFromSource('App.cs', code);
  1497. const importNode = result.nodes.find((n) => n.kind === 'import');
  1498. expect(importNode).toBeDefined();
  1499. expect(importNode?.name).toBe('System.Console');
  1500. expect(importNode?.signature).toContain('static');
  1501. });
  1502. it('should extract alias using', () => {
  1503. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1504. const result = extractFromSource('Types.cs', code);
  1505. const importNode = result.nodes.find((n) => n.kind === 'import');
  1506. expect(importNode).toBeDefined();
  1507. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1508. expect(importNode?.signature).toContain('MyList =');
  1509. });
  1510. it('should extract multiple usings', () => {
  1511. const code = `
  1512. using System;
  1513. using System.Threading.Tasks;
  1514. using Microsoft.Extensions.DependencyInjection;
  1515. `;
  1516. const result = extractFromSource('Service.cs', code);
  1517. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1518. expect(importNodes.length).toBe(3);
  1519. const names = importNodes.map((n) => n.name);
  1520. expect(names).toContain('System');
  1521. expect(names).toContain('System.Threading.Tasks');
  1522. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1523. });
  1524. });
  1525. describe('PHP imports', () => {
  1526. it('should extract simple use', () => {
  1527. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1528. const result = extractFromSource('Test.php', code);
  1529. const importNode = result.nodes.find((n) => n.kind === 'import');
  1530. expect(importNode).toBeDefined();
  1531. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1532. });
  1533. it('should extract aliased use', () => {
  1534. const code = `<?php use Mockery as m;`;
  1535. const result = extractFromSource('Test.php', code);
  1536. const importNode = result.nodes.find((n) => n.kind === 'import');
  1537. expect(importNode).toBeDefined();
  1538. expect(importNode?.name).toBe('Mockery');
  1539. expect(importNode?.signature).toContain('as m');
  1540. });
  1541. it('should extract function use', () => {
  1542. const code = `<?php use function Illuminate\\Support\\env;`;
  1543. const result = extractFromSource('helpers.php', code);
  1544. const importNode = result.nodes.find((n) => n.kind === 'import');
  1545. expect(importNode).toBeDefined();
  1546. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1547. expect(importNode?.signature).toContain('function');
  1548. });
  1549. it('should extract grouped use', () => {
  1550. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1551. const result = extractFromSource('Models.php', code);
  1552. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1553. expect(importNodes.length).toBe(2);
  1554. const names = importNodes.map((n) => n.name);
  1555. expect(names).toContain('Illuminate\\Database\\Model');
  1556. expect(names).toContain('Illuminate\\Database\\Builder');
  1557. });
  1558. it('should extract multiple uses', () => {
  1559. const code = `<?php
  1560. use Illuminate\\Support\\Collection;
  1561. use Illuminate\\Support\\Str;
  1562. use Closure;
  1563. `;
  1564. const result = extractFromSource('Service.php', code);
  1565. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1566. expect(importNodes.length).toBe(3);
  1567. const names = importNodes.map((n) => n.name);
  1568. expect(names).toContain('Illuminate\\Support\\Collection');
  1569. expect(names).toContain('Illuminate\\Support\\Str');
  1570. expect(names).toContain('Closure');
  1571. });
  1572. });
  1573. describe('Ruby imports', () => {
  1574. it('should extract require', () => {
  1575. const code = `require 'json'`;
  1576. const result = extractFromSource('app.rb', code);
  1577. const importNode = result.nodes.find((n) => n.kind === 'import');
  1578. expect(importNode).toBeDefined();
  1579. expect(importNode?.name).toBe('json');
  1580. expect(importNode?.signature).toBe("require 'json'");
  1581. });
  1582. it('should extract require with path', () => {
  1583. const code = `require 'active_support/core_ext/string'`;
  1584. const result = extractFromSource('config.rb', code);
  1585. const importNode = result.nodes.find((n) => n.kind === 'import');
  1586. expect(importNode).toBeDefined();
  1587. expect(importNode?.name).toBe('active_support/core_ext/string');
  1588. });
  1589. it('should extract require_relative', () => {
  1590. const code = `require_relative '../test_helper'`;
  1591. const result = extractFromSource('test/my_test.rb', code);
  1592. const importNode = result.nodes.find((n) => n.kind === 'import');
  1593. expect(importNode).toBeDefined();
  1594. expect(importNode?.name).toBe('../test_helper');
  1595. expect(importNode?.signature).toContain('require_relative');
  1596. });
  1597. it('should not extract non-require calls', () => {
  1598. const code = `puts 'hello'`;
  1599. const result = extractFromSource('app.rb', code);
  1600. const importNode = result.nodes.find((n) => n.kind === 'import');
  1601. expect(importNode).toBeUndefined();
  1602. });
  1603. it('should extract multiple requires', () => {
  1604. const code = `
  1605. require 'json'
  1606. require 'yaml'
  1607. require_relative 'helper'
  1608. `;
  1609. const result = extractFromSource('lib.rb', code);
  1610. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1611. expect(importNodes.length).toBe(3);
  1612. const names = importNodes.map((n) => n.name);
  1613. expect(names).toContain('json');
  1614. expect(names).toContain('yaml');
  1615. expect(names).toContain('helper');
  1616. });
  1617. });
  1618. describe('Ruby modules', () => {
  1619. it('should extract module as module node with containment', () => {
  1620. const code = `
  1621. module CachedCounting
  1622. def self.disable
  1623. @enabled = false
  1624. end
  1625. def perform_increment!(key, count)
  1626. write_cache!(key, count)
  1627. end
  1628. end
  1629. `;
  1630. const result = extractFromSource('concerns/cached_counting.rb', code);
  1631. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1632. expect(moduleNode).toBeDefined();
  1633. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1634. // Methods inside module should have module-qualified names
  1635. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1636. expect(disableMethod).toBeDefined();
  1637. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1638. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1639. expect(incrementMethod).toBeDefined();
  1640. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1641. // Containment edge from module to methods
  1642. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1643. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1644. });
  1645. it('should handle nested modules with classes', () => {
  1646. const code = `
  1647. module Discourse
  1648. module Auth
  1649. class AuthProvider
  1650. def authenticate(params)
  1651. validate(params)
  1652. end
  1653. end
  1654. end
  1655. end
  1656. `;
  1657. const result = extractFromSource('lib/auth.rb', code);
  1658. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1659. expect(discourseModule).toBeDefined();
  1660. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1661. expect(authModule).toBeDefined();
  1662. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1663. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1664. expect(authProvider).toBeDefined();
  1665. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1666. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1667. expect(authMethod).toBeDefined();
  1668. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1669. });
  1670. });
  1671. describe('C/C++ imports', () => {
  1672. it('should extract system include', () => {
  1673. const code = `#include <iostream>`;
  1674. const result = extractFromSource('main.cpp', code);
  1675. const importNode = result.nodes.find((n) => n.kind === 'import');
  1676. expect(importNode).toBeDefined();
  1677. expect(importNode?.name).toBe('iostream');
  1678. expect(importNode?.signature).toBe('#include <iostream>');
  1679. });
  1680. it('should extract system include with path', () => {
  1681. const code = `#include <nlohmann/json.hpp>`;
  1682. const result = extractFromSource('app.cpp', code);
  1683. const importNode = result.nodes.find((n) => n.kind === 'import');
  1684. expect(importNode).toBeDefined();
  1685. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1686. });
  1687. it('should extract local include', () => {
  1688. const code = `#include "myheader.h"`;
  1689. const result = extractFromSource('main.cpp', code);
  1690. const importNode = result.nodes.find((n) => n.kind === 'import');
  1691. expect(importNode).toBeDefined();
  1692. expect(importNode?.name).toBe('myheader.h');
  1693. });
  1694. it('should extract C header', () => {
  1695. const code = `#include <stdio.h>`;
  1696. const result = extractFromSource('main.c', code);
  1697. const importNode = result.nodes.find((n) => n.kind === 'import');
  1698. expect(importNode).toBeDefined();
  1699. expect(importNode?.name).toBe('stdio.h');
  1700. });
  1701. it('should extract multiple includes', () => {
  1702. const code = `
  1703. #include <iostream>
  1704. #include <vector>
  1705. #include "config.h"
  1706. `;
  1707. const result = extractFromSource('app.cpp', code);
  1708. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1709. expect(importNodes.length).toBe(3);
  1710. const names = importNodes.map((n) => n.name);
  1711. expect(names).toContain('iostream');
  1712. expect(names).toContain('vector');
  1713. expect(names).toContain('config.h');
  1714. });
  1715. it('should create unresolved references for local includes', () => {
  1716. const code = `#include "myheader.h"`;
  1717. const result = extractFromSource('main.cpp', code);
  1718. const importRef = result.unresolvedReferences.find(
  1719. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  1720. );
  1721. expect(importRef).toBeDefined();
  1722. expect(importRef?.line).toBe(1);
  1723. });
  1724. it('should create unresolved references for system includes', () => {
  1725. const code = `#include <iostream>`;
  1726. const result = extractFromSource('main.cpp', code);
  1727. const importRef = result.unresolvedReferences.find(
  1728. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  1729. );
  1730. expect(importRef).toBeDefined();
  1731. });
  1732. });
  1733. describe('Dart imports', () => {
  1734. it('should extract dart: import', () => {
  1735. const code = `import 'dart:async';`;
  1736. const result = extractFromSource('main.dart', code);
  1737. const importNode = result.nodes.find((n) => n.kind === 'import');
  1738. expect(importNode).toBeDefined();
  1739. expect(importNode?.name).toBe('dart:async');
  1740. expect(importNode?.signature).toBe("import 'dart:async';");
  1741. });
  1742. it('should extract package import', () => {
  1743. const code = `import 'package:flutter/material.dart';`;
  1744. const result = extractFromSource('app.dart', code);
  1745. const importNode = result.nodes.find((n) => n.kind === 'import');
  1746. expect(importNode).toBeDefined();
  1747. expect(importNode?.name).toBe('package:flutter/material.dart');
  1748. });
  1749. it('should extract aliased import', () => {
  1750. const code = `import 'package:http/http.dart' as http;`;
  1751. const result = extractFromSource('api.dart', code);
  1752. const importNode = result.nodes.find((n) => n.kind === 'import');
  1753. expect(importNode).toBeDefined();
  1754. expect(importNode?.name).toBe('package:http/http.dart');
  1755. expect(importNode?.signature).toContain('as http');
  1756. });
  1757. it('should extract multiple imports', () => {
  1758. const code = `
  1759. import 'dart:async';
  1760. import 'dart:convert';
  1761. import 'package:flutter/material.dart';
  1762. `;
  1763. const result = extractFromSource('main.dart', code);
  1764. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1765. expect(importNodes.length).toBe(3);
  1766. const names = importNodes.map((n) => n.name);
  1767. expect(names).toContain('dart:async');
  1768. expect(names).toContain('dart:convert');
  1769. expect(names).toContain('package:flutter/material.dart');
  1770. });
  1771. it('should extract relative import', () => {
  1772. const code = `import '../utils/helpers.dart';`;
  1773. const result = extractFromSource('lib/main.dart', code);
  1774. const importNode = result.nodes.find((n) => n.kind === 'import');
  1775. expect(importNode).toBeDefined();
  1776. expect(importNode?.name).toBe('../utils/helpers.dart');
  1777. });
  1778. });
  1779. describe('Liquid imports', () => {
  1780. it('should extract render tag', () => {
  1781. const code = `{% render 'loading-spinner' %}`;
  1782. const result = extractFromSource('template.liquid', code);
  1783. const importNode = result.nodes.find((n) => n.kind === 'import');
  1784. expect(importNode).toBeDefined();
  1785. expect(importNode?.name).toBe('loading-spinner');
  1786. expect(importNode?.signature).toContain('render');
  1787. });
  1788. it('should extract section tag', () => {
  1789. const code = `{% section 'header' %}`;
  1790. const result = extractFromSource('layout/theme.liquid', code);
  1791. const importNode = result.nodes.find((n) => n.kind === 'import');
  1792. expect(importNode).toBeDefined();
  1793. expect(importNode?.name).toBe('header');
  1794. expect(importNode?.signature).toContain('section');
  1795. });
  1796. it('should extract include tag', () => {
  1797. const code = `{% include 'icon-cart' %}`;
  1798. const result = extractFromSource('snippets/header.liquid', code);
  1799. const importNode = result.nodes.find((n) => n.kind === 'import');
  1800. expect(importNode).toBeDefined();
  1801. expect(importNode?.name).toBe('icon-cart');
  1802. expect(importNode?.signature).toContain('include');
  1803. });
  1804. it('should extract render with whitespace control', () => {
  1805. const code = `{%- render 'price' -%}`;
  1806. const result = extractFromSource('snippets/product.liquid', code);
  1807. const importNode = result.nodes.find((n) => n.kind === 'import');
  1808. expect(importNode).toBeDefined();
  1809. expect(importNode?.name).toBe('price');
  1810. });
  1811. it('should extract multiple imports', () => {
  1812. const code = `
  1813. {% section 'header' %}
  1814. {% render 'loading-spinner' %}
  1815. {% render 'cart-drawer' %}
  1816. `;
  1817. const result = extractFromSource('layout/theme.liquid', code);
  1818. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1819. expect(importNodes.length).toBe(3);
  1820. const names = importNodes.map((n) => n.name);
  1821. expect(names).toContain('header');
  1822. expect(names).toContain('loading-spinner');
  1823. expect(names).toContain('cart-drawer');
  1824. });
  1825. });
  1826. });
  1827. // =============================================================================
  1828. // Pascal / Delphi Extraction
  1829. // =============================================================================
  1830. describe('Pascal / Delphi Extraction', () => {
  1831. describe('Language detection', () => {
  1832. it('should detect Pascal files', () => {
  1833. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  1834. expect(detectLanguage('App.dpr')).toBe('pascal');
  1835. expect(detectLanguage('Package.dpk')).toBe('pascal');
  1836. expect(detectLanguage('App.lpr')).toBe('pascal');
  1837. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  1838. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  1839. });
  1840. it('should report Pascal as supported', () => {
  1841. expect(isLanguageSupported('pascal')).toBe(true);
  1842. expect(getSupportedLanguages()).toContain('pascal');
  1843. });
  1844. });
  1845. describe('Unit extraction', () => {
  1846. it('should extract unit as module', () => {
  1847. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  1848. const result = extractFromSource('MyUnit.pas', code);
  1849. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1850. expect(moduleNode).toBeDefined();
  1851. expect(moduleNode?.name).toBe('MyUnit');
  1852. expect(moduleNode?.language).toBe('pascal');
  1853. });
  1854. it('should extract program as module', () => {
  1855. const code = `program MyApp;\nbegin\nend.`;
  1856. const result = extractFromSource('MyApp.dpr', code);
  1857. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1858. expect(moduleNode).toBeDefined();
  1859. expect(moduleNode?.name).toBe('MyApp');
  1860. });
  1861. it('should fallback to filename when module name is empty', () => {
  1862. // Some .dpr templates use "program;" without a name
  1863. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  1864. const result = extractFromSource('Console.dpr', code);
  1865. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1866. expect(moduleNode).toBeDefined();
  1867. expect(moduleNode?.name).toBe('Console');
  1868. });
  1869. });
  1870. describe('Uses clause (imports)', () => {
  1871. it('should extract uses as individual imports', () => {
  1872. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  1873. const result = extractFromSource('Test.pas', code);
  1874. const imports = result.nodes.filter((n) => n.kind === 'import');
  1875. expect(imports.length).toBe(2);
  1876. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  1877. expect(imports.map((n) => n.name)).toContain('System.Classes');
  1878. });
  1879. it('should create unresolved references for imports', () => {
  1880. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  1881. const result = extractFromSource('Test.pas', code);
  1882. const importRef = result.unresolvedReferences.find(
  1883. (r) => r.referenceKind === 'imports'
  1884. );
  1885. expect(importRef).toBeDefined();
  1886. expect(importRef?.referenceName).toBe('UAuth');
  1887. });
  1888. });
  1889. describe('Class extraction', () => {
  1890. it('should extract class declarations', () => {
  1891. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  1892. const result = extractFromSource('Test.pas', code);
  1893. const classNode = result.nodes.find((n) => n.kind === 'class');
  1894. expect(classNode).toBeDefined();
  1895. expect(classNode?.name).toBe('TMyClass');
  1896. });
  1897. it('should extract class with inheritance', () => {
  1898. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  1899. const result = extractFromSource('Test.pas', code);
  1900. const extendsRef = result.unresolvedReferences.find(
  1901. (r) => r.referenceKind === 'extends'
  1902. );
  1903. expect(extendsRef).toBeDefined();
  1904. expect(extendsRef?.referenceName).toBe('TParent');
  1905. });
  1906. it('should extract class with interface implementation', () => {
  1907. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  1908. const result = extractFromSource('Test.pas', code);
  1909. const extendsRef = result.unresolvedReferences.find(
  1910. (r) => r.referenceKind === 'extends'
  1911. );
  1912. const implementsRef = result.unresolvedReferences.find(
  1913. (r) => r.referenceKind === 'implements'
  1914. );
  1915. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1916. expect(implementsRef?.referenceName).toBe('ILogger');
  1917. });
  1918. });
  1919. describe('Record extraction', () => {
  1920. it('should extract records as class nodes', () => {
  1921. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  1922. const result = extractFromSource('Test.pas', code);
  1923. const classNode = result.nodes.find((n) => n.kind === 'class');
  1924. expect(classNode).toBeDefined();
  1925. expect(classNode?.name).toBe('TPoint');
  1926. const fields = result.nodes.filter((n) => n.kind === 'field');
  1927. expect(fields.length).toBe(2);
  1928. expect(fields.map((f) => f.name)).toContain('X');
  1929. expect(fields.map((f) => f.name)).toContain('Y');
  1930. });
  1931. });
  1932. describe('Interface extraction', () => {
  1933. it('should extract interface declarations', () => {
  1934. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  1935. const result = extractFromSource('Test.pas', code);
  1936. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1937. expect(ifaceNode).toBeDefined();
  1938. expect(ifaceNode?.name).toBe('ILogger');
  1939. });
  1940. });
  1941. describe('Method extraction', () => {
  1942. it('should extract methods with visibility', () => {
  1943. 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.`;
  1944. const result = extractFromSource('Test.pas', code);
  1945. const methods = result.nodes.filter((n) => n.kind === 'method');
  1946. expect(methods.length).toBe(2);
  1947. const createMethod = methods.find((m) => m.name === 'Create');
  1948. expect(createMethod?.visibility).toBe('public');
  1949. const getValue = methods.find((m) => m.name === 'GetValue');
  1950. expect(getValue?.visibility).toBe('public');
  1951. const fields = result.nodes.filter((n) => n.kind === 'field');
  1952. const fValue = fields.find((f) => f.name === 'FValue');
  1953. expect(fValue?.visibility).toBe('private');
  1954. });
  1955. it('should detect static methods (class methods)', () => {
  1956. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  1957. const result = extractFromSource('Test.pas', code);
  1958. const methods = result.nodes.filter((n) => n.kind === 'method');
  1959. const staticMethod = methods.find((m) => m.name === 'Create');
  1960. expect(staticMethod?.isStatic).toBe(true);
  1961. });
  1962. });
  1963. describe('Enum extraction', () => {
  1964. it('should extract enums with members', () => {
  1965. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  1966. const result = extractFromSource('Test.pas', code);
  1967. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1968. expect(enumNode).toBeDefined();
  1969. expect(enumNode?.name).toBe('TColor');
  1970. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1971. expect(members.length).toBe(3);
  1972. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  1973. });
  1974. });
  1975. describe('Property extraction', () => {
  1976. it('should extract properties', () => {
  1977. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  1978. const result = extractFromSource('Test.pas', code);
  1979. const propNode = result.nodes.find((n) => n.kind === 'property');
  1980. expect(propNode).toBeDefined();
  1981. expect(propNode?.name).toBe('Name');
  1982. expect(propNode?.visibility).toBe('public');
  1983. });
  1984. });
  1985. describe('Constant extraction', () => {
  1986. it('should extract constants', () => {
  1987. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  1988. const result = extractFromSource('Test.pas', code);
  1989. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1990. expect(constants.length).toBe(2);
  1991. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  1992. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  1993. });
  1994. });
  1995. describe('Type alias extraction', () => {
  1996. it('should extract type aliases', () => {
  1997. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  1998. const result = extractFromSource('Test.pas', code);
  1999. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2000. expect(aliasNode).toBeDefined();
  2001. expect(aliasNode?.name).toBe('TUserName');
  2002. });
  2003. });
  2004. describe('Call extraction', () => {
  2005. it('should extract calls from implementation bodies', () => {
  2006. 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.`;
  2007. const result = extractFromSource('Test.pas', code);
  2008. const callRef = result.unresolvedReferences.find(
  2009. (r) => r.referenceKind === 'calls'
  2010. );
  2011. expect(callRef).toBeDefined();
  2012. expect(callRef?.referenceName).toBe('WriteLn');
  2013. });
  2014. });
  2015. describe('Containment edges', () => {
  2016. it('should create contains edges for class members', () => {
  2017. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2018. const result = extractFromSource('Test.pas', code);
  2019. const classNode = result.nodes.find((n) => n.kind === 'class');
  2020. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2021. expect(classNode).toBeDefined();
  2022. expect(methodNode).toBeDefined();
  2023. const containsEdge = result.edges.find(
  2024. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2025. );
  2026. expect(containsEdge).toBeDefined();
  2027. });
  2028. });
  2029. describe('Full fixture: UAuth.pas', () => {
  2030. const code = `unit UAuth;
  2031. interface
  2032. uses
  2033. System.SysUtils,
  2034. System.Classes;
  2035. type
  2036. ITokenValidator = interface
  2037. ['{11111111-1111-1111-1111-111111111111}']
  2038. function Validate(const AToken: string): Boolean;
  2039. end;
  2040. TAuthService = class(TInterfacedObject, ITokenValidator)
  2041. private
  2042. FToken: string;
  2043. FLoginCount: Integer;
  2044. procedure IncLoginCount;
  2045. protected
  2046. function GetToken: string;
  2047. public
  2048. constructor Create;
  2049. destructor Destroy; override;
  2050. function Validate(const AToken: string): Boolean;
  2051. function Login(const AUser, APass: string): string;
  2052. property Token: string read GetToken;
  2053. property LoginCount: Integer read FLoginCount;
  2054. end;
  2055. implementation
  2056. constructor TAuthService.Create;
  2057. begin
  2058. inherited Create;
  2059. FToken := '';
  2060. FLoginCount := 0;
  2061. end;
  2062. destructor TAuthService.Destroy;
  2063. begin
  2064. FToken := '';
  2065. inherited Destroy;
  2066. end;
  2067. procedure TAuthService.IncLoginCount;
  2068. begin
  2069. Inc(FLoginCount);
  2070. end;
  2071. function TAuthService.GetToken: string;
  2072. begin
  2073. Result := FToken;
  2074. end;
  2075. function TAuthService.Validate(const AToken: string): Boolean;
  2076. begin
  2077. Result := AToken <> '';
  2078. end;
  2079. function TAuthService.Login(const AUser, APass: string): string;
  2080. begin
  2081. IncLoginCount;
  2082. if Validate(AUser + ':' + APass) then
  2083. begin
  2084. FToken := AUser;
  2085. Result := 'ok';
  2086. end
  2087. else
  2088. Result := '';
  2089. end;
  2090. end.`;
  2091. it('should extract all expected nodes', () => {
  2092. const result = extractFromSource('UAuth.pas', code);
  2093. expect(result.errors).toHaveLength(0);
  2094. // Module
  2095. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2096. expect(moduleNode?.name).toBe('UAuth');
  2097. // Imports
  2098. const imports = result.nodes.filter((n) => n.kind === 'import');
  2099. expect(imports.length).toBe(2);
  2100. // Interface
  2101. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2102. expect(ifaceNode?.name).toBe('ITokenValidator');
  2103. // Class
  2104. const classNode = result.nodes.find((n) => n.kind === 'class');
  2105. expect(classNode?.name).toBe('TAuthService');
  2106. // Methods
  2107. const methods = result.nodes.filter((n) => n.kind === 'method');
  2108. expect(methods.length).toBeGreaterThanOrEqual(6);
  2109. expect(methods.map((m) => m.name)).toContain('Create');
  2110. expect(methods.map((m) => m.name)).toContain('Destroy');
  2111. expect(methods.map((m) => m.name)).toContain('Login');
  2112. // Fields
  2113. const fields = result.nodes.filter((n) => n.kind === 'field');
  2114. expect(fields.length).toBe(2);
  2115. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2116. // Properties
  2117. const props = result.nodes.filter((n) => n.kind === 'property');
  2118. expect(props.length).toBe(2);
  2119. expect(props.map((p) => p.name)).toContain('Token');
  2120. expect(props.map((p) => p.name)).toContain('LoginCount');
  2121. });
  2122. it('should extract inheritance and interface implementation', () => {
  2123. const result = extractFromSource('UAuth.pas', code);
  2124. const extendsRef = result.unresolvedReferences.find(
  2125. (r) => r.referenceKind === 'extends'
  2126. );
  2127. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2128. const implementsRef = result.unresolvedReferences.find(
  2129. (r) => r.referenceKind === 'implements'
  2130. );
  2131. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2132. });
  2133. it('should extract calls from implementation', () => {
  2134. const result = extractFromSource('UAuth.pas', code);
  2135. const callRefs = result.unresolvedReferences.filter(
  2136. (r) => r.referenceKind === 'calls'
  2137. );
  2138. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2139. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2140. });
  2141. });
  2142. describe('Full fixture: UTypes.pas', () => {
  2143. const code = `unit UTypes;
  2144. interface
  2145. uses
  2146. System.SysUtils;
  2147. const
  2148. C_MAX_RETRIES = 3;
  2149. C_DEFAULT_NAME = 'Guest';
  2150. type
  2151. TUserRole = (urAdmin, urEditor, urViewer);
  2152. TPoint2D = record
  2153. X: Double;
  2154. Y: Double;
  2155. end;
  2156. TUserName = string;
  2157. TUserInfo = class
  2158. public
  2159. type
  2160. TAddress = record
  2161. Street: string;
  2162. City: string;
  2163. Zip: string;
  2164. end;
  2165. private
  2166. FName: TUserName;
  2167. FRole: TUserRole;
  2168. FAddress: TAddress;
  2169. public
  2170. constructor Create(const AName: TUserName; ARole: TUserRole);
  2171. function GetDisplayName: string;
  2172. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2173. property Name: TUserName read FName write FName;
  2174. property Role: TUserRole read FRole;
  2175. property Address: TAddress read FAddress write FAddress;
  2176. end;
  2177. implementation
  2178. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2179. begin
  2180. FName := AName;
  2181. FRole := ARole;
  2182. end;
  2183. function TUserInfo.GetDisplayName: string;
  2184. begin
  2185. if FRole = urAdmin then
  2186. Result := '[Admin] ' + FName
  2187. else
  2188. Result := FName;
  2189. end;
  2190. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2191. begin
  2192. Result := TUserInfo.Create(AName, urAdmin);
  2193. end;
  2194. end.`;
  2195. it('should extract enums with members', () => {
  2196. const result = extractFromSource('UTypes.pas', code);
  2197. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2198. expect(enumNode?.name).toBe('TUserRole');
  2199. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2200. expect(members.length).toBe(3);
  2201. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2202. });
  2203. it('should extract constants', () => {
  2204. const result = extractFromSource('UTypes.pas', code);
  2205. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2206. expect(constants.length).toBe(2);
  2207. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2208. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2209. });
  2210. it('should extract type aliases', () => {
  2211. const result = extractFromSource('UTypes.pas', code);
  2212. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2213. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2214. });
  2215. it('should extract records as classes with fields', () => {
  2216. const result = extractFromSource('UTypes.pas', code);
  2217. const classes = result.nodes.filter((n) => n.kind === 'class');
  2218. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2219. // TPoint2D fields
  2220. const fields = result.nodes.filter((n) => n.kind === 'field');
  2221. expect(fields.map((f) => f.name)).toContain('X');
  2222. expect(fields.map((f) => f.name)).toContain('Y');
  2223. });
  2224. it('should extract static class methods', () => {
  2225. const result = extractFromSource('UTypes.pas', code);
  2226. const methods = result.nodes.filter((n) => n.kind === 'method');
  2227. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2228. expect(staticMethod).toBeDefined();
  2229. expect(staticMethod?.isStatic).toBe(true);
  2230. });
  2231. it('should extract nested types', () => {
  2232. const result = extractFromSource('UTypes.pas', code);
  2233. const classes = result.nodes.filter((n) => n.kind === 'class');
  2234. expect(classes.map((c) => c.name)).toContain('TAddress');
  2235. });
  2236. });
  2237. });
  2238. // =============================================================================
  2239. // DFM/FMX Extraction
  2240. // =============================================================================
  2241. describe('DFM/FMX Extraction', () => {
  2242. it('should extract components from DFM', () => {
  2243. const code = `object Form1: TForm1
  2244. Left = 0
  2245. Top = 0
  2246. Caption = 'My Form'
  2247. object Button1: TButton
  2248. Left = 10
  2249. Top = 10
  2250. Caption = 'Click Me'
  2251. end
  2252. end`;
  2253. const result = extractFromSource('Form1.dfm', code);
  2254. const components = result.nodes.filter((n) => n.kind === 'component');
  2255. expect(components.length).toBe(2);
  2256. expect(components.map((c) => c.name)).toContain('Form1');
  2257. expect(components.map((c) => c.name)).toContain('Button1');
  2258. const button = components.find((c) => c.name === 'Button1');
  2259. expect(button?.signature).toBe('TButton');
  2260. });
  2261. it('should extract nested component hierarchy', () => {
  2262. const code = `object Form1: TForm1
  2263. object Panel1: TPanel
  2264. object Label1: TLabel
  2265. Caption = 'Hello'
  2266. end
  2267. end
  2268. end`;
  2269. const result = extractFromSource('Form1.dfm', code);
  2270. const components = result.nodes.filter((n) => n.kind === 'component');
  2271. expect(components.length).toBe(3);
  2272. // Check nesting: Panel1 contains Label1
  2273. const panel = components.find((c) => c.name === 'Panel1');
  2274. const label = components.find((c) => c.name === 'Label1');
  2275. const containsEdge = result.edges.find(
  2276. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2277. );
  2278. expect(containsEdge).toBeDefined();
  2279. });
  2280. it('should extract event handler references', () => {
  2281. const code = `object Form1: TForm1
  2282. OnCreate = FormCreate
  2283. OnDestroy = FormDestroy
  2284. object Button1: TButton
  2285. OnClick = Button1Click
  2286. end
  2287. end`;
  2288. const result = extractFromSource('Form1.dfm', code);
  2289. const refs = result.unresolvedReferences;
  2290. expect(refs.length).toBe(3);
  2291. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2292. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2293. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2294. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2295. });
  2296. it('should handle multi-line properties', () => {
  2297. const code = `object Form1: TForm1
  2298. SQL.Strings = (
  2299. 'SELECT * FROM users'
  2300. 'WHERE active = 1')
  2301. object Button1: TButton
  2302. OnClick = Button1Click
  2303. end
  2304. end`;
  2305. const result = extractFromSource('Form1.dfm', code);
  2306. const components = result.nodes.filter((n) => n.kind === 'component');
  2307. expect(components.length).toBe(2);
  2308. const refs = result.unresolvedReferences;
  2309. expect(refs.length).toBe(1);
  2310. expect(refs[0]?.referenceName).toBe('Button1Click');
  2311. });
  2312. it('should handle inherited keyword', () => {
  2313. const code = `inherited Form1: TForm1
  2314. Caption = 'Inherited Form'
  2315. object Button1: TButton
  2316. OnClick = Button1Click
  2317. end
  2318. end`;
  2319. const result = extractFromSource('Form1.dfm', code);
  2320. const components = result.nodes.filter((n) => n.kind === 'component');
  2321. expect(components.length).toBe(2);
  2322. expect(components.map((c) => c.name)).toContain('Form1');
  2323. });
  2324. it('should handle item collection properties', () => {
  2325. const code = `object Form1: TForm1
  2326. object StatusBar1: TStatusBar
  2327. Panels = <
  2328. item
  2329. Width = 200
  2330. end
  2331. item
  2332. Width = 200
  2333. end>
  2334. end
  2335. end`;
  2336. const result = extractFromSource('Form1.dfm', code);
  2337. const components = result.nodes.filter((n) => n.kind === 'component');
  2338. expect(components.length).toBe(2);
  2339. });
  2340. describe('Full fixture: MainForm.dfm', () => {
  2341. const code = `object frmMain: TfrmMain
  2342. Left = 0
  2343. Top = 0
  2344. Caption = 'CodeGraph DFM Fixture'
  2345. ClientHeight = 480
  2346. ClientWidth = 640
  2347. OnCreate = FormCreate
  2348. OnDestroy = FormDestroy
  2349. object pnlTop: TPanel
  2350. Left = 0
  2351. Top = 0
  2352. Width = 640
  2353. Height = 50
  2354. object lblTitle: TLabel
  2355. Left = 16
  2356. Top = 16
  2357. Caption = 'Authentication Service'
  2358. end
  2359. object btnLogin: TButton
  2360. Left = 540
  2361. Top = 12
  2362. OnClick = btnLoginClick
  2363. end
  2364. end
  2365. object pnlContent: TPanel
  2366. Left = 0
  2367. Top = 50
  2368. object edtUsername: TEdit
  2369. Left = 16
  2370. Top = 16
  2371. OnChange = edtUsernameChange
  2372. end
  2373. object edtPassword: TEdit
  2374. Left = 16
  2375. Top = 48
  2376. OnKeyPress = edtPasswordKeyPress
  2377. end
  2378. object mmoLog: TMemo
  2379. Left = 16
  2380. Top = 88
  2381. end
  2382. end
  2383. object pnlStatus: TStatusBar
  2384. Left = 0
  2385. Top = 440
  2386. Panels = <
  2387. item
  2388. Width = 200
  2389. end
  2390. item
  2391. Width = 200
  2392. end>
  2393. end
  2394. end`;
  2395. it('should extract all components', () => {
  2396. const result = extractFromSource('MainForm.dfm', code);
  2397. const components = result.nodes.filter((n) => n.kind === 'component');
  2398. expect(components.length).toBe(9);
  2399. expect(components.map((c) => c.name)).toEqual(
  2400. expect.arrayContaining([
  2401. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2402. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2403. ])
  2404. );
  2405. });
  2406. it('should extract all event handlers', () => {
  2407. const result = extractFromSource('MainForm.dfm', code);
  2408. const refs = result.unresolvedReferences;
  2409. expect(refs.length).toBe(5);
  2410. expect(refs.map((r) => r.referenceName)).toEqual(
  2411. expect.arrayContaining([
  2412. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2413. 'edtUsernameChange', 'edtPasswordKeyPress',
  2414. ])
  2415. );
  2416. });
  2417. });
  2418. });
  2419. describe('Full Indexing', () => {
  2420. let tempDir: string;
  2421. beforeEach(() => {
  2422. tempDir = createTempDir();
  2423. });
  2424. afterEach(() => {
  2425. cleanupTempDir(tempDir);
  2426. });
  2427. it('should index a TypeScript file', async () => {
  2428. // Create test file
  2429. const srcDir = path.join(tempDir, 'src');
  2430. fs.mkdirSync(srcDir);
  2431. fs.writeFileSync(
  2432. path.join(srcDir, 'utils.ts'),
  2433. `
  2434. export function add(a: number, b: number): number {
  2435. return a + b;
  2436. }
  2437. export function multiply(a: number, b: number): number {
  2438. return a * b;
  2439. }
  2440. `
  2441. );
  2442. // Initialize and index
  2443. const cg = CodeGraph.initSync(tempDir);
  2444. const result = await cg.indexAll();
  2445. expect(result.success).toBe(true);
  2446. expect(result.filesIndexed).toBe(1);
  2447. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2448. // Check nodes were stored
  2449. const nodes = cg.getNodesInFile('src/utils.ts');
  2450. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2451. const addFunc = nodes.find((n) => n.name === 'add');
  2452. expect(addFunc).toBeDefined();
  2453. expect(addFunc?.kind).toBe('function');
  2454. cg.close();
  2455. });
  2456. it('should index multiple files', async () => {
  2457. // Create test files
  2458. const srcDir = path.join(tempDir, 'src');
  2459. fs.mkdirSync(srcDir);
  2460. fs.writeFileSync(
  2461. path.join(srcDir, 'math.ts'),
  2462. `export function add(a: number, b: number) { return a + b; }`
  2463. );
  2464. fs.writeFileSync(
  2465. path.join(srcDir, 'string.ts'),
  2466. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2467. );
  2468. // Initialize and index
  2469. const cg = CodeGraph.initSync(tempDir);
  2470. const result = await cg.indexAll();
  2471. expect(result.success).toBe(true);
  2472. expect(result.filesIndexed).toBe(2);
  2473. const files = cg.getFiles();
  2474. expect(files.length).toBe(2);
  2475. cg.close();
  2476. });
  2477. it('should track file hashes for incremental updates', async () => {
  2478. // Create initial file
  2479. const srcDir = path.join(tempDir, 'src');
  2480. fs.mkdirSync(srcDir);
  2481. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2482. // Initialize and index
  2483. const cg = CodeGraph.initSync(tempDir);
  2484. await cg.indexAll();
  2485. // Check file is tracked
  2486. const file = cg.getFile('src/main.ts');
  2487. expect(file).toBeDefined();
  2488. expect(file?.contentHash).toBeDefined();
  2489. // Modify file
  2490. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2491. // Check for changes
  2492. const changes = cg.getChangedFiles();
  2493. expect(changes.modified).toContain('src/main.ts');
  2494. cg.close();
  2495. });
  2496. it('should sync and detect changes', async () => {
  2497. // Create initial file
  2498. const srcDir = path.join(tempDir, 'src');
  2499. fs.mkdirSync(srcDir);
  2500. fs.writeFileSync(
  2501. path.join(srcDir, 'main.ts'),
  2502. `export function original() { return 1; }`
  2503. );
  2504. // Initialize and index
  2505. const cg = CodeGraph.initSync(tempDir);
  2506. await cg.indexAll();
  2507. const initialNodes = cg.getNodesInFile('src/main.ts');
  2508. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2509. // Modify file
  2510. fs.writeFileSync(
  2511. path.join(srcDir, 'main.ts'),
  2512. `export function updated() { return 2; }`
  2513. );
  2514. // Sync
  2515. const syncResult = await cg.sync();
  2516. expect(syncResult.filesModified).toBe(1);
  2517. // Check nodes were updated
  2518. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2519. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2520. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2521. cg.close();
  2522. });
  2523. });
  2524. describe('Path Normalization', () => {
  2525. it('should convert backslashes to forward slashes', () => {
  2526. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  2527. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  2528. });
  2529. it('should leave forward-slash paths unchanged', () => {
  2530. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  2531. });
  2532. it('should handle empty string', () => {
  2533. expect(normalizePath('')).toBe('');
  2534. });
  2535. });
  2536. describe('Directory Exclusion', () => {
  2537. let tempDir: string;
  2538. beforeEach(() => {
  2539. tempDir = createTempDir();
  2540. });
  2541. afterEach(() => {
  2542. cleanupTempDir(tempDir);
  2543. });
  2544. it('should exclude directories listed in .gitignore', () => {
  2545. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  2546. const srcDir = path.join(tempDir, 'src');
  2547. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  2548. fs.mkdirSync(srcDir, { recursive: true });
  2549. fs.mkdirSync(nmDir, { recursive: true });
  2550. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2551. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2552. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  2553. const files = scanDirectory(tempDir);
  2554. expect(files).toContain('src/index.ts');
  2555. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2556. });
  2557. it('should exclude nested node_modules via a root .gitignore', () => {
  2558. // A trailing-slash pattern with no leading slash matches at any depth.
  2559. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  2560. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  2561. fs.mkdirSync(srcDir, { recursive: true });
  2562. fs.mkdirSync(nmDir, { recursive: true });
  2563. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2564. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2565. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  2566. const files = scanDirectory(tempDir);
  2567. expect(files).toContain('packages/app/src/index.ts');
  2568. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2569. });
  2570. it('should apply a nested .gitignore only to its own subtree', () => {
  2571. const appSrc = path.join(tempDir, 'app', 'src');
  2572. fs.mkdirSync(appSrc, { recursive: true });
  2573. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  2574. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  2575. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  2576. // A sibling with the same name outside app/ must NOT be ignored.
  2577. const otherDir = path.join(tempDir, 'other', 'src');
  2578. fs.mkdirSync(otherDir, { recursive: true });
  2579. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  2580. const files = scanDirectory(tempDir);
  2581. expect(files).toContain('app/src/keep.ts');
  2582. expect(files).not.toContain('app/src/skip.ts');
  2583. expect(files).toContain('other/src/skip.ts');
  2584. });
  2585. it('should always skip .git directories', () => {
  2586. const srcDir = path.join(tempDir, 'src');
  2587. const gitDir = path.join(tempDir, '.git', 'objects');
  2588. fs.mkdirSync(srcDir, { recursive: true });
  2589. fs.mkdirSync(gitDir, { recursive: true });
  2590. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2591. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  2592. const files = scanDirectory(tempDir);
  2593. expect(files).toContain('src/index.ts');
  2594. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  2595. });
  2596. it('should return forward-slash paths on all platforms', () => {
  2597. const srcDir = path.join(tempDir, 'src', 'components');
  2598. fs.mkdirSync(srcDir, { recursive: true });
  2599. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  2600. const files = scanDirectory(tempDir);
  2601. expect(files.length).toBe(1);
  2602. expect(files[0]).toBe('src/components/Button.tsx');
  2603. expect(files[0]).not.toContain('\\');
  2604. });
  2605. });
  2606. describe('Git Submodules', () => {
  2607. let tempDir: string;
  2608. beforeEach(() => {
  2609. tempDir = createTempDir();
  2610. });
  2611. afterEach(() => {
  2612. cleanupTempDir(tempDir);
  2613. });
  2614. it('should index files inside git submodules (issue #147)', async () => {
  2615. const { execFileSync } = await import('child_process');
  2616. const git = (cwd: string, ...args: string[]) =>
  2617. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2618. // Build a separate "library" repo to use as a submodule source.
  2619. const libDir = path.join(tempDir, '_lib');
  2620. fs.mkdirSync(libDir, { recursive: true });
  2621. git(libDir, 'init', '-q');
  2622. git(libDir, 'config', 'user.email', 'test@test.com');
  2623. git(libDir, 'config', 'user.name', 'Test');
  2624. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  2625. git(libDir, 'add', '-A');
  2626. git(libDir, 'commit', '-q', '-m', 'lib init');
  2627. // Build the main repo and add the lib repo as a submodule.
  2628. const mainDir = path.join(tempDir, 'main');
  2629. fs.mkdirSync(mainDir, { recursive: true });
  2630. git(mainDir, 'init', '-q');
  2631. git(mainDir, 'config', 'user.email', 'test@test.com');
  2632. git(mainDir, 'config', 'user.name', 'Test');
  2633. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  2634. git(mainDir, 'add', '-A');
  2635. git(mainDir, 'commit', '-q', '-m', 'app init');
  2636. // protocol.file.allow=always is required to add a local-path submodule on
  2637. // recent git versions (CVE-2022-39253 mitigation).
  2638. execFileSync(
  2639. 'git',
  2640. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  2641. { cwd: mainDir, stdio: 'pipe' }
  2642. );
  2643. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  2644. const files = scanDirectory(mainDir);
  2645. expect(files).toContain('app.ts');
  2646. expect(files).toContain('libs/lib/lib.ts');
  2647. });
  2648. });
  2649. describe('Nested non-submodule git repos', () => {
  2650. let tempDir: string;
  2651. beforeEach(() => {
  2652. tempDir = createTempDir();
  2653. });
  2654. afterEach(() => {
  2655. cleanupTempDir(tempDir);
  2656. });
  2657. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  2658. const { execFileSync } = await import('child_process');
  2659. const git = (cwd: string, ...args: string[]) =>
  2660. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2661. // Top-level workspace is itself a git repo, holding no source directly —
  2662. // the CMake "super-repo" layout from the issue.
  2663. const root = path.join(tempDir, 'root');
  2664. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  2665. git(root, 'init', '-q');
  2666. git(root, 'config', 'user.email', 'test@test.com');
  2667. git(root, 'config', 'user.name', 'Test');
  2668. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  2669. // Two independent clones living inside the workspace (NOT submodules):
  2670. // one with committed source, one with only untracked source.
  2671. const sub1 = path.join(root, 'sub_repo1', 'src');
  2672. fs.mkdirSync(sub1, { recursive: true });
  2673. git(path.join(root, 'sub_repo1'), 'init', '-q');
  2674. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  2675. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  2676. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  2677. git(path.join(root, 'sub_repo1'), 'add', '-A');
  2678. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  2679. const sub2 = path.join(root, 'sub_repo2', 'src');
  2680. fs.mkdirSync(sub2, { recursive: true });
  2681. git(path.join(root, 'sub_repo2'), 'init', '-q');
  2682. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  2683. const files = scanDirectory(root);
  2684. // Both committed and untracked source from the nested repos must be found.
  2685. expect(files).toContain('sub_repo1/src/one.ts');
  2686. expect(files).toContain('sub_repo2/src/two.ts');
  2687. });
  2688. it('should respect each embedded repo\'s own .gitignore', async () => {
  2689. const { execFileSync } = await import('child_process');
  2690. const git = (cwd: string, ...args: string[]) =>
  2691. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2692. const root = path.join(tempDir, 'root');
  2693. fs.mkdirSync(root, { recursive: true });
  2694. git(root, 'init', '-q');
  2695. const sub = path.join(root, 'sub_repo', 'src');
  2696. fs.mkdirSync(sub, { recursive: true });
  2697. git(path.join(root, 'sub_repo'), 'init', '-q');
  2698. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  2699. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  2700. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  2701. const files = scanDirectory(root);
  2702. expect(files).toContain('sub_repo/src/real.ts');
  2703. expect(files).not.toContain('sub_repo/src/generated.ts');
  2704. });
  2705. });
  2706. // =============================================================================
  2707. // Scala
  2708. // =============================================================================
  2709. describe('Scala Extraction', () => {
  2710. describe('Language detection', () => {
  2711. it('should detect Scala files', () => {
  2712. expect(detectLanguage('Main.scala')).toBe('scala');
  2713. expect(detectLanguage('script.sc')).toBe('scala');
  2714. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  2715. });
  2716. it('should report Scala as supported', () => {
  2717. expect(isLanguageSupported('scala')).toBe(true);
  2718. expect(getSupportedLanguages()).toContain('scala');
  2719. });
  2720. });
  2721. describe('Class extraction', () => {
  2722. it('should extract class definitions', () => {
  2723. const code = `
  2724. class UserService(private val repo: UserRepository) {
  2725. def findUser(id: String): Option[String] = Some(id)
  2726. }
  2727. `;
  2728. const result = extractFromSource('UserService.scala', code);
  2729. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  2730. expect(cls).toBeDefined();
  2731. expect(cls?.language).toBe('scala');
  2732. });
  2733. it('should extract object definitions as class kind', () => {
  2734. const code = `
  2735. object DatabaseConfig {
  2736. val url = "jdbc:postgresql://localhost/mydb"
  2737. }
  2738. `;
  2739. const result = extractFromSource('Config.scala', code);
  2740. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  2741. expect(obj).toBeDefined();
  2742. });
  2743. it('should extract trait definitions as trait kind', () => {
  2744. const code = `
  2745. trait Repository[A] {
  2746. def findById(id: String): Option[A]
  2747. def save(entity: A): Unit
  2748. }
  2749. `;
  2750. const result = extractFromSource('Repository.scala', code);
  2751. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  2752. expect(trait_).toBeDefined();
  2753. });
  2754. });
  2755. describe('Method and function extraction', () => {
  2756. it('should extract method definitions inside a class', () => {
  2757. const code = `
  2758. class Calculator {
  2759. def add(a: Int, b: Int): Int = a + b
  2760. def divide(a: Double, b: Double): Double = a / b
  2761. }
  2762. `;
  2763. const result = extractFromSource('Calculator.scala', code);
  2764. const methods = result.nodes.filter((n) => n.kind === 'method');
  2765. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  2766. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  2767. });
  2768. it('should extract method signatures', () => {
  2769. const code = `
  2770. class Greeter {
  2771. def greet(name: String): String = s"Hello, \${name}!"
  2772. }
  2773. `;
  2774. const result = extractFromSource('Greeter.scala', code);
  2775. const method = result.nodes.find((n) => n.name === 'greet');
  2776. expect(method?.signature).toContain('name: String');
  2777. expect(method?.signature).toContain('String');
  2778. });
  2779. it('should extract top-level function definitions as functions', () => {
  2780. const code = `
  2781. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  2782. def greet(name: String): String = s"Hello, \${name}!"
  2783. `;
  2784. const result = extractFromSource('utils.scala', code);
  2785. const fns = result.nodes.filter((n) => n.kind === 'function');
  2786. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  2787. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  2788. });
  2789. });
  2790. describe('Val and var extraction', () => {
  2791. it('should extract val inside a class as field', () => {
  2792. const code = `
  2793. class Config {
  2794. val timeout: Int = 30
  2795. val host: String = "localhost"
  2796. }
  2797. `;
  2798. const result = extractFromSource('Config.scala', code);
  2799. const fields = result.nodes.filter((n) => n.kind === 'field');
  2800. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  2801. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  2802. });
  2803. it('should extract var inside a class as field', () => {
  2804. const code = `
  2805. class Counter {
  2806. var count: Int = 0
  2807. }
  2808. `;
  2809. const result = extractFromSource('Counter.scala', code);
  2810. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  2811. expect(field).toBeDefined();
  2812. });
  2813. it('should extract top-level val as constant', () => {
  2814. const code = `
  2815. val MaxConnections: Int = 100
  2816. val DefaultTimeout = 30
  2817. `;
  2818. const result = extractFromSource('constants.scala', code);
  2819. const consts = result.nodes.filter((n) => n.kind === 'constant');
  2820. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  2821. });
  2822. it('should extract top-level var as variable', () => {
  2823. const code = `
  2824. var retries: Int = 3
  2825. `;
  2826. const result = extractFromSource('state.scala', code);
  2827. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  2828. expect(v).toBeDefined();
  2829. });
  2830. it('should include type in val/var signature', () => {
  2831. const code = `
  2832. class Service {
  2833. val timeout: Int = 30
  2834. }
  2835. `;
  2836. const result = extractFromSource('Service.scala', code);
  2837. const field = result.nodes.find((n) => n.name === 'timeout');
  2838. expect(field?.signature).toContain('timeout');
  2839. expect(field?.signature).toContain('Int');
  2840. });
  2841. });
  2842. describe('Enum extraction', () => {
  2843. it('should extract enum definitions', () => {
  2844. const code = `
  2845. enum Color:
  2846. case Red
  2847. case Green
  2848. case Blue
  2849. `;
  2850. const result = extractFromSource('Color.scala', code);
  2851. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  2852. expect(enumNode).toBeDefined();
  2853. });
  2854. it('should extract enum cases as enum_member', () => {
  2855. const code = `
  2856. enum Direction:
  2857. case North
  2858. case South
  2859. case East
  2860. case West
  2861. `;
  2862. const result = extractFromSource('Direction.scala', code);
  2863. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2864. expect(members.find((m) => m.name === 'North')).toBeDefined();
  2865. expect(members.find((m) => m.name === 'South')).toBeDefined();
  2866. expect(members.length).toBeGreaterThanOrEqual(4);
  2867. });
  2868. });
  2869. describe('Type alias extraction', () => {
  2870. it('should extract type aliases', () => {
  2871. const code = `
  2872. type UserId = String
  2873. type UserMap = Map[String, String]
  2874. `;
  2875. const result = extractFromSource('types.scala', code);
  2876. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2877. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  2878. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  2879. });
  2880. });
  2881. describe('Import extraction', () => {
  2882. it('should extract import declarations', () => {
  2883. const code = `
  2884. import scala.collection.mutable.ListBuffer
  2885. import scala.concurrent.Future
  2886. `;
  2887. const result = extractFromSource('imports.scala', code);
  2888. const imports = result.nodes.filter((n) => n.kind === 'import');
  2889. expect(imports.length).toBeGreaterThanOrEqual(2);
  2890. });
  2891. });
  2892. describe('Visibility modifiers', () => {
  2893. it('should extract private visibility', () => {
  2894. const code = `
  2895. class Service {
  2896. private val secret: String = "abc"
  2897. private def helper(): Unit = {}
  2898. }
  2899. `;
  2900. const result = extractFromSource('Service.scala', code);
  2901. const secretField = result.nodes.find((n) => n.name === 'secret');
  2902. expect(secretField?.visibility).toBe('private');
  2903. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  2904. expect(helperMethod?.visibility).toBe('private');
  2905. });
  2906. it('should extract protected visibility', () => {
  2907. const code = `
  2908. class Base {
  2909. protected def helperMethod(): Unit = {}
  2910. }
  2911. `;
  2912. const result = extractFromSource('Base.scala', code);
  2913. const method = result.nodes.find((n) => n.name === 'helperMethod');
  2914. expect(method?.visibility).toBe('protected');
  2915. });
  2916. it('should default to public visibility', () => {
  2917. const code = `
  2918. class Greeter {
  2919. def hello(): Unit = {}
  2920. }
  2921. `;
  2922. const result = extractFromSource('Greeter.scala', code);
  2923. const method = result.nodes.find((n) => n.name === 'hello');
  2924. expect(method?.visibility).toBe('public');
  2925. });
  2926. });
  2927. describe('Inheritance', () => {
  2928. it('should extract extends relationships', () => {
  2929. const code = `
  2930. class AdminUser extends User {
  2931. def adminAction(): Unit = {}
  2932. }
  2933. `;
  2934. const result = extractFromSource('AdminUser.scala', code);
  2935. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  2936. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  2937. });
  2938. });
  2939. describe('Call extraction', () => {
  2940. it('should extract function call expressions', () => {
  2941. const code = `
  2942. def processData(): Unit = {
  2943. val result = computeResult()
  2944. println(result)
  2945. }
  2946. `;
  2947. const result = extractFromSource('processor.scala', code);
  2948. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  2949. expect(calls.length).toBeGreaterThan(0);
  2950. });
  2951. });
  2952. });
  2953. describe('Vue Extraction', () => {
  2954. it('should detect Vue files', () => {
  2955. expect(detectLanguage('App.vue')).toBe('vue');
  2956. expect(detectLanguage('components/Button.vue')).toBe('vue');
  2957. expect(isLanguageSupported('vue')).toBe(true);
  2958. });
  2959. it('should extract component node from a Vue SFC', () => {
  2960. const code = `<template>
  2961. <div>{{ message }}</div>
  2962. </template>
  2963. <script>
  2964. export default {
  2965. data() {
  2966. return { message: 'Hello' };
  2967. }
  2968. }
  2969. </script>
  2970. `;
  2971. const result = extractFromSource('HelloWorld.vue', code);
  2972. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2973. expect(componentNode).toBeDefined();
  2974. expect(componentNode?.name).toBe('HelloWorld');
  2975. expect(componentNode?.language).toBe('vue');
  2976. expect(componentNode?.isExported).toBe(true);
  2977. });
  2978. it('should extract functions from <script> block', () => {
  2979. const code = `<template>
  2980. <button @click="handleClick">Click</button>
  2981. </template>
  2982. <script>
  2983. function handleClick() {
  2984. console.log('clicked');
  2985. }
  2986. const count = 0;
  2987. </script>
  2988. `;
  2989. const result = extractFromSource('Button.vue', code);
  2990. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2991. expect(componentNode).toBeDefined();
  2992. expect(componentNode?.name).toBe('Button');
  2993. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  2994. expect(funcNode).toBeDefined();
  2995. expect(funcNode?.language).toBe('vue');
  2996. });
  2997. it('should extract from <script setup lang="ts"> block', () => {
  2998. const code = `<template>
  2999. <div>{{ count }}</div>
  3000. </template>
  3001. <script setup lang="ts">
  3002. import { ref } from 'vue';
  3003. const count = ref(0);
  3004. function increment(): void {
  3005. count.value++;
  3006. }
  3007. </script>
  3008. `;
  3009. const result = extractFromSource('Counter.vue', code);
  3010. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3011. expect(componentNode).toBeDefined();
  3012. expect(componentNode?.name).toBe('Counter');
  3013. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  3014. expect(funcNode).toBeDefined();
  3015. expect(funcNode?.language).toBe('vue');
  3016. // All nodes should be marked as vue language
  3017. for (const node of result.nodes) {
  3018. expect(node.language).toBe('vue');
  3019. }
  3020. });
  3021. it('should extract calls from top-level <script setup> initializers', () => {
  3022. const code = `<template>
  3023. <div>{{ token }}</div>
  3024. </template>
  3025. <script setup lang="ts">
  3026. import { getTokenMp } from './api/upload';
  3027. const token = getTokenMp();
  3028. </script>
  3029. `;
  3030. const result = extractFromSource('Issue425Setup.vue', code);
  3031. const call = result.unresolvedReferences.find(
  3032. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3033. );
  3034. expect(call).toBeDefined();
  3035. });
  3036. it('should extract calls from Vue Options API object methods', () => {
  3037. const code = `<template>
  3038. <button @click="save">Save</button>
  3039. </template>
  3040. <script>
  3041. import { getTokenMp } from './api/upload';
  3042. export default {
  3043. methods: {
  3044. save() {
  3045. return getTokenMp();
  3046. }
  3047. },
  3048. setup() {
  3049. return getTokenMp();
  3050. }
  3051. }
  3052. </script>
  3053. `;
  3054. const result = extractFromSource('Issue425Options.vue', code);
  3055. const calls = result.unresolvedReferences.filter(
  3056. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3057. );
  3058. expect(calls).toHaveLength(2);
  3059. });
  3060. it('should extract from both <script> and <script setup> blocks', () => {
  3061. const code = `<template>
  3062. <div>{{ msg }}</div>
  3063. </template>
  3064. <script>
  3065. export default {
  3066. name: 'DualScript'
  3067. }
  3068. </script>
  3069. <script setup>
  3070. const msg = 'hello';
  3071. function greet() {
  3072. return msg;
  3073. }
  3074. </script>
  3075. `;
  3076. const result = extractFromSource('DualScript.vue', code);
  3077. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3078. expect(componentNode).toBeDefined();
  3079. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  3080. expect(greetFunc).toBeDefined();
  3081. });
  3082. it('should create component node for template-only Vue file', () => {
  3083. const code = `<template>
  3084. <div>Static content</div>
  3085. </template>
  3086. `;
  3087. const result = extractFromSource('Static.vue', code);
  3088. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3089. expect(componentNode).toBeDefined();
  3090. expect(componentNode?.name).toBe('Static');
  3091. expect(componentNode?.language).toBe('vue');
  3092. // Only the component node should exist (no script nodes)
  3093. expect(result.nodes.length).toBe(1);
  3094. });
  3095. it('should create containment edges from component to script nodes', () => {
  3096. const code = `<template>
  3097. <div>{{ value }}</div>
  3098. </template>
  3099. <script setup lang="ts">
  3100. const value = 42;
  3101. </script>
  3102. `;
  3103. const result = extractFromSource('Contained.vue', code);
  3104. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3105. expect(componentNode).toBeDefined();
  3106. // Should have containment edges from component to child nodes
  3107. const containEdges = result.edges.filter(
  3108. (e) => e.source === componentNode!.id && e.kind === 'contains'
  3109. );
  3110. expect(containEdges.length).toBeGreaterThan(0);
  3111. });
  3112. });
  3113. describe('Instantiates + Decorates edge extraction', () => {
  3114. it('emits an instantiates ref for `new Foo()`', () => {
  3115. const code = `
  3116. class Foo {}
  3117. function bootstrap() { return new Foo(); }
  3118. `;
  3119. const result = extractFromSource('app.ts', code);
  3120. const ref = result.unresolvedReferences.find(
  3121. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  3122. );
  3123. expect(ref).toBeDefined();
  3124. });
  3125. it('strips type-argument suffix from generic constructors', () => {
  3126. const code = `
  3127. class Container<T> { constructor(_: T) {} }
  3128. function go() { return new Container<string>('x'); }
  3129. `;
  3130. const result = extractFromSource('app.ts', code);
  3131. const ref = result.unresolvedReferences.find(
  3132. (r) => r.referenceKind === 'instantiates'
  3133. );
  3134. expect(ref).toBeDefined();
  3135. // Container<string> must be normalised to "Container" — otherwise
  3136. // resolution can never match the class node.
  3137. expect(ref!.referenceName).toBe('Container');
  3138. });
  3139. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  3140. const code = `
  3141. const ns = { Foo: class {} };
  3142. function go() { return new ns.Foo(); }
  3143. `;
  3144. const result = extractFromSource('app.ts', code);
  3145. const ref = result.unresolvedReferences.find(
  3146. (r) => r.referenceKind === 'instantiates'
  3147. );
  3148. // We can't always resolve which Foo, but the name should be the
  3149. // simple identifier so name-matching has a chance.
  3150. expect(ref?.referenceName).toBe('Foo');
  3151. });
  3152. it('emits a decorates ref for `@Foo class X {}`', () => {
  3153. const code = `
  3154. function Foo(_arg: string) { return (cls: any) => cls; }
  3155. @Foo('x')
  3156. class X {}
  3157. `;
  3158. const result = extractFromSource('app.ts', code);
  3159. const decorClass = result.unresolvedReferences.find(
  3160. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  3161. );
  3162. expect(decorClass).toBeDefined();
  3163. });
  3164. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  3165. // Regression: the sibling-walk must stop at the first non-
  3166. // decorator separator. `@A class Foo {} @B class Bar {}` must
  3167. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  3168. // `decorates(Bar, A)`.
  3169. const code = `
  3170. function A(cls: any) { return cls; }
  3171. function B(cls: any) { return cls; }
  3172. @A
  3173. class Foo {}
  3174. @B
  3175. class Bar {}
  3176. `;
  3177. const result = extractFromSource('app.ts', code);
  3178. const decoratesEdges = result.unresolvedReferences.filter(
  3179. (r) => r.referenceKind === 'decorates'
  3180. );
  3181. // Exactly one decorates ref per decorated class, no cross-attribution.
  3182. const fromBar = decoratesEdges.filter((r) =>
  3183. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  3184. );
  3185. expect(fromBar.length).toBe(1);
  3186. expect(fromBar[0]!.referenceName).toBe('B');
  3187. });
  3188. it('emits a decorates ref for `@Foo method() {}`', () => {
  3189. const code = `
  3190. function Get(p: string) { return (t: any, k: string) => t; }
  3191. class Svc {
  3192. @Get('/x') method() { return 1; }
  3193. }
  3194. `;
  3195. const result = extractFromSource('app.ts', code);
  3196. const decorMethod = result.unresolvedReferences.find(
  3197. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  3198. );
  3199. expect(decorMethod).toBeDefined();
  3200. // The decorated symbol must be `method`, not the constructor or class.
  3201. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  3202. expect(decoratedNode?.name).toBe('method');
  3203. });
  3204. });
  3205. // =============================================================================
  3206. // Lua
  3207. // =============================================================================
  3208. describe('Lua Extraction', () => {
  3209. describe('Language detection', () => {
  3210. it('should detect Lua files', () => {
  3211. expect(detectLanguage('init.lua')).toBe('lua');
  3212. expect(detectLanguage('src/util.lua')).toBe('lua');
  3213. });
  3214. it('should report Lua as supported', () => {
  3215. expect(isLanguageSupported('lua')).toBe(true);
  3216. expect(getSupportedLanguages()).toContain('lua');
  3217. });
  3218. });
  3219. describe('Function extraction', () => {
  3220. it('should extract global and local functions', () => {
  3221. const code = `
  3222. function configure(opts) return opts end
  3223. local function helper(x) return x * 2 end
  3224. `;
  3225. const result = extractFromSource('init.lua', code);
  3226. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  3227. expect(funcs).toContain('configure');
  3228. expect(funcs).toContain('helper');
  3229. const configure = result.nodes.find((n) => n.name === 'configure');
  3230. expect(configure?.language).toBe('lua');
  3231. expect(configure?.signature).toBe('(opts)');
  3232. });
  3233. it('should split table/method functions into a receiver and method name', () => {
  3234. const code = `
  3235. function M.connect(host, port) return host end
  3236. function M:send(data) return self end
  3237. `;
  3238. const result = extractFromSource('init.lua', code);
  3239. const methods = result.nodes.filter((n) => n.kind === 'method');
  3240. const connect = methods.find((m) => m.name === 'connect');
  3241. expect(connect?.qualifiedName).toBe('M::connect');
  3242. const send = methods.find((m) => m.name === 'send');
  3243. expect(send?.qualifiedName).toBe('M::send');
  3244. });
  3245. });
  3246. describe('Variable extraction', () => {
  3247. it('should extract local variable declarations', () => {
  3248. const code = `
  3249. local M = {}
  3250. local count = 0
  3251. `;
  3252. const result = extractFromSource('mod.lua', code);
  3253. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3254. expect(vars).toContain('M');
  3255. expect(vars).toContain('count');
  3256. });
  3257. });
  3258. describe('Import extraction (require)', () => {
  3259. it('should extract require() in local declarations and bare calls', () => {
  3260. const code = `
  3261. local socket = require("socket")
  3262. local http = require "resty.http"
  3263. require("side.effect")
  3264. `;
  3265. const result = extractFromSource('net.lua', code);
  3266. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3267. expect(imports).toContain('socket');
  3268. expect(imports).toContain('resty.http');
  3269. expect(imports).toContain('side.effect');
  3270. const ref = result.unresolvedReferences.find(
  3271. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  3272. );
  3273. expect(ref).toBeDefined();
  3274. });
  3275. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  3276. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  3277. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  3278. // by extracting several sources in sequence and asserting the LAST still works.
  3279. it('should keep extracting require across many sequential parses', () => {
  3280. let last;
  3281. for (let i = 0; i < 8; i++) {
  3282. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  3283. }
  3284. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3285. expect(imports).toContain('module.7');
  3286. });
  3287. });
  3288. describe('Call extraction', () => {
  3289. it('should record intra-file calls as resolvable references', () => {
  3290. const code = `
  3291. local function helper(x) return x end
  3292. local function run(y) return helper(y) end
  3293. `;
  3294. const result = extractFromSource('calls.lua', code);
  3295. const call = result.unresolvedReferences.find(
  3296. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  3297. );
  3298. expect(call).toBeDefined();
  3299. });
  3300. });
  3301. });
  3302. // =============================================================================
  3303. // Luau (typed superset of Lua — https://luau.org)
  3304. // =============================================================================
  3305. describe('Luau Extraction', () => {
  3306. describe('Language detection', () => {
  3307. it('should detect Luau files', () => {
  3308. expect(detectLanguage('init.luau')).toBe('luau');
  3309. expect(detectLanguage('src/Client.luau')).toBe('luau');
  3310. });
  3311. it('should report Luau as supported', () => {
  3312. expect(isLanguageSupported('luau')).toBe(true);
  3313. expect(getSupportedLanguages()).toContain('luau');
  3314. });
  3315. });
  3316. describe('Type aliases', () => {
  3317. it('should extract `type` and `export type` definitions', () => {
  3318. const code = `
  3319. export type Vector = { x: number, y: number }
  3320. type Handler = (msg: string) -> boolean
  3321. `;
  3322. const result = extractFromSource('types.luau', code);
  3323. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3324. const vector = aliases.find((a) => a.name === 'Vector');
  3325. expect(vector).toBeDefined();
  3326. expect(vector?.isExported).toBe(true);
  3327. const handler = aliases.find((a) => a.name === 'Handler');
  3328. expect(handler).toBeDefined();
  3329. expect(handler?.isExported).toBe(false);
  3330. });
  3331. });
  3332. describe('Typed functions and methods', () => {
  3333. it('should capture typed signatures and split methods by receiver', () => {
  3334. const code = `
  3335. function configure(opts: { debug: boolean }): boolean
  3336. return opts.debug
  3337. end
  3338. function Client:fetch(path: string): Response
  3339. return path
  3340. end
  3341. `;
  3342. const result = extractFromSource('client.luau', code);
  3343. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  3344. expect(configure?.language).toBe('luau');
  3345. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  3346. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  3347. expect(fetch?.qualifiedName).toBe('Client::fetch');
  3348. });
  3349. });
  3350. describe('Imports and variables', () => {
  3351. it('should extract string and Roblox instance-path require imports', () => {
  3352. const code = `
  3353. local http = require("http")
  3354. local Signal = require(script.Parent.Signal)
  3355. local count = 0
  3356. `;
  3357. const result = extractFromSource('mod.luau', code);
  3358. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3359. expect(imports).toContain('http'); // string require
  3360. expect(imports).toContain('Signal'); // Roblox instance-path require
  3361. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3362. expect(vars).toContain('count');
  3363. });
  3364. });
  3365. });
  3366. // =============================================================================
  3367. // Objective-C
  3368. // =============================================================================
  3369. describe('Objective-C Extraction', () => {
  3370. const sample = `
  3371. #import <Foundation/Foundation.h>
  3372. #import "MyClass.h"
  3373. @interface MyClass : NSObject <NSCopying>
  3374. @property (nonatomic, copy) NSString *name;
  3375. - (void)greet;
  3376. - (void)doThing:(id)x with:(id)y;
  3377. + (instancetype)shared;
  3378. @end
  3379. @implementation MyClass
  3380. - (void)greet {
  3381. NSLog(@"Hello");
  3382. [self doWork];
  3383. }
  3384. - (void)doThing:(id)x with:(id)y {
  3385. [self notify:x];
  3386. }
  3387. + (instancetype)shared {
  3388. return [[MyClass alloc] init];
  3389. }
  3390. @end
  3391. void helperFunction(int count) {
  3392. MyClass *obj = [MyClass shared];
  3393. [obj greet];
  3394. }
  3395. `;
  3396. it('should extract classes, methods, functions, and imports', () => {
  3397. const result = extractFromSource('App.m', sample);
  3398. const classes = result.nodes.filter((n) => n.kind === 'class');
  3399. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  3400. const methods = result.nodes.filter((n) => n.kind === 'method');
  3401. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  3402. const shared = methods.find((m) => m.name === 'shared');
  3403. expect(shared?.isStatic).toBe(true);
  3404. const properties = result.nodes.filter((n) => n.kind === 'property');
  3405. expect(properties.some((p) => p.name === 'name')).toBe(true);
  3406. const functions = result.nodes.filter((n) => n.kind === 'function');
  3407. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  3408. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3409. expect(imports).toContain('Foundation/Foundation.h');
  3410. expect(imports).toContain('MyClass.h');
  3411. });
  3412. it('should record inheritance and protocol conformance', () => {
  3413. const result = extractFromSource('App.m', sample);
  3414. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  3415. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  3416. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  3417. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  3418. });
  3419. it('should record message sends and C calls', () => {
  3420. const result = extractFromSource('App.m', sample);
  3421. const calls = result.unresolvedReferences
  3422. .filter((r) => r.referenceKind === 'calls')
  3423. .map((r) => r.referenceName);
  3424. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  3425. });
  3426. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  3427. // Regression for the gap discovered post-#165: message_expression's
  3428. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  3429. // so calls never resolved to multi-part method definitions like
  3430. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  3431. // must match the method-definition name with full keywords + trailing colons.
  3432. const code = `
  3433. @implementation Caller
  3434. - (void)demo {
  3435. NSMutableDictionary *d = [NSMutableDictionary new];
  3436. [d setObject:@"v" forKey:@"k"];
  3437. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  3438. [self touchesBegan:nil withEvent:nil];
  3439. }
  3440. @end
  3441. `;
  3442. const result = extractFromSource('Caller.m', code);
  3443. const calls = result.unresolvedReferences
  3444. .filter((r) => r.referenceKind === 'calls')
  3445. .map((r) => r.referenceName);
  3446. expect(calls).toEqual(
  3447. expect.arrayContaining([
  3448. 'd.setObject:forKey:',
  3449. 'd.setObject:forKey:withRetry:',
  3450. 'touchesBegan:withEvent:',
  3451. ])
  3452. );
  3453. });
  3454. it('should not classify pure C headers with @end in comments as objc', () => {
  3455. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  3456. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  3457. });
  3458. it('should extract protocol declarations', () => {
  3459. const code = `
  3460. @protocol DataSource <NSObject>
  3461. - (NSInteger)numberOfItems;
  3462. @end
  3463. `;
  3464. const result = extractFromSource('DataSource.h', code);
  3465. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  3466. expect(protocol).toBeDefined();
  3467. });
  3468. it('should report Objective-C as supported', () => {
  3469. expect(isLanguageSupported('objc')).toBe(true);
  3470. expect(getSupportedLanguages()).toContain('objc');
  3471. });
  3472. });