extraction.test.ts 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205
  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, isSourceFile } 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('extracts type references from in-body local variable annotations', () => {
  200. // A function that uses a type ONLY in its body — `const items: Foo[] = []` —
  201. // still depends on Foo. The body walker used to capture calls but never type
  202. // annotations, so impact / `affected` missed the dependency. Must cover
  203. // function, class-method, and object-literal-method bodies — and must NOT
  204. // turn the locals themselves into graph nodes (that would explode the graph).
  205. const code = `
  206. import { Foo } from './types';
  207. export function build(): void {
  208. const items: Foo[] = [];
  209. void items;
  210. }
  211. export class K {
  212. run(): void {
  213. const a: Foo = { x: 1 };
  214. void a;
  215. }
  216. }
  217. export const handler = {
  218. handle(): void {
  219. const b: Foo = { x: 1 };
  220. void b;
  221. },
  222. };
  223. `;
  224. const result = extractFromSource('inbody.ts', code);
  225. const fooRefs = result.unresolvedReferences.filter(
  226. (r) => r.referenceKind === 'references' && r.referenceName === 'Foo'
  227. );
  228. // One per body scope: build(), K.run(), handler.handle().
  229. expect(fooRefs.length).toBeGreaterThanOrEqual(3);
  230. // Each reference is attributed to its enclosing function/method node — never
  231. // to a local-variable node, because locals are intentionally not extracted.
  232. const byId = new Map(result.nodes.map((n) => [n.id, n]));
  233. for (const ref of fooRefs) {
  234. const owner = byId.get(ref.fromNodeId);
  235. expect(owner).toBeDefined();
  236. expect(['function', 'method']).toContain(owner!.kind);
  237. }
  238. // The locals (items/a/b) must not leak in as symbols.
  239. expect(result.nodes.some((n) => ['items', 'a', 'b'].includes(n.name))).toBe(false);
  240. });
  241. it('should track function calls', () => {
  242. const code = `
  243. function main() {
  244. const result = processData();
  245. console.log(result);
  246. }
  247. `;
  248. const result = extractFromSource('main.ts', code);
  249. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  250. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  251. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  252. });
  253. });
  254. describe('Arrow Function Export Extraction', () => {
  255. it('should extract exported arrow functions assigned to const', () => {
  256. const code = `
  257. export const useAuth = (): AuthContextValue => {
  258. return useContext(AuthContext);
  259. };
  260. `;
  261. const result = extractFromSource('hooks.ts', code);
  262. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  263. expect(funcNode).toBeDefined();
  264. expect(funcNode).toMatchObject({
  265. kind: 'function',
  266. name: 'useAuth',
  267. isExported: true,
  268. });
  269. });
  270. it('should extract exported function expressions assigned to const', () => {
  271. const code = `
  272. export const processData = function(input: string): string {
  273. return input.trim();
  274. };
  275. `;
  276. const result = extractFromSource('utils.ts', code);
  277. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  278. expect(funcNode).toBeDefined();
  279. expect(funcNode).toMatchObject({
  280. kind: 'function',
  281. name: 'processData',
  282. isExported: true,
  283. });
  284. });
  285. it('should not extract non-exported arrow functions as exported', () => {
  286. const code = `
  287. const internalHelper = () => {
  288. return 42;
  289. };
  290. `;
  291. const result = extractFromSource('internal.ts', code);
  292. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  293. expect(helperNode).toBeDefined();
  294. expect(helperNode?.isExported).toBeFalsy();
  295. });
  296. it('should still skip truly anonymous arrow functions', () => {
  297. const code = `
  298. const items = [1, 2, 3].map((x) => x * 2);
  299. `;
  300. const result = extractFromSource('anon.ts', code);
  301. // The inline arrow function passed to .map() has no variable_declarator parent
  302. // and should remain anonymous (skipped)
  303. const anonFunctions = result.nodes.filter(
  304. (n) => n.kind === 'function' && n.name === '<anonymous>'
  305. );
  306. expect(anonFunctions).toHaveLength(0);
  307. });
  308. it('should extract multiple exported arrow functions from the same file', () => {
  309. const code = `
  310. export const add = (a: number, b: number): number => a + b;
  311. export const subtract = (a: number, b: number): number => a - b;
  312. const internal = () => 'not exported';
  313. `;
  314. const result = extractFromSource('math.ts', code);
  315. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  316. expect(exported).toHaveLength(2);
  317. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  318. const internalNode = result.nodes.find((n) => n.name === 'internal');
  319. expect(internalNode).toBeDefined();
  320. expect(internalNode?.isExported).toBeFalsy();
  321. });
  322. it('should extract arrow functions in JavaScript files', () => {
  323. const code = `
  324. export const fetchData = async () => {
  325. const response = await fetch('/api/data');
  326. return response.json();
  327. };
  328. `;
  329. const result = extractFromSource('api.js', code);
  330. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  331. expect(funcNode).toBeDefined();
  332. expect(funcNode).toMatchObject({
  333. kind: 'function',
  334. name: 'fetchData',
  335. isExported: true,
  336. });
  337. });
  338. });
  339. describe('Type Alias Extraction', () => {
  340. it('should extract exported type aliases in TypeScript', () => {
  341. const code = `
  342. export type AuthContextValue = {
  343. user: User | null;
  344. login: () => void;
  345. logout: () => void;
  346. };
  347. `;
  348. const result = extractFromSource('types.ts', code);
  349. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  350. expect(typeNode).toMatchObject({
  351. kind: 'type_alias',
  352. name: 'AuthContextValue',
  353. isExported: true,
  354. });
  355. });
  356. it('should extract non-exported type aliases', () => {
  357. const code = `
  358. type InternalState = {
  359. loading: boolean;
  360. error: string | null;
  361. };
  362. `;
  363. const result = extractFromSource('internal.ts', code);
  364. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  365. expect(typeNode).toMatchObject({
  366. kind: 'type_alias',
  367. name: 'InternalState',
  368. isExported: false,
  369. });
  370. });
  371. it('should extract multiple type aliases from the same file', () => {
  372. const code = `
  373. export type UnitSystem = 'metric' | 'imperial';
  374. export type DateFormat = 'ISO' | 'US' | 'EU';
  375. type Internal = string;
  376. `;
  377. const result = extractFromSource('config.ts', code);
  378. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  379. expect(typeAliases).toHaveLength(3);
  380. const exported = typeAliases.filter((n) => n.isExported);
  381. expect(exported).toHaveLength(2);
  382. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  383. });
  384. });
  385. describe('Exported Variable Extraction', () => {
  386. it('should extract exported const with call expression (Zustand store)', () => {
  387. const code = `
  388. export const useUIStore = create<UIState>((set) => ({
  389. isOpen: false,
  390. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  391. }));
  392. `;
  393. const result = extractFromSource('store.ts', code);
  394. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  395. expect(varNode).toBeDefined();
  396. expect(varNode?.isExported).toBe(true);
  397. });
  398. it('should extract exported const with object literal', () => {
  399. const code = `
  400. export const config = {
  401. apiUrl: 'https://api.example.com',
  402. timeout: 5000,
  403. };
  404. `;
  405. const result = extractFromSource('config.ts', code);
  406. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  407. expect(varNode).toBeDefined();
  408. expect(varNode?.isExported).toBe(true);
  409. });
  410. it('should extract exported const with array literal', () => {
  411. const code = `
  412. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  413. `;
  414. const result = extractFromSource('constants.ts', code);
  415. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  416. expect(varNode).toBeDefined();
  417. expect(varNode?.isExported).toBe(true);
  418. });
  419. it('should extract exported const with primitive value', () => {
  420. const code = `
  421. export const MAX_RETRIES = 3;
  422. export const API_VERSION = "v2";
  423. `;
  424. const result = extractFromSource('constants.ts', code);
  425. const variables = result.nodes.filter((n) => n.kind === 'constant');
  426. expect(variables).toHaveLength(2);
  427. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  428. });
  429. it('should NOT duplicate arrow functions as both function and variable', () => {
  430. const code = `
  431. export const useAuth = () => {
  432. return useContext(AuthContext);
  433. };
  434. `;
  435. const result = extractFromSource('hooks.ts', code);
  436. // Should be extracted as function (from arrow function handler), NOT as variable
  437. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  438. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  439. expect(funcNodes).toHaveLength(1);
  440. expect(varNodes).toHaveLength(0);
  441. });
  442. it('should extract non-exported const as non-exported variable', () => {
  443. const code = `
  444. const internalConfig = {
  445. debug: true,
  446. };
  447. `;
  448. const result = extractFromSource('internal.ts', code);
  449. // Non-exported const at file level should be extracted as a constant (not exported)
  450. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  451. expect(varNodes).toHaveLength(1);
  452. expect(varNodes[0]?.isExported).toBeFalsy();
  453. });
  454. it('should extract Zod schema exports', () => {
  455. const code = `
  456. export const userSchema = z.object({
  457. id: z.string(),
  458. name: z.string(),
  459. email: z.string().email(),
  460. });
  461. `;
  462. const result = extractFromSource('schemas.ts', code);
  463. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  464. expect(varNode).toBeDefined();
  465. expect(varNode?.isExported).toBe(true);
  466. });
  467. it('should extract XState machine exports', () => {
  468. const code = `
  469. export const authMachine = createMachine({
  470. id: "auth",
  471. initial: "idle",
  472. states: {
  473. idle: {},
  474. authenticated: {},
  475. },
  476. });
  477. `;
  478. const result = extractFromSource('machine.ts', code);
  479. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  480. expect(varNode).toBeDefined();
  481. expect(varNode?.isExported).toBe(true);
  482. });
  483. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  484. const code = `
  485. import { getTokenMp } from './api/upload';
  486. const token = getTokenMp();
  487. `;
  488. const result = extractFromSource('app.ts', code);
  489. const call = result.unresolvedReferences.find(
  490. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  491. );
  492. expect(call).toBeDefined();
  493. });
  494. });
  495. describe('File Node Extraction', () => {
  496. it('should create a file-kind node for each parsed file', () => {
  497. const code = `
  498. export function greet(name: string): string {
  499. return "Hello " + name;
  500. }
  501. `;
  502. const result = extractFromSource('greeter.ts', code);
  503. const fileNode = result.nodes.find((n) => n.kind === 'file');
  504. expect(fileNode).toBeDefined();
  505. expect(fileNode?.name).toBe('greeter.ts');
  506. expect(fileNode?.filePath).toBe('greeter.ts');
  507. expect(fileNode?.language).toBe('typescript');
  508. expect(fileNode?.startLine).toBe(1);
  509. });
  510. it('should create file nodes for Python files', () => {
  511. const code = `
  512. def main():
  513. pass
  514. `;
  515. const result = extractFromSource('main.py', code);
  516. const fileNode = result.nodes.find((n) => n.kind === 'file');
  517. expect(fileNode).toBeDefined();
  518. expect(fileNode?.name).toBe('main.py');
  519. expect(fileNode?.language).toBe('python');
  520. });
  521. it('should create containment edges from file node to top-level declarations', () => {
  522. const code = `
  523. export function foo() {}
  524. export function bar() {}
  525. `;
  526. const result = extractFromSource('fns.ts', code);
  527. const fileNode = result.nodes.find((n) => n.kind === 'file');
  528. expect(fileNode).toBeDefined();
  529. // There should be contains edges from the file node to each function
  530. const containsEdges = result.edges.filter(
  531. (e) => e.source === fileNode?.id && e.kind === 'contains'
  532. );
  533. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  534. });
  535. });
  536. describe('Python Extraction', () => {
  537. it('should extract function definitions', () => {
  538. const code = `
  539. def calculate_total(items: list, tax_rate: float) -> float:
  540. """Calculate total with tax."""
  541. subtotal = sum(item.price for item in items)
  542. return subtotal * (1 + tax_rate)
  543. `;
  544. const result = extractFromSource('calc.py', code);
  545. const fileNode = result.nodes.find((n) => n.kind === 'file');
  546. expect(fileNode).toBeDefined();
  547. const funcNode = result.nodes.find((n) => n.kind === 'function');
  548. expect(funcNode).toMatchObject({
  549. kind: 'function',
  550. name: 'calculate_total',
  551. language: 'python',
  552. });
  553. });
  554. it('should extract class definitions', () => {
  555. const code = `
  556. class UserService:
  557. """Service for managing users."""
  558. def __init__(self, db):
  559. self.db = db
  560. def get_user(self, user_id: str) -> User:
  561. return self.db.find_user(user_id)
  562. `;
  563. const result = extractFromSource('service.py', code);
  564. const classNode = result.nodes.find((n) => n.kind === 'class');
  565. expect(classNode).toBeDefined();
  566. expect(classNode?.name).toBe('UserService');
  567. });
  568. });
  569. describe('Go Extraction', () => {
  570. it('should extract function declarations', () => {
  571. const code = `
  572. package main
  573. func ProcessOrder(order Order) (Receipt, error) {
  574. // Process the order
  575. return Receipt{}, nil
  576. }
  577. `;
  578. const result = extractFromSource('main.go', code);
  579. const funcNode = result.nodes.find((n) => n.kind === 'function');
  580. expect(funcNode).toBeDefined();
  581. expect(funcNode?.name).toBe('ProcessOrder');
  582. });
  583. it('should extract method declarations', () => {
  584. const code = `
  585. package main
  586. type Service struct {
  587. db *Database
  588. }
  589. func (s *Service) GetUser(id string) (*User, error) {
  590. return s.db.FindUser(id)
  591. }
  592. `;
  593. const result = extractFromSource('service.go', code);
  594. const methodNode = result.nodes.find((n) => n.kind === 'method');
  595. expect(methodNode).toBeDefined();
  596. expect(methodNode?.name).toBe('GetUser');
  597. });
  598. });
  599. describe('Rust Extraction', () => {
  600. it('should extract function declarations', () => {
  601. const code = `
  602. pub fn process_data(input: &str) -> Result<Output, Error> {
  603. // Process data
  604. Ok(Output::new())
  605. }
  606. `;
  607. const result = extractFromSource('lib.rs', code);
  608. const funcNode = result.nodes.find((n) => n.kind === 'function');
  609. expect(funcNode).toBeDefined();
  610. expect(funcNode?.name).toBe('process_data');
  611. expect(funcNode?.visibility).toBe('public');
  612. });
  613. it('should extract struct declarations', () => {
  614. const code = `
  615. pub struct User {
  616. pub id: String,
  617. pub name: String,
  618. email: String,
  619. }
  620. `;
  621. const result = extractFromSource('models.rs', code);
  622. const structNode = result.nodes.find((n) => n.kind === 'struct');
  623. expect(structNode).toBeDefined();
  624. expect(structNode?.name).toBe('User');
  625. });
  626. it('should extract trait declarations', () => {
  627. const code = `
  628. pub trait Repository {
  629. fn find(&self, id: &str) -> Option<Entity>;
  630. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  631. }
  632. `;
  633. const result = extractFromSource('traits.rs', code);
  634. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  635. expect(traitNode).toBeDefined();
  636. expect(traitNode?.name).toBe('Repository');
  637. });
  638. it('should extract impl Trait for Type as implements edges', () => {
  639. const code = `
  640. pub struct MyCache {}
  641. pub trait Cache {
  642. fn get(&self, key: &str) -> Option<String>;
  643. }
  644. impl Cache for MyCache {
  645. fn get(&self, key: &str) -> Option<String> {
  646. None
  647. }
  648. }
  649. `;
  650. const result = extractFromSource('cache.rs', code);
  651. // Should have an unresolved reference for implements
  652. const implRef = result.unresolvedReferences.find(
  653. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  654. );
  655. expect(implRef).toBeDefined();
  656. // The struct MyCache should be the source
  657. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  658. expect(myCacheNode).toBeDefined();
  659. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  660. });
  661. it('should extract trait supertraits as extends references', () => {
  662. const code = `
  663. pub trait Display {}
  664. pub trait Error: Display {
  665. fn description(&self) -> &str;
  666. }
  667. `;
  668. const result = extractFromSource('error.rs', code);
  669. const extendsRef = result.unresolvedReferences.find(
  670. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  671. );
  672. expect(extendsRef).toBeDefined();
  673. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  674. expect(errorTrait).toBeDefined();
  675. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  676. });
  677. it('should not create implements edges for plain impl blocks', () => {
  678. const code = `
  679. pub struct Counter {
  680. count: u32,
  681. }
  682. impl Counter {
  683. pub fn new() -> Counter {
  684. Counter { count: 0 }
  685. }
  686. pub fn increment(&mut self) {
  687. self.count += 1;
  688. }
  689. }
  690. `;
  691. const result = extractFromSource('counter.rs', code);
  692. // Should have no implements references (no trait involved)
  693. const implRefs = result.unresolvedReferences.filter(
  694. (r) => r.referenceKind === 'implements'
  695. );
  696. expect(implRefs).toHaveLength(0);
  697. });
  698. });
  699. describe('Java Extraction', () => {
  700. it('should extract class declarations', () => {
  701. const code = `
  702. public class UserService {
  703. private final UserRepository repository;
  704. public UserService(UserRepository repository) {
  705. this.repository = repository;
  706. }
  707. public User getUser(String id) {
  708. return repository.findById(id);
  709. }
  710. }
  711. `;
  712. const result = extractFromSource('UserService.java', code);
  713. const classNode = result.nodes.find((n) => n.kind === 'class');
  714. expect(classNode).toBeDefined();
  715. expect(classNode?.name).toBe('UserService');
  716. expect(classNode?.visibility).toBe('public');
  717. });
  718. it('should extract method declarations', () => {
  719. const code = `
  720. public class Calculator {
  721. public static int add(int a, int b) {
  722. return a + b;
  723. }
  724. }
  725. `;
  726. const result = extractFromSource('Calculator.java', code);
  727. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  728. expect(methodNode).toBeDefined();
  729. expect(methodNode?.isStatic).toBe(true);
  730. });
  731. it('wraps top-level declarations in a namespace from package_declaration', () => {
  732. const code = `
  733. package com.example.foo;
  734. public class Bar {
  735. public String greet() { return "hi"; }
  736. }
  737. `;
  738. const result = extractFromSource('Bar.java', code);
  739. const ns = result.nodes.find((n) => n.kind === 'namespace');
  740. expect(ns?.name).toBe('com.example.foo');
  741. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  742. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  743. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  744. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  745. });
  746. it('does not wrap when no package is declared', () => {
  747. const code = `
  748. public class Bar {
  749. public String greet() { return "hi"; }
  750. }
  751. `;
  752. const result = extractFromSource('Bar.java', code);
  753. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  754. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  755. expect(cls?.qualifiedName).toBe('Bar');
  756. });
  757. it('extracts anonymous-class overrides from `new T() { ... }`', () => {
  758. // The pattern that breaks the trace through `strategy.foo()` in
  759. // libraries like guava's Splitter: the lambda-returned anonymous
  760. // class overrides abstract methods on the base, but without
  761. // extracting those overrides the interface→impl synthesizer has
  762. // nothing to bridge.
  763. const code = `
  764. package com.example;
  765. abstract class Base {
  766. abstract int compute(int x);
  767. }
  768. public class Factory {
  769. public Base make() {
  770. return new Base() {
  771. @Override
  772. int compute(int x) { return x + 1; }
  773. };
  774. }
  775. }
  776. `;
  777. const result = extractFromSource('Factory.java', code);
  778. const anon = result.nodes.find((n) => n.kind === 'class' && /Base\$anon@/.test(n.name));
  779. expect(anon, 'anonymous Base subclass should be extracted as a class').toBeDefined();
  780. const compute = result.nodes.find(
  781. (n) => n.kind === 'method' && n.name === 'compute' && n.qualifiedName.includes('$anon@')
  782. );
  783. expect(compute, 'override method should be a method on the anon class').toBeDefined();
  784. expect(compute!.qualifiedName).toContain('Factory::make::<Base$anon@');
  785. expect(compute!.qualifiedName.endsWith('::compute')).toBe(true);
  786. // Anon class must extend Base so Phase 5.5 (interface-impl) can bridge.
  787. const extendsRef = result.unresolvedReferences.find(
  788. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base' && r.fromNodeId === anon!.id
  789. );
  790. expect(extendsRef, 'anon class should carry an `extends Base` reference').toBeDefined();
  791. // The enclosing `make` method still emits an instantiates edge to Base —
  792. // anon extraction must not swallow that signal.
  793. const instantiatesRef = result.unresolvedReferences.find(
  794. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Base'
  795. );
  796. expect(instantiatesRef, 'enclosing method should still instantiate Base').toBeDefined();
  797. });
  798. it('extracts anonymous-class overrides inside a lambda body', () => {
  799. // The exact guava pattern: a lambda is passed to a constructor, and the
  800. // lambda body returns `new T() { @Override ... }`. The anon class must
  801. // still surface even though it sits inside a lambda_expression node.
  802. const code = `
  803. package com.example;
  804. interface Strategy {
  805. java.util.Iterator<String> iterator(String s);
  806. }
  807. abstract class BaseIter implements java.util.Iterator<String> {
  808. abstract int separatorStart(int start);
  809. }
  810. public class Splitter {
  811. private final Strategy strategy;
  812. public Splitter(Strategy s) { this.strategy = s; }
  813. public static Splitter on(char c) {
  814. return new Splitter((seq) ->
  815. new BaseIter() {
  816. @Override
  817. int separatorStart(int start) { return start + 1; }
  818. @Override public boolean hasNext() { return false; }
  819. @Override public String next() { return null; }
  820. });
  821. }
  822. }
  823. `;
  824. const result = extractFromSource('Splitter.java', code);
  825. const anon = result.nodes.find((n) => n.kind === 'class' && /BaseIter\$anon@/.test(n.name));
  826. expect(anon, 'anon BaseIter inside the lambda body should be extracted').toBeDefined();
  827. const sepStart = result.nodes.find(
  828. (n) =>
  829. n.kind === 'method' &&
  830. n.name === 'separatorStart' &&
  831. n.qualifiedName.includes('$anon@')
  832. );
  833. expect(sepStart, 'override inside the lambda-returned anon class should be a method node').toBeDefined();
  834. });
  835. });
  836. describe('C# Extraction', () => {
  837. it('should extract class declarations', () => {
  838. const code = `
  839. public class OrderService
  840. {
  841. private readonly IOrderRepository _repository;
  842. public OrderService(IOrderRepository repository)
  843. {
  844. _repository = repository;
  845. }
  846. public async Task<Order> GetOrderAsync(string id)
  847. {
  848. return await _repository.FindByIdAsync(id);
  849. }
  850. }
  851. `;
  852. const result = extractFromSource('OrderService.cs', code);
  853. const classNode = result.nodes.find((n) => n.kind === 'class');
  854. expect(classNode).toBeDefined();
  855. expect(classNode?.name).toBe('OrderService');
  856. expect(classNode?.visibility).toBe('public');
  857. });
  858. });
  859. describe('PHP Extraction', () => {
  860. it('should extract class declarations', () => {
  861. const code = `<?php
  862. class UserController
  863. {
  864. private UserService $userService;
  865. public function __construct(UserService $userService)
  866. {
  867. $this->userService = $userService;
  868. }
  869. public function show(string $id): User
  870. {
  871. return $this->userService->find($id);
  872. }
  873. }
  874. `;
  875. const result = extractFromSource('UserController.php', code);
  876. const classNode = result.nodes.find((n) => n.kind === 'class');
  877. expect(classNode).toBeDefined();
  878. expect(classNode?.name).toBe('UserController');
  879. });
  880. it('should extract class inheritance (extends) and interface implementation', () => {
  881. const code = `<?php
  882. class ChildController extends BaseController implements Serializable, JsonSerializable
  883. {
  884. public function serialize(): string
  885. {
  886. return json_encode($this);
  887. }
  888. }
  889. `;
  890. const result = extractFromSource('ChildController.php', code);
  891. const classNode = result.nodes.find((n) => n.kind === 'class');
  892. expect(classNode).toBeDefined();
  893. expect(classNode?.name).toBe('ChildController');
  894. const extendsRef = result.unresolvedReferences.find(
  895. (r) => r.referenceKind === 'extends'
  896. );
  897. expect(extendsRef).toBeDefined();
  898. expect(extendsRef?.referenceName).toBe('BaseController');
  899. const implementsRefs = result.unresolvedReferences.filter(
  900. (r) => r.referenceKind === 'implements'
  901. );
  902. expect(implementsRefs.length).toBe(2);
  903. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  904. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  905. });
  906. });
  907. describe('Swift Extraction', () => {
  908. it('should extract class declarations', () => {
  909. const code = `
  910. public class NetworkManager {
  911. private let session: URLSession
  912. public init(session: URLSession = .shared) {
  913. self.session = session
  914. }
  915. public func fetchData(from url: URL) async throws -> Data {
  916. let (data, _) = try await session.data(from: url)
  917. return data
  918. }
  919. }
  920. `;
  921. const result = extractFromSource('NetworkManager.swift', code);
  922. const classNode = result.nodes.find((n) => n.kind === 'class');
  923. expect(classNode).toBeDefined();
  924. expect(classNode?.name).toBe('NetworkManager');
  925. });
  926. it('should extract function declarations', () => {
  927. const code = `
  928. func calculateSum(_ numbers: [Int]) -> Int {
  929. return numbers.reduce(0, +)
  930. }
  931. public func formatCurrency(amount: Double) -> String {
  932. return String(format: "$%.2f", amount)
  933. }
  934. `;
  935. const result = extractFromSource('utils.swift', code);
  936. const functions = result.nodes.filter((n) => n.kind === 'function');
  937. expect(functions.length).toBeGreaterThanOrEqual(1);
  938. });
  939. it('should extract struct declarations', () => {
  940. const code = `
  941. public struct User {
  942. let id: UUID
  943. var name: String
  944. var email: String
  945. func displayName() -> String {
  946. return name
  947. }
  948. }
  949. `;
  950. const result = extractFromSource('User.swift', code);
  951. const structNode = result.nodes.find((n) => n.kind === 'struct');
  952. expect(structNode).toBeDefined();
  953. expect(structNode?.name).toBe('User');
  954. });
  955. it('should extract protocol declarations', () => {
  956. const code = `
  957. public protocol Repository {
  958. associatedtype Entity
  959. func find(id: String) async throws -> Entity?
  960. func save(_ entity: Entity) async throws
  961. }
  962. `;
  963. const result = extractFromSource('Repository.swift', code);
  964. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  965. expect(protocolNode).toBeDefined();
  966. expect(protocolNode?.name).toBe('Repository');
  967. });
  968. it('should extract class inheritance and protocol conformance', () => {
  969. const code = `
  970. class DataRequest: Request {
  971. func validate() {}
  972. }
  973. class UploadRequest: DataRequest, Sendable {
  974. func upload() {}
  975. }
  976. enum AFError: Error {
  977. case invalidURL
  978. }
  979. struct HTTPMethod: RawRepresentable {
  980. let rawValue: String
  981. }
  982. protocol UploadConvertible: URLRequestConvertible {
  983. func asURLRequest() throws -> URLRequest
  984. }
  985. `;
  986. const result = extractFromSource('Inheritance.swift', code);
  987. const extendsRefs = result.unresolvedReferences.filter(
  988. (r) => r.referenceKind === 'extends'
  989. );
  990. // DataRequest extends Request
  991. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  992. // UploadRequest extends DataRequest and Sendable
  993. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  994. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  995. // AFError extends Error
  996. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  997. // HTTPMethod extends RawRepresentable
  998. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  999. // UploadConvertible extends URLRequestConvertible
  1000. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  1001. });
  1002. });
  1003. describe('Kotlin Extraction', () => {
  1004. it('should extract class declarations', () => {
  1005. const code = `
  1006. class UserRepository(private val database: Database) {
  1007. fun findById(id: String): User? {
  1008. return database.query("SELECT * FROM users WHERE id = ?", id)
  1009. }
  1010. suspend fun save(user: User) {
  1011. database.insert(user)
  1012. }
  1013. }
  1014. `;
  1015. const result = extractFromSource('UserRepository.kt', code);
  1016. const classNode = result.nodes.find((n) => n.kind === 'class');
  1017. expect(classNode).toBeDefined();
  1018. expect(classNode?.name).toBe('UserRepository');
  1019. });
  1020. it('should extract function declarations', () => {
  1021. const code = `
  1022. fun calculateTotal(items: List<Item>): Double {
  1023. return items.sumOf { it.price }
  1024. }
  1025. suspend fun fetchUserData(userId: String): User {
  1026. return api.getUser(userId)
  1027. }
  1028. `;
  1029. const result = extractFromSource('utils.kt', code);
  1030. const functions = result.nodes.filter((n) => n.kind === 'function');
  1031. expect(functions.length).toBeGreaterThanOrEqual(1);
  1032. });
  1033. it('should detect suspend functions as async', () => {
  1034. const code = `
  1035. suspend fun loadData(): List<String> {
  1036. delay(1000)
  1037. return listOf("a", "b", "c")
  1038. }
  1039. `;
  1040. const result = extractFromSource('loader.kt', code);
  1041. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1042. expect(funcNode).toBeDefined();
  1043. expect(funcNode?.isAsync).toBe(true);
  1044. });
  1045. it('should extract fun interface declarations', () => {
  1046. const code = `
  1047. fun interface OnObjectRetainedListener {
  1048. fun onObjectRetained()
  1049. }
  1050. `;
  1051. const result = extractFromSource('listener.kt', code);
  1052. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1053. expect(ifaceNode).toBeDefined();
  1054. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  1055. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1056. expect(methodNode).toBeDefined();
  1057. expect(methodNode?.name).toBe('onObjectRetained');
  1058. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  1059. });
  1060. it('should extract complex fun interface with nested classes', () => {
  1061. const code = `
  1062. fun interface EventListener {
  1063. fun onEvent(event: Event)
  1064. sealed class Event {
  1065. class DumpingHeap : Event()
  1066. }
  1067. }
  1068. `;
  1069. const result = extractFromSource('events.kt', code);
  1070. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1071. expect(ifaceNode).toBeDefined();
  1072. expect(ifaceNode?.name).toBe('EventListener');
  1073. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  1074. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  1075. expect(eventClass).toBeDefined();
  1076. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  1077. expect(dumpingHeap).toBeDefined();
  1078. });
  1079. it('should not affect regular function declarations', () => {
  1080. const code = `
  1081. fun interface MyCallback {
  1082. fun invoke(value: Int)
  1083. }
  1084. fun regularFunction(): String {
  1085. return "hello"
  1086. }
  1087. `;
  1088. const result = extractFromSource('mixed.kt', code);
  1089. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1090. expect(ifaceNode).toBeDefined();
  1091. expect(ifaceNode?.name).toBe('MyCallback');
  1092. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1093. expect(funcNode).toBeDefined();
  1094. expect(funcNode?.name).toBe('regularFunction');
  1095. });
  1096. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  1097. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  1098. // misparse: function_declaration > ERROR("interface Name {") instead of
  1099. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  1100. const code = `
  1101. import java.io.IOException
  1102. fun interface Interceptor {
  1103. @Throws(IOException::class)
  1104. fun intercept(chain: Chain): Response
  1105. }
  1106. `;
  1107. const result = extractFromSource('interceptor.kt', code);
  1108. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1109. expect(ifaceNode).toBeDefined();
  1110. expect(ifaceNode?.name).toBe('Interceptor');
  1111. });
  1112. it('should extract methods from interface with nested fun interface', () => {
  1113. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  1114. // the parent body as ERROR. Methods inside should still be extracted.
  1115. const code = `
  1116. interface WebSocket {
  1117. fun request(): Request
  1118. fun send(text: String): Boolean
  1119. fun cancel()
  1120. fun interface Factory {
  1121. fun newWebSocket(request: Request): WebSocket
  1122. }
  1123. }
  1124. `;
  1125. const result = extractFromSource('websocket.kt', code);
  1126. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  1127. expect(wsIface).toBeDefined();
  1128. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  1129. const methodNames = methods.map((m) => m.name);
  1130. expect(methodNames).toContain('request');
  1131. expect(methodNames).toContain('send');
  1132. expect(methodNames).toContain('cancel');
  1133. });
  1134. it('wraps top-level declarations in a namespace from package_header', () => {
  1135. const code = `
  1136. package com.example.foo
  1137. class Bar {
  1138. fun greet(): String = "hi"
  1139. }
  1140. fun util(): Int = 42
  1141. `;
  1142. const result = extractFromSource('Bar.kt', code);
  1143. const ns = result.nodes.find((n) => n.kind === 'namespace');
  1144. expect(ns?.name).toBe('com.example.foo');
  1145. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1146. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  1147. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  1148. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  1149. const util = result.nodes.find((n) => n.kind === 'function' && n.name === 'util');
  1150. expect(util?.qualifiedName).toBe('com.example.foo::util');
  1151. });
  1152. it('handles a single-segment package', () => {
  1153. const code = `
  1154. package foo
  1155. class Bar
  1156. `;
  1157. const result = extractFromSource('Bar.kt', code);
  1158. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1159. expect(cls?.qualifiedName).toBe('foo::Bar');
  1160. });
  1161. it('does not wrap when no package is declared', () => {
  1162. const code = `
  1163. class Bar {
  1164. fun greet() = "hi"
  1165. }
  1166. `;
  1167. const result = extractFromSource('Bar.kt', code);
  1168. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  1169. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1170. expect(cls?.qualifiedName).toBe('Bar');
  1171. });
  1172. });
  1173. describe('Dart Extraction', () => {
  1174. it('should extract class declarations', () => {
  1175. const code = `
  1176. class UserService {
  1177. final Database _db;
  1178. Future<User> findById(String id) async {
  1179. return await _db.query(id);
  1180. }
  1181. void _privateMethod() {}
  1182. }
  1183. `;
  1184. const result = extractFromSource('service.dart', code);
  1185. const classNode = result.nodes.find((n) => n.kind === 'class');
  1186. expect(classNode).toBeDefined();
  1187. expect(classNode?.name).toBe('UserService');
  1188. expect(classNode?.visibility).toBe('public');
  1189. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1190. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1191. const findById = methodNodes.find((m) => m.name === 'findById');
  1192. expect(findById).toBeDefined();
  1193. expect(findById?.isAsync).toBe(true);
  1194. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1195. expect(privateMethod).toBeDefined();
  1196. expect(privateMethod?.visibility).toBe('private');
  1197. // Dart models a method body as a SIBLING of the signature, so the method
  1198. // node must be extended to span its body (not just the signature line) —
  1199. // required for body-level analysis (callees, the callback synthesizer).
  1200. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1201. });
  1202. it('should extract top-level function declarations', () => {
  1203. const code = `
  1204. void topLevelFunction(String name) {
  1205. print(name);
  1206. }
  1207. `;
  1208. const result = extractFromSource('utils.dart', code);
  1209. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1210. expect(funcNode).toBeDefined();
  1211. expect(funcNode?.name).toBe('topLevelFunction');
  1212. expect(funcNode?.language).toBe('dart');
  1213. });
  1214. it('should extract enum declarations', () => {
  1215. const code = `
  1216. enum Status { active, inactive, pending }
  1217. `;
  1218. const result = extractFromSource('models.dart', code);
  1219. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1220. expect(enumNode).toBeDefined();
  1221. expect(enumNode?.name).toBe('Status');
  1222. });
  1223. it('should extract mixin declarations', () => {
  1224. const code = `
  1225. mixin LoggerMixin {
  1226. void log(String message) {}
  1227. }
  1228. `;
  1229. const result = extractFromSource('mixins.dart', code);
  1230. const classNode = result.nodes.find((n) => n.kind === 'class');
  1231. expect(classNode).toBeDefined();
  1232. expect(classNode?.name).toBe('LoggerMixin');
  1233. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1234. expect(methodNode).toBeDefined();
  1235. expect(methodNode?.name).toBe('log');
  1236. });
  1237. it('should extract extension declarations', () => {
  1238. const code = `
  1239. extension StringExt on String {
  1240. bool get isBlank => trim().isEmpty;
  1241. }
  1242. `;
  1243. const result = extractFromSource('extensions.dart', code);
  1244. const classNode = result.nodes.find((n) => n.kind === 'class');
  1245. expect(classNode).toBeDefined();
  1246. expect(classNode?.name).toBe('StringExt');
  1247. });
  1248. it('should detect static methods', () => {
  1249. const code = `
  1250. class Utils {
  1251. static void doWork() {}
  1252. }
  1253. `;
  1254. const result = extractFromSource('utils.dart', code);
  1255. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1256. expect(methodNode).toBeDefined();
  1257. expect(methodNode?.name).toBe('doWork');
  1258. expect(methodNode?.isStatic).toBe(true);
  1259. });
  1260. it('should detect async functions', () => {
  1261. const code = `
  1262. Future<String> fetchData() async {
  1263. return await http.get('/data');
  1264. }
  1265. `;
  1266. const result = extractFromSource('api.dart', code);
  1267. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1268. expect(funcNode).toBeDefined();
  1269. expect(funcNode?.name).toBe('fetchData');
  1270. expect(funcNode?.isAsync).toBe(true);
  1271. });
  1272. it('should detect private visibility via underscore convention', () => {
  1273. const code = `
  1274. void _privateHelper() {}
  1275. void publicFunction() {}
  1276. `;
  1277. const result = extractFromSource('helpers.dart', code);
  1278. const functions = result.nodes.filter((n) => n.kind === 'function');
  1279. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1280. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1281. expect(privateFunc?.visibility).toBe('private');
  1282. expect(publicFunc?.visibility).toBe('public');
  1283. });
  1284. });
  1285. describe('Import Extraction', () => {
  1286. describe('TypeScript/JavaScript imports', () => {
  1287. it('should extract default imports', () => {
  1288. const code = `import React from 'react';`;
  1289. const result = extractFromSource('app.tsx', code);
  1290. const importNode = result.nodes.find((n) => n.kind === 'import');
  1291. expect(importNode).toBeDefined();
  1292. expect(importNode?.name).toBe('react');
  1293. expect(importNode?.signature).toBe("import React from 'react';");
  1294. });
  1295. it('should extract named imports', () => {
  1296. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1297. const result = extractFromSource('icons.tsx', code);
  1298. const importNode = result.nodes.find((n) => n.kind === 'import');
  1299. expect(importNode).toBeDefined();
  1300. expect(importNode?.name).toBe('@phosphor-icons/react');
  1301. expect(importNode?.signature).toContain('Bug');
  1302. expect(importNode?.signature).toContain('Database');
  1303. });
  1304. it('should extract namespace imports', () => {
  1305. const code = `import * as Icons from '@phosphor-icons/react';`;
  1306. const result = extractFromSource('icons.tsx', code);
  1307. const importNode = result.nodes.find((n) => n.kind === 'import');
  1308. expect(importNode).toBeDefined();
  1309. expect(importNode?.name).toBe('@phosphor-icons/react');
  1310. expect(importNode?.signature).toContain('* as Icons');
  1311. });
  1312. it('should extract side-effect imports', () => {
  1313. const code = `import './styles.css';`;
  1314. const result = extractFromSource('app.tsx', code);
  1315. const importNode = result.nodes.find((n) => n.kind === 'import');
  1316. expect(importNode).toBeDefined();
  1317. expect(importNode?.name).toBe('./styles.css');
  1318. });
  1319. it('should extract mixed imports (default + named)', () => {
  1320. const code = `import React, { useState, useEffect } from 'react';`;
  1321. const result = extractFromSource('app.tsx', code);
  1322. const importNode = result.nodes.find((n) => n.kind === 'import');
  1323. expect(importNode).toBeDefined();
  1324. expect(importNode?.name).toBe('react');
  1325. expect(importNode?.signature).toContain('React');
  1326. expect(importNode?.signature).toContain('useState');
  1327. expect(importNode?.signature).toContain('useEffect');
  1328. });
  1329. it('should extract multiple import statements', () => {
  1330. const code = `
  1331. import React from 'react';
  1332. import { Button } from './components';
  1333. import './styles.css';
  1334. `;
  1335. const result = extractFromSource('app.tsx', code);
  1336. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1337. expect(importNodes.length).toBe(3);
  1338. const names = importNodes.map((n) => n.name);
  1339. expect(names).toContain('react');
  1340. expect(names).toContain('./components');
  1341. expect(names).toContain('./styles.css');
  1342. });
  1343. it('should extract type imports', () => {
  1344. const code = `import type { FC, ReactNode } from 'react';`;
  1345. const result = extractFromSource('types.ts', code);
  1346. const importNode = result.nodes.find((n) => n.kind === 'import');
  1347. expect(importNode).toBeDefined();
  1348. expect(importNode?.name).toBe('react');
  1349. expect(importNode?.signature).toContain('type');
  1350. expect(importNode?.signature).toContain('FC');
  1351. });
  1352. it('should extract aliased named imports', () => {
  1353. const code = `import { useState as useStateAlias } from 'react';`;
  1354. const result = extractFromSource('hooks.ts', code);
  1355. const importNode = result.nodes.find((n) => n.kind === 'import');
  1356. expect(importNode).toBeDefined();
  1357. expect(importNode?.name).toBe('react');
  1358. expect(importNode?.signature).toContain('useState');
  1359. expect(importNode?.signature).toContain('useStateAlias');
  1360. });
  1361. it('should extract relative path imports', () => {
  1362. const code = `import { helper } from '../utils/helper';`;
  1363. const result = extractFromSource('components/Button.tsx', code);
  1364. const importNode = result.nodes.find((n) => n.kind === 'import');
  1365. expect(importNode).toBeDefined();
  1366. expect(importNode?.name).toBe('../utils/helper');
  1367. expect(importNode?.signature).toContain('helper');
  1368. });
  1369. });
  1370. describe('Python imports', () => {
  1371. it('should extract simple import statement', () => {
  1372. const code = `import json`;
  1373. const result = extractFromSource('utils.py', code);
  1374. const importNode = result.nodes.find((n) => n.kind === 'import');
  1375. expect(importNode).toBeDefined();
  1376. expect(importNode?.name).toBe('json');
  1377. });
  1378. it('should extract from import statement', () => {
  1379. const code = `from os import path`;
  1380. const result = extractFromSource('utils.py', code);
  1381. const importNode = result.nodes.find((n) => n.kind === 'import');
  1382. expect(importNode).toBeDefined();
  1383. expect(importNode?.name).toBe('os');
  1384. expect(importNode?.signature).toContain('path');
  1385. });
  1386. it('should extract multiple imports from same module', () => {
  1387. const code = `from typing import List, Dict, Optional`;
  1388. const result = extractFromSource('types.py', code);
  1389. const importNode = result.nodes.find((n) => n.kind === 'import');
  1390. expect(importNode).toBeDefined();
  1391. expect(importNode?.name).toBe('typing');
  1392. expect(importNode?.signature).toContain('List');
  1393. expect(importNode?.signature).toContain('Dict');
  1394. });
  1395. it('should extract multiple import statements', () => {
  1396. const code = `
  1397. import os
  1398. import sys
  1399. `;
  1400. const result = extractFromSource('main.py', code);
  1401. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1402. expect(importNodes.length).toBe(2);
  1403. const names = importNodes.map((n) => n.name);
  1404. expect(names).toContain('os');
  1405. expect(names).toContain('sys');
  1406. });
  1407. it('should extract aliased import', () => {
  1408. const code = `import numpy as np`;
  1409. const result = extractFromSource('data.py', code);
  1410. const importNode = result.nodes.find((n) => n.kind === 'import');
  1411. expect(importNode).toBeDefined();
  1412. expect(importNode?.name).toBe('numpy');
  1413. expect(importNode?.signature).toContain('as np');
  1414. });
  1415. it('should extract relative import', () => {
  1416. const code = `from .utils import helper`;
  1417. const result = extractFromSource('module.py', code);
  1418. const importNode = result.nodes.find((n) => n.kind === 'import');
  1419. expect(importNode).toBeDefined();
  1420. expect(importNode?.name).toBe('.utils');
  1421. expect(importNode?.signature).toContain('helper');
  1422. });
  1423. it('should extract wildcard import', () => {
  1424. const code = `from typing import *`;
  1425. const result = extractFromSource('types.py', code);
  1426. const importNode = result.nodes.find((n) => n.kind === 'import');
  1427. expect(importNode).toBeDefined();
  1428. expect(importNode?.name).toBe('typing');
  1429. expect(importNode?.signature).toContain('*');
  1430. });
  1431. });
  1432. describe('Rust imports', () => {
  1433. it('should extract simple use declaration', () => {
  1434. const code = `use std::io;`;
  1435. const result = extractFromSource('main.rs', code);
  1436. const importNode = result.nodes.find((n) => n.kind === 'import');
  1437. expect(importNode).toBeDefined();
  1438. expect(importNode?.name).toBe('std');
  1439. expect(importNode?.signature).toBe('use std::io;');
  1440. });
  1441. it('should extract scoped use list', () => {
  1442. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1443. const result = extractFromSource('main.rs', code);
  1444. const importNode = result.nodes.find((n) => n.kind === 'import');
  1445. expect(importNode).toBeDefined();
  1446. expect(importNode?.name).toBe('std');
  1447. expect(importNode?.signature).toContain('ffi::OsStr');
  1448. expect(importNode?.signature).toContain('path::Path');
  1449. });
  1450. it('should extract crate imports', () => {
  1451. const code = `use crate::error::Error;`;
  1452. const result = extractFromSource('lib.rs', code);
  1453. const importNode = result.nodes.find((n) => n.kind === 'import');
  1454. expect(importNode).toBeDefined();
  1455. expect(importNode?.name).toBe('crate');
  1456. });
  1457. it('should extract super imports', () => {
  1458. const code = `use super::utils;`;
  1459. const result = extractFromSource('submod.rs', code);
  1460. const importNode = result.nodes.find((n) => n.kind === 'import');
  1461. expect(importNode).toBeDefined();
  1462. expect(importNode?.name).toBe('super');
  1463. });
  1464. it('should extract external crate imports', () => {
  1465. const code = `use serde::{Serialize, Deserialize};`;
  1466. const result = extractFromSource('types.rs', code);
  1467. const importNode = result.nodes.find((n) => n.kind === 'import');
  1468. expect(importNode).toBeDefined();
  1469. expect(importNode?.name).toBe('serde');
  1470. expect(importNode?.signature).toContain('Serialize');
  1471. expect(importNode?.signature).toContain('Deserialize');
  1472. });
  1473. });
  1474. describe('Go imports', () => {
  1475. it('should extract single import', () => {
  1476. const code = `
  1477. package main
  1478. import "fmt"
  1479. `;
  1480. const result = extractFromSource('main.go', code);
  1481. const importNode = result.nodes.find((n) => n.kind === 'import');
  1482. expect(importNode).toBeDefined();
  1483. expect(importNode?.name).toBe('fmt');
  1484. });
  1485. it('should extract grouped imports', () => {
  1486. const code = `
  1487. package main
  1488. import (
  1489. "fmt"
  1490. "os"
  1491. "encoding/json"
  1492. )
  1493. `;
  1494. const result = extractFromSource('main.go', code);
  1495. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1496. expect(importNodes.length).toBe(3);
  1497. const names = importNodes.map((n) => n.name);
  1498. expect(names).toContain('fmt');
  1499. expect(names).toContain('os');
  1500. expect(names).toContain('encoding/json');
  1501. });
  1502. it('should extract aliased import', () => {
  1503. const code = `
  1504. package main
  1505. import f "fmt"
  1506. `;
  1507. const result = extractFromSource('main.go', code);
  1508. const importNode = result.nodes.find((n) => n.kind === 'import');
  1509. expect(importNode).toBeDefined();
  1510. expect(importNode?.name).toBe('fmt');
  1511. expect(importNode?.signature).toContain('f');
  1512. });
  1513. it('should extract dot import', () => {
  1514. const code = `
  1515. package main
  1516. import . "math"
  1517. `;
  1518. const result = extractFromSource('main.go', code);
  1519. const importNode = result.nodes.find((n) => n.kind === 'import');
  1520. expect(importNode).toBeDefined();
  1521. expect(importNode?.name).toBe('math');
  1522. expect(importNode?.signature).toContain('.');
  1523. });
  1524. it('should extract blank import', () => {
  1525. const code = `
  1526. package main
  1527. import _ "github.com/go-sql-driver/mysql"
  1528. `;
  1529. const result = extractFromSource('main.go', code);
  1530. const importNode = result.nodes.find((n) => n.kind === 'import');
  1531. expect(importNode).toBeDefined();
  1532. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1533. expect(importNode?.signature).toContain('_');
  1534. });
  1535. });
  1536. describe('Swift imports', () => {
  1537. it('should extract simple import', () => {
  1538. const code = `import Foundation`;
  1539. const result = extractFromSource('main.swift', code);
  1540. const importNode = result.nodes.find((n) => n.kind === 'import');
  1541. expect(importNode).toBeDefined();
  1542. expect(importNode?.name).toBe('Foundation');
  1543. expect(importNode?.signature).toBe('import Foundation');
  1544. });
  1545. it('should extract @testable import', () => {
  1546. const code = `@testable import Alamofire`;
  1547. const result = extractFromSource('Tests.swift', code);
  1548. const importNode = result.nodes.find((n) => n.kind === 'import');
  1549. expect(importNode).toBeDefined();
  1550. expect(importNode?.name).toBe('Alamofire');
  1551. expect(importNode?.signature).toContain('@testable');
  1552. });
  1553. it('should extract @preconcurrency import', () => {
  1554. const code = `@preconcurrency import Security`;
  1555. const result = extractFromSource('Auth.swift', code);
  1556. const importNode = result.nodes.find((n) => n.kind === 'import');
  1557. expect(importNode).toBeDefined();
  1558. expect(importNode?.name).toBe('Security');
  1559. });
  1560. it('should extract multiple imports', () => {
  1561. const code = `
  1562. import Foundation
  1563. import UIKit
  1564. import Alamofire
  1565. `;
  1566. const result = extractFromSource('App.swift', code);
  1567. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1568. expect(importNodes.length).toBe(3);
  1569. const names = importNodes.map((n) => n.name);
  1570. expect(names).toContain('Foundation');
  1571. expect(names).toContain('UIKit');
  1572. expect(names).toContain('Alamofire');
  1573. });
  1574. });
  1575. describe('Kotlin imports', () => {
  1576. it('should extract simple import', () => {
  1577. const code = `import java.io.IOException`;
  1578. const result = extractFromSource('Main.kt', code);
  1579. const importNode = result.nodes.find((n) => n.kind === 'import');
  1580. expect(importNode).toBeDefined();
  1581. expect(importNode?.name).toBe('java.io.IOException');
  1582. expect(importNode?.signature).toBe('import java.io.IOException');
  1583. });
  1584. it('should extract aliased import', () => {
  1585. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1586. const result = extractFromSource('Utils.kt', code);
  1587. const importNode = result.nodes.find((n) => n.kind === 'import');
  1588. expect(importNode).toBeDefined();
  1589. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1590. expect(importNode?.signature).toContain('as RequestBuilder');
  1591. });
  1592. it('should extract wildcard import', () => {
  1593. const code = `import java.util.concurrent.TimeUnit.*`;
  1594. const result = extractFromSource('Time.kt', code);
  1595. const importNode = result.nodes.find((n) => n.kind === 'import');
  1596. expect(importNode).toBeDefined();
  1597. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1598. expect(importNode?.signature).toContain('.*');
  1599. });
  1600. it('should extract multiple imports', () => {
  1601. const code = `
  1602. import java.io.IOException
  1603. import kotlin.test.assertFailsWith
  1604. import okhttp3.OkHttpClient
  1605. `;
  1606. const result = extractFromSource('Test.kt', code);
  1607. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1608. expect(importNodes.length).toBe(3);
  1609. const names = importNodes.map((n) => n.name);
  1610. expect(names).toContain('java.io.IOException');
  1611. expect(names).toContain('kotlin.test.assertFailsWith');
  1612. expect(names).toContain('okhttp3.OkHttpClient');
  1613. });
  1614. });
  1615. describe('Java imports', () => {
  1616. it('should extract simple import', () => {
  1617. const code = `import java.util.List;`;
  1618. const result = extractFromSource('Main.java', code);
  1619. const importNode = result.nodes.find((n) => n.kind === 'import');
  1620. expect(importNode).toBeDefined();
  1621. expect(importNode?.name).toBe('java.util.List');
  1622. expect(importNode?.signature).toBe('import java.util.List;');
  1623. });
  1624. it('should extract static import', () => {
  1625. const code = `import static java.util.Collections.emptyList;`;
  1626. const result = extractFromSource('Utils.java', code);
  1627. const importNode = result.nodes.find((n) => n.kind === 'import');
  1628. expect(importNode).toBeDefined();
  1629. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1630. expect(importNode?.signature).toContain('static');
  1631. });
  1632. it('should extract wildcard import', () => {
  1633. const code = `import java.util.*;`;
  1634. const result = extractFromSource('App.java', code);
  1635. const importNode = result.nodes.find((n) => n.kind === 'import');
  1636. expect(importNode).toBeDefined();
  1637. expect(importNode?.name).toBe('java.util');
  1638. expect(importNode?.signature).toContain('.*');
  1639. });
  1640. it('should extract nested class import', () => {
  1641. const code = `import java.util.Map.Entry;`;
  1642. const result = extractFromSource('MapUtil.java', code);
  1643. const importNode = result.nodes.find((n) => n.kind === 'import');
  1644. expect(importNode).toBeDefined();
  1645. expect(importNode?.name).toBe('java.util.Map.Entry');
  1646. });
  1647. it('should extract multiple imports', () => {
  1648. const code = `
  1649. import java.util.List;
  1650. import java.util.Map;
  1651. import java.io.IOException;
  1652. `;
  1653. const result = extractFromSource('Service.java', code);
  1654. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1655. expect(importNodes.length).toBe(3);
  1656. const names = importNodes.map((n) => n.name);
  1657. expect(names).toContain('java.util.List');
  1658. expect(names).toContain('java.util.Map');
  1659. expect(names).toContain('java.io.IOException');
  1660. });
  1661. });
  1662. describe('C# imports', () => {
  1663. it('should extract simple using', () => {
  1664. const code = `using System;`;
  1665. const result = extractFromSource('Program.cs', code);
  1666. const importNode = result.nodes.find((n) => n.kind === 'import');
  1667. expect(importNode).toBeDefined();
  1668. expect(importNode?.name).toBe('System');
  1669. expect(importNode?.signature).toBe('using System;');
  1670. });
  1671. it('should extract qualified using', () => {
  1672. const code = `using System.Collections.Generic;`;
  1673. const result = extractFromSource('Utils.cs', code);
  1674. const importNode = result.nodes.find((n) => n.kind === 'import');
  1675. expect(importNode).toBeDefined();
  1676. expect(importNode?.name).toBe('System.Collections.Generic');
  1677. });
  1678. it('should extract static using', () => {
  1679. const code = `using static System.Console;`;
  1680. const result = extractFromSource('App.cs', code);
  1681. const importNode = result.nodes.find((n) => n.kind === 'import');
  1682. expect(importNode).toBeDefined();
  1683. expect(importNode?.name).toBe('System.Console');
  1684. expect(importNode?.signature).toContain('static');
  1685. });
  1686. it('should extract alias using', () => {
  1687. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1688. const result = extractFromSource('Types.cs', code);
  1689. const importNode = result.nodes.find((n) => n.kind === 'import');
  1690. expect(importNode).toBeDefined();
  1691. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1692. expect(importNode?.signature).toContain('MyList =');
  1693. });
  1694. it('should extract multiple usings', () => {
  1695. const code = `
  1696. using System;
  1697. using System.Threading.Tasks;
  1698. using Microsoft.Extensions.DependencyInjection;
  1699. `;
  1700. const result = extractFromSource('Service.cs', code);
  1701. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1702. expect(importNodes.length).toBe(3);
  1703. const names = importNodes.map((n) => n.name);
  1704. expect(names).toContain('System');
  1705. expect(names).toContain('System.Threading.Tasks');
  1706. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1707. });
  1708. });
  1709. describe('PHP imports', () => {
  1710. it('should extract simple use', () => {
  1711. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1712. const result = extractFromSource('Test.php', code);
  1713. const importNode = result.nodes.find((n) => n.kind === 'import');
  1714. expect(importNode).toBeDefined();
  1715. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1716. });
  1717. it('should extract aliased use', () => {
  1718. const code = `<?php use Mockery as m;`;
  1719. const result = extractFromSource('Test.php', code);
  1720. const importNode = result.nodes.find((n) => n.kind === 'import');
  1721. expect(importNode).toBeDefined();
  1722. expect(importNode?.name).toBe('Mockery');
  1723. expect(importNode?.signature).toContain('as m');
  1724. });
  1725. it('should extract function use', () => {
  1726. const code = `<?php use function Illuminate\\Support\\env;`;
  1727. const result = extractFromSource('helpers.php', code);
  1728. const importNode = result.nodes.find((n) => n.kind === 'import');
  1729. expect(importNode).toBeDefined();
  1730. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1731. expect(importNode?.signature).toContain('function');
  1732. });
  1733. it('should extract grouped use', () => {
  1734. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1735. const result = extractFromSource('Models.php', code);
  1736. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1737. expect(importNodes.length).toBe(2);
  1738. const names = importNodes.map((n) => n.name);
  1739. expect(names).toContain('Illuminate\\Database\\Model');
  1740. expect(names).toContain('Illuminate\\Database\\Builder');
  1741. });
  1742. it('should extract multiple uses', () => {
  1743. const code = `<?php
  1744. use Illuminate\\Support\\Collection;
  1745. use Illuminate\\Support\\Str;
  1746. use Closure;
  1747. `;
  1748. const result = extractFromSource('Service.php', code);
  1749. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1750. expect(importNodes.length).toBe(3);
  1751. const names = importNodes.map((n) => n.name);
  1752. expect(names).toContain('Illuminate\\Support\\Collection');
  1753. expect(names).toContain('Illuminate\\Support\\Str');
  1754. expect(names).toContain('Closure');
  1755. });
  1756. });
  1757. describe('Ruby imports', () => {
  1758. it('should extract require', () => {
  1759. const code = `require 'json'`;
  1760. const result = extractFromSource('app.rb', code);
  1761. const importNode = result.nodes.find((n) => n.kind === 'import');
  1762. expect(importNode).toBeDefined();
  1763. expect(importNode?.name).toBe('json');
  1764. expect(importNode?.signature).toBe("require 'json'");
  1765. });
  1766. it('should extract require with path', () => {
  1767. const code = `require 'active_support/core_ext/string'`;
  1768. const result = extractFromSource('config.rb', code);
  1769. const importNode = result.nodes.find((n) => n.kind === 'import');
  1770. expect(importNode).toBeDefined();
  1771. expect(importNode?.name).toBe('active_support/core_ext/string');
  1772. });
  1773. it('should extract require_relative', () => {
  1774. const code = `require_relative '../test_helper'`;
  1775. const result = extractFromSource('test/my_test.rb', code);
  1776. const importNode = result.nodes.find((n) => n.kind === 'import');
  1777. expect(importNode).toBeDefined();
  1778. expect(importNode?.name).toBe('../test_helper');
  1779. expect(importNode?.signature).toContain('require_relative');
  1780. });
  1781. it('should not extract non-require calls', () => {
  1782. const code = `puts 'hello'`;
  1783. const result = extractFromSource('app.rb', code);
  1784. const importNode = result.nodes.find((n) => n.kind === 'import');
  1785. expect(importNode).toBeUndefined();
  1786. });
  1787. it('should extract multiple requires', () => {
  1788. const code = `
  1789. require 'json'
  1790. require 'yaml'
  1791. require_relative 'helper'
  1792. `;
  1793. const result = extractFromSource('lib.rb', code);
  1794. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1795. expect(importNodes.length).toBe(3);
  1796. const names = importNodes.map((n) => n.name);
  1797. expect(names).toContain('json');
  1798. expect(names).toContain('yaml');
  1799. expect(names).toContain('helper');
  1800. });
  1801. });
  1802. describe('Ruby modules', () => {
  1803. it('should extract module as module node with containment', () => {
  1804. const code = `
  1805. module CachedCounting
  1806. def self.disable
  1807. @enabled = false
  1808. end
  1809. def perform_increment!(key, count)
  1810. write_cache!(key, count)
  1811. end
  1812. end
  1813. `;
  1814. const result = extractFromSource('concerns/cached_counting.rb', code);
  1815. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1816. expect(moduleNode).toBeDefined();
  1817. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1818. // Methods inside module should have module-qualified names
  1819. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1820. expect(disableMethod).toBeDefined();
  1821. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1822. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1823. expect(incrementMethod).toBeDefined();
  1824. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1825. // Containment edge from module to methods
  1826. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1827. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1828. });
  1829. it('should handle nested modules with classes', () => {
  1830. const code = `
  1831. module Discourse
  1832. module Auth
  1833. class AuthProvider
  1834. def authenticate(params)
  1835. validate(params)
  1836. end
  1837. end
  1838. end
  1839. end
  1840. `;
  1841. const result = extractFromSource('lib/auth.rb', code);
  1842. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1843. expect(discourseModule).toBeDefined();
  1844. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1845. expect(authModule).toBeDefined();
  1846. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1847. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1848. expect(authProvider).toBeDefined();
  1849. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1850. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1851. expect(authMethod).toBeDefined();
  1852. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1853. });
  1854. });
  1855. describe('C/C++ imports', () => {
  1856. it('should extract system include', () => {
  1857. const code = `#include <iostream>`;
  1858. const result = extractFromSource('main.cpp', code);
  1859. const importNode = result.nodes.find((n) => n.kind === 'import');
  1860. expect(importNode).toBeDefined();
  1861. expect(importNode?.name).toBe('iostream');
  1862. expect(importNode?.signature).toBe('#include <iostream>');
  1863. });
  1864. it('should extract system include with path', () => {
  1865. const code = `#include <nlohmann/json.hpp>`;
  1866. const result = extractFromSource('app.cpp', code);
  1867. const importNode = result.nodes.find((n) => n.kind === 'import');
  1868. expect(importNode).toBeDefined();
  1869. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1870. });
  1871. it('should extract local include', () => {
  1872. const code = `#include "myheader.h"`;
  1873. const result = extractFromSource('main.cpp', code);
  1874. const importNode = result.nodes.find((n) => n.kind === 'import');
  1875. expect(importNode).toBeDefined();
  1876. expect(importNode?.name).toBe('myheader.h');
  1877. });
  1878. it('should extract C header', () => {
  1879. const code = `#include <stdio.h>`;
  1880. const result = extractFromSource('main.c', code);
  1881. const importNode = result.nodes.find((n) => n.kind === 'import');
  1882. expect(importNode).toBeDefined();
  1883. expect(importNode?.name).toBe('stdio.h');
  1884. });
  1885. it('should extract multiple includes', () => {
  1886. const code = `
  1887. #include <iostream>
  1888. #include <vector>
  1889. #include "config.h"
  1890. `;
  1891. const result = extractFromSource('app.cpp', code);
  1892. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1893. expect(importNodes.length).toBe(3);
  1894. const names = importNodes.map((n) => n.name);
  1895. expect(names).toContain('iostream');
  1896. expect(names).toContain('vector');
  1897. expect(names).toContain('config.h');
  1898. });
  1899. it('should create unresolved references for local includes', () => {
  1900. const code = `#include "myheader.h"`;
  1901. const result = extractFromSource('main.cpp', code);
  1902. const importRef = result.unresolvedReferences.find(
  1903. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  1904. );
  1905. expect(importRef).toBeDefined();
  1906. expect(importRef?.line).toBe(1);
  1907. });
  1908. it('should create unresolved references for system includes', () => {
  1909. const code = `#include <iostream>`;
  1910. const result = extractFromSource('main.cpp', code);
  1911. const importRef = result.unresolvedReferences.find(
  1912. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  1913. );
  1914. expect(importRef).toBeDefined();
  1915. });
  1916. });
  1917. describe('Dart imports', () => {
  1918. it('should extract dart: import', () => {
  1919. const code = `import 'dart:async';`;
  1920. const result = extractFromSource('main.dart', code);
  1921. const importNode = result.nodes.find((n) => n.kind === 'import');
  1922. expect(importNode).toBeDefined();
  1923. expect(importNode?.name).toBe('dart:async');
  1924. expect(importNode?.signature).toBe("import 'dart:async';");
  1925. });
  1926. it('should extract package import', () => {
  1927. const code = `import 'package:flutter/material.dart';`;
  1928. const result = extractFromSource('app.dart', code);
  1929. const importNode = result.nodes.find((n) => n.kind === 'import');
  1930. expect(importNode).toBeDefined();
  1931. expect(importNode?.name).toBe('package:flutter/material.dart');
  1932. });
  1933. it('should extract aliased import', () => {
  1934. const code = `import 'package:http/http.dart' as http;`;
  1935. const result = extractFromSource('api.dart', code);
  1936. const importNode = result.nodes.find((n) => n.kind === 'import');
  1937. expect(importNode).toBeDefined();
  1938. expect(importNode?.name).toBe('package:http/http.dart');
  1939. expect(importNode?.signature).toContain('as http');
  1940. });
  1941. it('should extract multiple imports', () => {
  1942. const code = `
  1943. import 'dart:async';
  1944. import 'dart:convert';
  1945. import 'package:flutter/material.dart';
  1946. `;
  1947. const result = extractFromSource('main.dart', code);
  1948. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1949. expect(importNodes.length).toBe(3);
  1950. const names = importNodes.map((n) => n.name);
  1951. expect(names).toContain('dart:async');
  1952. expect(names).toContain('dart:convert');
  1953. expect(names).toContain('package:flutter/material.dart');
  1954. });
  1955. it('should extract relative import', () => {
  1956. const code = `import '../utils/helpers.dart';`;
  1957. const result = extractFromSource('lib/main.dart', code);
  1958. const importNode = result.nodes.find((n) => n.kind === 'import');
  1959. expect(importNode).toBeDefined();
  1960. expect(importNode?.name).toBe('../utils/helpers.dart');
  1961. });
  1962. });
  1963. describe('Liquid imports', () => {
  1964. it('should extract render tag', () => {
  1965. const code = `{% render 'loading-spinner' %}`;
  1966. const result = extractFromSource('template.liquid', code);
  1967. const importNode = result.nodes.find((n) => n.kind === 'import');
  1968. expect(importNode).toBeDefined();
  1969. expect(importNode?.name).toBe('loading-spinner');
  1970. expect(importNode?.signature).toContain('render');
  1971. });
  1972. it('should extract section tag', () => {
  1973. const code = `{% section 'header' %}`;
  1974. const result = extractFromSource('layout/theme.liquid', code);
  1975. const importNode = result.nodes.find((n) => n.kind === 'import');
  1976. expect(importNode).toBeDefined();
  1977. expect(importNode?.name).toBe('header');
  1978. expect(importNode?.signature).toContain('section');
  1979. });
  1980. it('should extract include tag', () => {
  1981. const code = `{% include 'icon-cart' %}`;
  1982. const result = extractFromSource('snippets/header.liquid', code);
  1983. const importNode = result.nodes.find((n) => n.kind === 'import');
  1984. expect(importNode).toBeDefined();
  1985. expect(importNode?.name).toBe('icon-cart');
  1986. expect(importNode?.signature).toContain('include');
  1987. });
  1988. it('should extract render with whitespace control', () => {
  1989. const code = `{%- render 'price' -%}`;
  1990. const result = extractFromSource('snippets/product.liquid', code);
  1991. const importNode = result.nodes.find((n) => n.kind === 'import');
  1992. expect(importNode).toBeDefined();
  1993. expect(importNode?.name).toBe('price');
  1994. });
  1995. it('should extract multiple imports', () => {
  1996. const code = `
  1997. {% section 'header' %}
  1998. {% render 'loading-spinner' %}
  1999. {% render 'cart-drawer' %}
  2000. `;
  2001. const result = extractFromSource('layout/theme.liquid', code);
  2002. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2003. expect(importNodes.length).toBe(3);
  2004. const names = importNodes.map((n) => n.name);
  2005. expect(names).toContain('header');
  2006. expect(names).toContain('loading-spinner');
  2007. expect(names).toContain('cart-drawer');
  2008. });
  2009. });
  2010. });
  2011. // =============================================================================
  2012. // Pascal / Delphi Extraction
  2013. // =============================================================================
  2014. describe('Pascal / Delphi Extraction', () => {
  2015. describe('Language detection', () => {
  2016. it('should detect Pascal files', () => {
  2017. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2018. expect(detectLanguage('App.dpr')).toBe('pascal');
  2019. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2020. expect(detectLanguage('App.lpr')).toBe('pascal');
  2021. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2022. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2023. });
  2024. it('should report Pascal as supported', () => {
  2025. expect(isLanguageSupported('pascal')).toBe(true);
  2026. expect(getSupportedLanguages()).toContain('pascal');
  2027. });
  2028. });
  2029. describe('Unit extraction', () => {
  2030. it('should extract unit as module', () => {
  2031. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2032. const result = extractFromSource('MyUnit.pas', code);
  2033. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2034. expect(moduleNode).toBeDefined();
  2035. expect(moduleNode?.name).toBe('MyUnit');
  2036. expect(moduleNode?.language).toBe('pascal');
  2037. });
  2038. it('should extract program as module', () => {
  2039. const code = `program MyApp;\nbegin\nend.`;
  2040. const result = extractFromSource('MyApp.dpr', code);
  2041. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2042. expect(moduleNode).toBeDefined();
  2043. expect(moduleNode?.name).toBe('MyApp');
  2044. });
  2045. it('should fallback to filename when module name is empty', () => {
  2046. // Some .dpr templates use "program;" without a name
  2047. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2048. const result = extractFromSource('Console.dpr', code);
  2049. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2050. expect(moduleNode).toBeDefined();
  2051. expect(moduleNode?.name).toBe('Console');
  2052. });
  2053. });
  2054. describe('Uses clause (imports)', () => {
  2055. it('should extract uses as individual imports', () => {
  2056. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2057. const result = extractFromSource('Test.pas', code);
  2058. const imports = result.nodes.filter((n) => n.kind === 'import');
  2059. expect(imports.length).toBe(2);
  2060. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2061. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2062. });
  2063. it('should create unresolved references for imports', () => {
  2064. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2065. const result = extractFromSource('Test.pas', code);
  2066. const importRef = result.unresolvedReferences.find(
  2067. (r) => r.referenceKind === 'imports'
  2068. );
  2069. expect(importRef).toBeDefined();
  2070. expect(importRef?.referenceName).toBe('UAuth');
  2071. });
  2072. });
  2073. describe('Class extraction', () => {
  2074. it('should extract class declarations', () => {
  2075. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2076. const result = extractFromSource('Test.pas', code);
  2077. const classNode = result.nodes.find((n) => n.kind === 'class');
  2078. expect(classNode).toBeDefined();
  2079. expect(classNode?.name).toBe('TMyClass');
  2080. });
  2081. it('should extract class with inheritance', () => {
  2082. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2083. const result = extractFromSource('Test.pas', code);
  2084. const extendsRef = result.unresolvedReferences.find(
  2085. (r) => r.referenceKind === 'extends'
  2086. );
  2087. expect(extendsRef).toBeDefined();
  2088. expect(extendsRef?.referenceName).toBe('TParent');
  2089. });
  2090. it('should extract class with interface implementation', () => {
  2091. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2092. const result = extractFromSource('Test.pas', code);
  2093. const extendsRef = result.unresolvedReferences.find(
  2094. (r) => r.referenceKind === 'extends'
  2095. );
  2096. const implementsRef = result.unresolvedReferences.find(
  2097. (r) => r.referenceKind === 'implements'
  2098. );
  2099. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2100. expect(implementsRef?.referenceName).toBe('ILogger');
  2101. });
  2102. });
  2103. describe('Record extraction', () => {
  2104. it('should extract records as class nodes', () => {
  2105. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2106. const result = extractFromSource('Test.pas', code);
  2107. const classNode = result.nodes.find((n) => n.kind === 'class');
  2108. expect(classNode).toBeDefined();
  2109. expect(classNode?.name).toBe('TPoint');
  2110. const fields = result.nodes.filter((n) => n.kind === 'field');
  2111. expect(fields.length).toBe(2);
  2112. expect(fields.map((f) => f.name)).toContain('X');
  2113. expect(fields.map((f) => f.name)).toContain('Y');
  2114. });
  2115. });
  2116. describe('Interface extraction', () => {
  2117. it('should extract interface declarations', () => {
  2118. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2119. const result = extractFromSource('Test.pas', code);
  2120. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2121. expect(ifaceNode).toBeDefined();
  2122. expect(ifaceNode?.name).toBe('ILogger');
  2123. });
  2124. });
  2125. describe('Method extraction', () => {
  2126. it('should extract methods with visibility', () => {
  2127. 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.`;
  2128. const result = extractFromSource('Test.pas', code);
  2129. const methods = result.nodes.filter((n) => n.kind === 'method');
  2130. expect(methods.length).toBe(2);
  2131. const createMethod = methods.find((m) => m.name === 'Create');
  2132. expect(createMethod?.visibility).toBe('public');
  2133. const getValue = methods.find((m) => m.name === 'GetValue');
  2134. expect(getValue?.visibility).toBe('public');
  2135. const fields = result.nodes.filter((n) => n.kind === 'field');
  2136. const fValue = fields.find((f) => f.name === 'FValue');
  2137. expect(fValue?.visibility).toBe('private');
  2138. });
  2139. it('should detect static methods (class methods)', () => {
  2140. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2141. const result = extractFromSource('Test.pas', code);
  2142. const methods = result.nodes.filter((n) => n.kind === 'method');
  2143. const staticMethod = methods.find((m) => m.name === 'Create');
  2144. expect(staticMethod?.isStatic).toBe(true);
  2145. });
  2146. });
  2147. describe('Enum extraction', () => {
  2148. it('should extract enums with members', () => {
  2149. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2150. const result = extractFromSource('Test.pas', code);
  2151. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2152. expect(enumNode).toBeDefined();
  2153. expect(enumNode?.name).toBe('TColor');
  2154. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2155. expect(members.length).toBe(3);
  2156. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2157. });
  2158. });
  2159. describe('Property extraction', () => {
  2160. it('should extract properties', () => {
  2161. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2162. const result = extractFromSource('Test.pas', code);
  2163. const propNode = result.nodes.find((n) => n.kind === 'property');
  2164. expect(propNode).toBeDefined();
  2165. expect(propNode?.name).toBe('Name');
  2166. expect(propNode?.visibility).toBe('public');
  2167. });
  2168. });
  2169. describe('Constant extraction', () => {
  2170. it('should extract constants', () => {
  2171. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2172. const result = extractFromSource('Test.pas', code);
  2173. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2174. expect(constants.length).toBe(2);
  2175. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2176. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2177. });
  2178. });
  2179. describe('Type alias extraction', () => {
  2180. it('should extract type aliases', () => {
  2181. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2182. const result = extractFromSource('Test.pas', code);
  2183. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2184. expect(aliasNode).toBeDefined();
  2185. expect(aliasNode?.name).toBe('TUserName');
  2186. });
  2187. });
  2188. describe('Call extraction', () => {
  2189. it('should extract calls from implementation bodies', () => {
  2190. 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.`;
  2191. const result = extractFromSource('Test.pas', code);
  2192. const callRef = result.unresolvedReferences.find(
  2193. (r) => r.referenceKind === 'calls'
  2194. );
  2195. expect(callRef).toBeDefined();
  2196. expect(callRef?.referenceName).toBe('WriteLn');
  2197. });
  2198. });
  2199. describe('Containment edges', () => {
  2200. it('should create contains edges for class members', () => {
  2201. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2202. const result = extractFromSource('Test.pas', code);
  2203. const classNode = result.nodes.find((n) => n.kind === 'class');
  2204. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2205. expect(classNode).toBeDefined();
  2206. expect(methodNode).toBeDefined();
  2207. const containsEdge = result.edges.find(
  2208. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2209. );
  2210. expect(containsEdge).toBeDefined();
  2211. });
  2212. });
  2213. describe('Full fixture: UAuth.pas', () => {
  2214. const code = `unit UAuth;
  2215. interface
  2216. uses
  2217. System.SysUtils,
  2218. System.Classes;
  2219. type
  2220. ITokenValidator = interface
  2221. ['{11111111-1111-1111-1111-111111111111}']
  2222. function Validate(const AToken: string): Boolean;
  2223. end;
  2224. TAuthService = class(TInterfacedObject, ITokenValidator)
  2225. private
  2226. FToken: string;
  2227. FLoginCount: Integer;
  2228. procedure IncLoginCount;
  2229. protected
  2230. function GetToken: string;
  2231. public
  2232. constructor Create;
  2233. destructor Destroy; override;
  2234. function Validate(const AToken: string): Boolean;
  2235. function Login(const AUser, APass: string): string;
  2236. property Token: string read GetToken;
  2237. property LoginCount: Integer read FLoginCount;
  2238. end;
  2239. implementation
  2240. constructor TAuthService.Create;
  2241. begin
  2242. inherited Create;
  2243. FToken := '';
  2244. FLoginCount := 0;
  2245. end;
  2246. destructor TAuthService.Destroy;
  2247. begin
  2248. FToken := '';
  2249. inherited Destroy;
  2250. end;
  2251. procedure TAuthService.IncLoginCount;
  2252. begin
  2253. Inc(FLoginCount);
  2254. end;
  2255. function TAuthService.GetToken: string;
  2256. begin
  2257. Result := FToken;
  2258. end;
  2259. function TAuthService.Validate(const AToken: string): Boolean;
  2260. begin
  2261. Result := AToken <> '';
  2262. end;
  2263. function TAuthService.Login(const AUser, APass: string): string;
  2264. begin
  2265. IncLoginCount;
  2266. if Validate(AUser + ':' + APass) then
  2267. begin
  2268. FToken := AUser;
  2269. Result := 'ok';
  2270. end
  2271. else
  2272. Result := '';
  2273. end;
  2274. end.`;
  2275. it('should extract all expected nodes', () => {
  2276. const result = extractFromSource('UAuth.pas', code);
  2277. expect(result.errors).toHaveLength(0);
  2278. // Module
  2279. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2280. expect(moduleNode?.name).toBe('UAuth');
  2281. // Imports
  2282. const imports = result.nodes.filter((n) => n.kind === 'import');
  2283. expect(imports.length).toBe(2);
  2284. // Interface
  2285. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2286. expect(ifaceNode?.name).toBe('ITokenValidator');
  2287. // Class
  2288. const classNode = result.nodes.find((n) => n.kind === 'class');
  2289. expect(classNode?.name).toBe('TAuthService');
  2290. // Methods
  2291. const methods = result.nodes.filter((n) => n.kind === 'method');
  2292. expect(methods.length).toBeGreaterThanOrEqual(6);
  2293. expect(methods.map((m) => m.name)).toContain('Create');
  2294. expect(methods.map((m) => m.name)).toContain('Destroy');
  2295. expect(methods.map((m) => m.name)).toContain('Login');
  2296. // Fields
  2297. const fields = result.nodes.filter((n) => n.kind === 'field');
  2298. expect(fields.length).toBe(2);
  2299. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2300. // Properties
  2301. const props = result.nodes.filter((n) => n.kind === 'property');
  2302. expect(props.length).toBe(2);
  2303. expect(props.map((p) => p.name)).toContain('Token');
  2304. expect(props.map((p) => p.name)).toContain('LoginCount');
  2305. });
  2306. it('should extract inheritance and interface implementation', () => {
  2307. const result = extractFromSource('UAuth.pas', code);
  2308. const extendsRef = result.unresolvedReferences.find(
  2309. (r) => r.referenceKind === 'extends'
  2310. );
  2311. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2312. const implementsRef = result.unresolvedReferences.find(
  2313. (r) => r.referenceKind === 'implements'
  2314. );
  2315. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2316. });
  2317. it('should extract calls from implementation', () => {
  2318. const result = extractFromSource('UAuth.pas', code);
  2319. const callRefs = result.unresolvedReferences.filter(
  2320. (r) => r.referenceKind === 'calls'
  2321. );
  2322. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2323. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2324. });
  2325. });
  2326. describe('Full fixture: UTypes.pas', () => {
  2327. const code = `unit UTypes;
  2328. interface
  2329. uses
  2330. System.SysUtils;
  2331. const
  2332. C_MAX_RETRIES = 3;
  2333. C_DEFAULT_NAME = 'Guest';
  2334. type
  2335. TUserRole = (urAdmin, urEditor, urViewer);
  2336. TPoint2D = record
  2337. X: Double;
  2338. Y: Double;
  2339. end;
  2340. TUserName = string;
  2341. TUserInfo = class
  2342. public
  2343. type
  2344. TAddress = record
  2345. Street: string;
  2346. City: string;
  2347. Zip: string;
  2348. end;
  2349. private
  2350. FName: TUserName;
  2351. FRole: TUserRole;
  2352. FAddress: TAddress;
  2353. public
  2354. constructor Create(const AName: TUserName; ARole: TUserRole);
  2355. function GetDisplayName: string;
  2356. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2357. property Name: TUserName read FName write FName;
  2358. property Role: TUserRole read FRole;
  2359. property Address: TAddress read FAddress write FAddress;
  2360. end;
  2361. implementation
  2362. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2363. begin
  2364. FName := AName;
  2365. FRole := ARole;
  2366. end;
  2367. function TUserInfo.GetDisplayName: string;
  2368. begin
  2369. if FRole = urAdmin then
  2370. Result := '[Admin] ' + FName
  2371. else
  2372. Result := FName;
  2373. end;
  2374. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2375. begin
  2376. Result := TUserInfo.Create(AName, urAdmin);
  2377. end;
  2378. end.`;
  2379. it('should extract enums with members', () => {
  2380. const result = extractFromSource('UTypes.pas', code);
  2381. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2382. expect(enumNode?.name).toBe('TUserRole');
  2383. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2384. expect(members.length).toBe(3);
  2385. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2386. });
  2387. it('should extract constants', () => {
  2388. const result = extractFromSource('UTypes.pas', code);
  2389. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2390. expect(constants.length).toBe(2);
  2391. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2392. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2393. });
  2394. it('should extract type aliases', () => {
  2395. const result = extractFromSource('UTypes.pas', code);
  2396. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2397. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2398. });
  2399. it('should extract records as classes with fields', () => {
  2400. const result = extractFromSource('UTypes.pas', code);
  2401. const classes = result.nodes.filter((n) => n.kind === 'class');
  2402. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2403. // TPoint2D fields
  2404. const fields = result.nodes.filter((n) => n.kind === 'field');
  2405. expect(fields.map((f) => f.name)).toContain('X');
  2406. expect(fields.map((f) => f.name)).toContain('Y');
  2407. });
  2408. it('should extract static class methods', () => {
  2409. const result = extractFromSource('UTypes.pas', code);
  2410. const methods = result.nodes.filter((n) => n.kind === 'method');
  2411. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2412. expect(staticMethod).toBeDefined();
  2413. expect(staticMethod?.isStatic).toBe(true);
  2414. });
  2415. it('should extract nested types', () => {
  2416. const result = extractFromSource('UTypes.pas', code);
  2417. const classes = result.nodes.filter((n) => n.kind === 'class');
  2418. expect(classes.map((c) => c.name)).toContain('TAddress');
  2419. });
  2420. });
  2421. });
  2422. // =============================================================================
  2423. // DFM/FMX Extraction
  2424. // =============================================================================
  2425. describe('DFM/FMX Extraction', () => {
  2426. it('should extract components from DFM', () => {
  2427. const code = `object Form1: TForm1
  2428. Left = 0
  2429. Top = 0
  2430. Caption = 'My Form'
  2431. object Button1: TButton
  2432. Left = 10
  2433. Top = 10
  2434. Caption = 'Click Me'
  2435. end
  2436. end`;
  2437. const result = extractFromSource('Form1.dfm', code);
  2438. const components = result.nodes.filter((n) => n.kind === 'component');
  2439. expect(components.length).toBe(2);
  2440. expect(components.map((c) => c.name)).toContain('Form1');
  2441. expect(components.map((c) => c.name)).toContain('Button1');
  2442. const button = components.find((c) => c.name === 'Button1');
  2443. expect(button?.signature).toBe('TButton');
  2444. });
  2445. it('should extract nested component hierarchy', () => {
  2446. const code = `object Form1: TForm1
  2447. object Panel1: TPanel
  2448. object Label1: TLabel
  2449. Caption = 'Hello'
  2450. end
  2451. end
  2452. end`;
  2453. const result = extractFromSource('Form1.dfm', code);
  2454. const components = result.nodes.filter((n) => n.kind === 'component');
  2455. expect(components.length).toBe(3);
  2456. // Check nesting: Panel1 contains Label1
  2457. const panel = components.find((c) => c.name === 'Panel1');
  2458. const label = components.find((c) => c.name === 'Label1');
  2459. const containsEdge = result.edges.find(
  2460. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2461. );
  2462. expect(containsEdge).toBeDefined();
  2463. });
  2464. it('should extract event handler references', () => {
  2465. const code = `object Form1: TForm1
  2466. OnCreate = FormCreate
  2467. OnDestroy = FormDestroy
  2468. object Button1: TButton
  2469. OnClick = Button1Click
  2470. end
  2471. end`;
  2472. const result = extractFromSource('Form1.dfm', code);
  2473. const refs = result.unresolvedReferences;
  2474. expect(refs.length).toBe(3);
  2475. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2476. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2477. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2478. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2479. });
  2480. it('should handle multi-line properties', () => {
  2481. const code = `object Form1: TForm1
  2482. SQL.Strings = (
  2483. 'SELECT * FROM users'
  2484. 'WHERE active = 1')
  2485. object Button1: TButton
  2486. OnClick = Button1Click
  2487. end
  2488. end`;
  2489. const result = extractFromSource('Form1.dfm', code);
  2490. const components = result.nodes.filter((n) => n.kind === 'component');
  2491. expect(components.length).toBe(2);
  2492. const refs = result.unresolvedReferences;
  2493. expect(refs.length).toBe(1);
  2494. expect(refs[0]?.referenceName).toBe('Button1Click');
  2495. });
  2496. it('should handle inherited keyword', () => {
  2497. const code = `inherited Form1: TForm1
  2498. Caption = 'Inherited Form'
  2499. object Button1: TButton
  2500. OnClick = Button1Click
  2501. end
  2502. end`;
  2503. const result = extractFromSource('Form1.dfm', code);
  2504. const components = result.nodes.filter((n) => n.kind === 'component');
  2505. expect(components.length).toBe(2);
  2506. expect(components.map((c) => c.name)).toContain('Form1');
  2507. });
  2508. it('should handle item collection properties', () => {
  2509. const code = `object Form1: TForm1
  2510. object StatusBar1: TStatusBar
  2511. Panels = <
  2512. item
  2513. Width = 200
  2514. end
  2515. item
  2516. Width = 200
  2517. end>
  2518. end
  2519. end`;
  2520. const result = extractFromSource('Form1.dfm', code);
  2521. const components = result.nodes.filter((n) => n.kind === 'component');
  2522. expect(components.length).toBe(2);
  2523. });
  2524. describe('Full fixture: MainForm.dfm', () => {
  2525. const code = `object frmMain: TfrmMain
  2526. Left = 0
  2527. Top = 0
  2528. Caption = 'CodeGraph DFM Fixture'
  2529. ClientHeight = 480
  2530. ClientWidth = 640
  2531. OnCreate = FormCreate
  2532. OnDestroy = FormDestroy
  2533. object pnlTop: TPanel
  2534. Left = 0
  2535. Top = 0
  2536. Width = 640
  2537. Height = 50
  2538. object lblTitle: TLabel
  2539. Left = 16
  2540. Top = 16
  2541. Caption = 'Authentication Service'
  2542. end
  2543. object btnLogin: TButton
  2544. Left = 540
  2545. Top = 12
  2546. OnClick = btnLoginClick
  2547. end
  2548. end
  2549. object pnlContent: TPanel
  2550. Left = 0
  2551. Top = 50
  2552. object edtUsername: TEdit
  2553. Left = 16
  2554. Top = 16
  2555. OnChange = edtUsernameChange
  2556. end
  2557. object edtPassword: TEdit
  2558. Left = 16
  2559. Top = 48
  2560. OnKeyPress = edtPasswordKeyPress
  2561. end
  2562. object mmoLog: TMemo
  2563. Left = 16
  2564. Top = 88
  2565. end
  2566. end
  2567. object pnlStatus: TStatusBar
  2568. Left = 0
  2569. Top = 440
  2570. Panels = <
  2571. item
  2572. Width = 200
  2573. end
  2574. item
  2575. Width = 200
  2576. end>
  2577. end
  2578. end`;
  2579. it('should extract all components', () => {
  2580. const result = extractFromSource('MainForm.dfm', code);
  2581. const components = result.nodes.filter((n) => n.kind === 'component');
  2582. expect(components.length).toBe(9);
  2583. expect(components.map((c) => c.name)).toEqual(
  2584. expect.arrayContaining([
  2585. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2586. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2587. ])
  2588. );
  2589. });
  2590. it('should extract all event handlers', () => {
  2591. const result = extractFromSource('MainForm.dfm', code);
  2592. const refs = result.unresolvedReferences;
  2593. expect(refs.length).toBe(5);
  2594. expect(refs.map((r) => r.referenceName)).toEqual(
  2595. expect.arrayContaining([
  2596. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2597. 'edtUsernameChange', 'edtPasswordKeyPress',
  2598. ])
  2599. );
  2600. });
  2601. });
  2602. });
  2603. describe('Kotlin Multiplatform expect/actual', () => {
  2604. let tempDir: string;
  2605. let cg: CodeGraph;
  2606. beforeEach(() => {
  2607. tempDir = createTempDir();
  2608. });
  2609. afterEach(() => {
  2610. if (cg) cg.close();
  2611. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2612. });
  2613. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  2614. const common = path.join(tempDir, 'src', 'commonMain');
  2615. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2616. fs.mkdirSync(common, { recursive: true });
  2617. fs.mkdirSync(jvm, { recursive: true });
  2618. // common source set: expect declarations + a caller that uses them
  2619. fs.writeFileSync(
  2620. path.join(common, 'SystemProps.kt'),
  2621. `package demo.internal
  2622. expect fun systemProp(name: String): String?
  2623. expect class Platform {
  2624. fun describe(): String
  2625. }
  2626. `
  2627. );
  2628. fs.writeFileSync(
  2629. path.join(common, 'Caller.kt'),
  2630. `package demo
  2631. import demo.internal.systemProp
  2632. import demo.internal.Platform
  2633. fun useIt(): String {
  2634. val v = systemProp("os.name")
  2635. return Platform().describe() + v
  2636. }
  2637. `
  2638. );
  2639. // jvm source set: actual implementations
  2640. fs.writeFileSync(
  2641. path.join(jvm, 'SystemProps.kt'),
  2642. `package demo.internal
  2643. actual fun systemProp(name: String): String? = System.getProperty(name)
  2644. actual class Platform {
  2645. actual fun describe(): String = "JVM"
  2646. }
  2647. `
  2648. );
  2649. cg = CodeGraph.initSync(tempDir);
  2650. await cg.indexAll();
  2651. cg.resolveReferences();
  2652. // The expect/actual markers are captured onto the node's decorators.
  2653. const fns = cg.getNodesByKind('function');
  2654. const actualFn = fns.find(
  2655. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  2656. );
  2657. const expectFn = fns.find(
  2658. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  2659. );
  2660. expect(actualFn).toBeDefined();
  2661. expect(expectFn).toBeDefined();
  2662. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  2663. // Editing the JVM actual must surface the common expect AND its caller —
  2664. // before the expect/actual bridge the actual had zero dependents.
  2665. const impact = cg.getImpactRadius(actualFn!.id, 3);
  2666. const impacted = [...impact.nodes.values()].map((n) => n.name);
  2667. expect(impacted).toContain('systemProp'); // the common expect
  2668. expect(impacted).toContain('useIt'); // the caller, reached transitively
  2669. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  2670. const bridge = impact.edges.find(
  2671. (e) =>
  2672. e.target === actualFn!.id &&
  2673. e.provenance === 'heuristic' &&
  2674. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2675. 'kotlin-expect-actual'
  2676. );
  2677. expect(bridge).toBeDefined();
  2678. expect(bridge!.source).toBe(expectFn!.id);
  2679. });
  2680. it('links an expect class to an actual typealias (different node kinds)', async () => {
  2681. const common = path.join(tempDir, 'src', 'commonMain');
  2682. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2683. fs.mkdirSync(common, { recursive: true });
  2684. fs.mkdirSync(jvm, { recursive: true });
  2685. fs.writeFileSync(
  2686. path.join(common, 'Lock.kt'),
  2687. `package demo
  2688. expect class Lock {
  2689. fun acquire()
  2690. }
  2691. `
  2692. );
  2693. fs.writeFileSync(
  2694. path.join(jvm, 'Lock.kt'),
  2695. `package demo
  2696. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  2697. `
  2698. );
  2699. cg = CodeGraph.initSync(tempDir);
  2700. await cg.indexAll();
  2701. cg.resolveReferences();
  2702. const aliasNode = cg
  2703. .getNodesByKind('type_alias')
  2704. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  2705. expect(aliasNode).toBeDefined();
  2706. // The actual typealias is now a cross-file dependency target (linked from
  2707. // the expect class), so it participates in impact rather than being orphaned.
  2708. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  2709. const bridge = impact.edges.find(
  2710. (e) =>
  2711. e.target === aliasNode!.id &&
  2712. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2713. 'kotlin-expect-actual'
  2714. );
  2715. expect(bridge).toBeDefined();
  2716. });
  2717. });
  2718. describe('Scala cross-file dependencies', () => {
  2719. let tempDir: string;
  2720. let cg: CodeGraph;
  2721. beforeEach(() => {
  2722. tempDir = createTempDir();
  2723. });
  2724. afterEach(() => {
  2725. if (cg) cg.close();
  2726. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2727. });
  2728. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  2729. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  2730. fs.mkdirSync(src, { recursive: true });
  2731. fs.writeFileSync(
  2732. path.join(src, 'Semigroup.scala'),
  2733. `package demo
  2734. trait Semigroup[A] {
  2735. def combine(x: A, y: A): A
  2736. }
  2737. `
  2738. );
  2739. fs.writeFileSync(
  2740. path.join(src, 'Monoid.scala'),
  2741. `package demo
  2742. trait Monoid[A] extends Semigroup[A] {
  2743. def empty: A
  2744. }
  2745. `
  2746. );
  2747. fs.writeFileSync(
  2748. path.join(src, 'Instances.scala'),
  2749. `package demo
  2750. object Instances {
  2751. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  2752. def empty: Int = 0
  2753. def combine(x: Int, y: Int): Int = x + y
  2754. }
  2755. }
  2756. `
  2757. );
  2758. fs.writeFileSync(
  2759. path.join(src, 'Folding.scala'),
  2760. `package demo
  2761. object Folding {
  2762. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  2763. xs.foldLeft(M.empty)(M.combine)
  2764. }
  2765. `
  2766. );
  2767. cg = CodeGraph.initSync(tempDir);
  2768. await cg.indexAll();
  2769. cg.resolveReferences();
  2770. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  2771. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  2772. expect(monoid).toBeDefined();
  2773. expect(semigroup).toBeDefined();
  2774. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  2775. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  2776. // the whole point of the fix (the `[A]` used to defeat name matching).
  2777. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  2778. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  2779. // Editing Monoid surfaces the cross-file users: the instance val typed
  2780. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  2781. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  2782. expect(impacted).toContain('intMonoid'); // field type annotation
  2783. expect(impacted).toContain('fold'); // trailing implicit parameter list
  2784. });
  2785. });
  2786. describe('PHP namespace + import resolution', () => {
  2787. let tempDir: string;
  2788. let cg: CodeGraph;
  2789. beforeEach(() => {
  2790. tempDir = createTempDir();
  2791. });
  2792. afterEach(() => {
  2793. if (cg) cg.close();
  2794. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2795. });
  2796. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  2797. const src = path.join(tempDir, 'src');
  2798. // Two interfaces with the SAME simple name in different namespaces — the
  2799. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  2800. // resolve. The namespace qualifies them; the `use` import disambiguates.
  2801. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  2802. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  2803. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  2804. fs.writeFileSync(
  2805. path.join(src, 'Cache', 'Factory.php'),
  2806. `<?php
  2807. namespace Contracts\\Cache;
  2808. interface Factory {
  2809. public function store(): object;
  2810. }
  2811. `
  2812. );
  2813. fs.writeFileSync(
  2814. path.join(src, 'Mail', 'Factory.php'),
  2815. `<?php
  2816. namespace Contracts\\Mail;
  2817. interface Factory {
  2818. public function mailer(): object;
  2819. }
  2820. `
  2821. );
  2822. fs.writeFileSync(
  2823. path.join(src, 'App', 'Service.php'),
  2824. `<?php
  2825. namespace App;
  2826. use Contracts\\Cache\\Factory;
  2827. class Service {
  2828. public function make(): Factory {
  2829. return resolve(Factory::class);
  2830. }
  2831. }
  2832. `
  2833. );
  2834. cg = CodeGraph.initSync(tempDir);
  2835. await cg.indexAll();
  2836. cg.resolveReferences();
  2837. // The PHP namespace is captured into the qualified name, so the two
  2838. // same-named interfaces are distinguishable.
  2839. const cacheFactory = cg
  2840. .getNodesByKind('interface')
  2841. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  2842. const mailFactory = cg
  2843. .getNodesByKind('interface')
  2844. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  2845. expect(cacheFactory).toBeDefined();
  2846. expect(mailFactory).toBeDefined();
  2847. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  2848. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  2849. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  2850. const serviceFile = 'src/App/Service.php';
  2851. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  2852. (n) => (n.filePath ?? '').endsWith(serviceFile)
  2853. );
  2854. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  2855. (n) => (n.filePath ?? '').endsWith(serviceFile)
  2856. );
  2857. expect(cacheReaches).toBe(true);
  2858. expect(mailReaches).toBe(false);
  2859. });
  2860. });
  2861. describe('Full Indexing', () => {
  2862. let tempDir: string;
  2863. beforeEach(() => {
  2864. tempDir = createTempDir();
  2865. });
  2866. afterEach(() => {
  2867. cleanupTempDir(tempDir);
  2868. });
  2869. it('should index a TypeScript file', async () => {
  2870. // Create test file
  2871. const srcDir = path.join(tempDir, 'src');
  2872. fs.mkdirSync(srcDir);
  2873. fs.writeFileSync(
  2874. path.join(srcDir, 'utils.ts'),
  2875. `
  2876. export function add(a: number, b: number): number {
  2877. return a + b;
  2878. }
  2879. export function multiply(a: number, b: number): number {
  2880. return a * b;
  2881. }
  2882. `
  2883. );
  2884. // Initialize and index
  2885. const cg = CodeGraph.initSync(tempDir);
  2886. const result = await cg.indexAll();
  2887. expect(result.success).toBe(true);
  2888. expect(result.filesIndexed).toBe(1);
  2889. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2890. // Check nodes were stored
  2891. const nodes = cg.getNodesInFile('src/utils.ts');
  2892. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2893. const addFunc = nodes.find((n) => n.name === 'add');
  2894. expect(addFunc).toBeDefined();
  2895. expect(addFunc?.kind).toBe('function');
  2896. cg.close();
  2897. });
  2898. it('should index multiple files', async () => {
  2899. // Create test files
  2900. const srcDir = path.join(tempDir, 'src');
  2901. fs.mkdirSync(srcDir);
  2902. fs.writeFileSync(
  2903. path.join(srcDir, 'math.ts'),
  2904. `export function add(a: number, b: number) { return a + b; }`
  2905. );
  2906. fs.writeFileSync(
  2907. path.join(srcDir, 'string.ts'),
  2908. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2909. );
  2910. // Initialize and index
  2911. const cg = CodeGraph.initSync(tempDir);
  2912. const result = await cg.indexAll();
  2913. expect(result.success).toBe(true);
  2914. expect(result.filesIndexed).toBe(2);
  2915. const files = cg.getFiles();
  2916. expect(files.length).toBe(2);
  2917. cg.close();
  2918. });
  2919. it('should track file hashes for incremental updates', async () => {
  2920. // Create initial file
  2921. const srcDir = path.join(tempDir, 'src');
  2922. fs.mkdirSync(srcDir);
  2923. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2924. // Initialize and index
  2925. const cg = CodeGraph.initSync(tempDir);
  2926. await cg.indexAll();
  2927. // Check file is tracked
  2928. const file = cg.getFile('src/main.ts');
  2929. expect(file).toBeDefined();
  2930. expect(file?.contentHash).toBeDefined();
  2931. // Modify file
  2932. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2933. // Check for changes
  2934. const changes = cg.getChangedFiles();
  2935. expect(changes.modified).toContain('src/main.ts');
  2936. cg.close();
  2937. });
  2938. it('should sync and detect changes', async () => {
  2939. // Create initial file
  2940. const srcDir = path.join(tempDir, 'src');
  2941. fs.mkdirSync(srcDir);
  2942. fs.writeFileSync(
  2943. path.join(srcDir, 'main.ts'),
  2944. `export function original() { return 1; }`
  2945. );
  2946. // Initialize and index
  2947. const cg = CodeGraph.initSync(tempDir);
  2948. await cg.indexAll();
  2949. const initialNodes = cg.getNodesInFile('src/main.ts');
  2950. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2951. // Modify file
  2952. fs.writeFileSync(
  2953. path.join(srcDir, 'main.ts'),
  2954. `export function updated() { return 2; }`
  2955. );
  2956. // Sync
  2957. const syncResult = await cg.sync();
  2958. expect(syncResult.filesModified).toBe(1);
  2959. // Check nodes were updated
  2960. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2961. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2962. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2963. cg.close();
  2964. });
  2965. it('should count file-level tracked YAML files as indexed', async () => {
  2966. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  2967. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  2968. const cg = CodeGraph.initSync(tempDir);
  2969. const result = await cg.indexAll();
  2970. expect(result.success).toBe(true);
  2971. expect(result.filesIndexed).toBe(2);
  2972. expect(result.filesSkipped).toBe(0);
  2973. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  2974. cg.close();
  2975. });
  2976. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  2977. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  2978. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  2979. const cg = CodeGraph.initSync(tempDir);
  2980. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  2981. expect(result.success).toBe(true);
  2982. expect(result.filesIndexed).toBe(2);
  2983. expect(result.filesSkipped).toBe(0);
  2984. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  2985. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  2986. cg.close();
  2987. });
  2988. it('should count file-level tracked .properties files as indexed', async () => {
  2989. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  2990. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  2991. const cg = CodeGraph.initSync(tempDir);
  2992. const result = await cg.indexAll();
  2993. expect(result.success).toBe(true);
  2994. expect(result.filesIndexed).toBe(2);
  2995. expect(result.filesSkipped).toBe(0);
  2996. cg.close();
  2997. });
  2998. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  2999. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3000. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  3001. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  3002. const cg = CodeGraph.initSync(tempDir);
  3003. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  3004. expect(result.success).toBe(true);
  3005. expect(result.filesIndexed).toBe(3);
  3006. expect(result.filesSkipped).toBe(0);
  3007. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  3008. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  3009. cg.close();
  3010. });
  3011. });
  3012. describe('Path Normalization', () => {
  3013. it('should convert backslashes to forward slashes', () => {
  3014. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  3015. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  3016. });
  3017. it('should leave forward-slash paths unchanged', () => {
  3018. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  3019. });
  3020. it('should handle empty string', () => {
  3021. expect(normalizePath('')).toBe('');
  3022. });
  3023. });
  3024. describe('Directory Exclusion', () => {
  3025. let tempDir: string;
  3026. beforeEach(() => {
  3027. tempDir = createTempDir();
  3028. });
  3029. afterEach(() => {
  3030. cleanupTempDir(tempDir);
  3031. });
  3032. it('should exclude directories listed in .gitignore', () => {
  3033. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  3034. const srcDir = path.join(tempDir, 'src');
  3035. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  3036. fs.mkdirSync(srcDir, { recursive: true });
  3037. fs.mkdirSync(nmDir, { recursive: true });
  3038. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3039. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  3040. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  3041. const files = scanDirectory(tempDir);
  3042. expect(files).toContain('src/index.ts');
  3043. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  3044. });
  3045. it('should exclude nested node_modules via a root .gitignore', () => {
  3046. // A trailing-slash pattern with no leading slash matches at any depth.
  3047. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  3048. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  3049. fs.mkdirSync(srcDir, { recursive: true });
  3050. fs.mkdirSync(nmDir, { recursive: true });
  3051. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3052. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  3053. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  3054. const files = scanDirectory(tempDir);
  3055. expect(files).toContain('packages/app/src/index.ts');
  3056. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  3057. });
  3058. it('should apply a nested .gitignore only to its own subtree', () => {
  3059. const appSrc = path.join(tempDir, 'app', 'src');
  3060. fs.mkdirSync(appSrc, { recursive: true });
  3061. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  3062. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  3063. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  3064. // A sibling with the same name outside app/ must NOT be ignored.
  3065. const otherDir = path.join(tempDir, 'other', 'src');
  3066. fs.mkdirSync(otherDir, { recursive: true });
  3067. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  3068. const files = scanDirectory(tempDir);
  3069. expect(files).toContain('app/src/keep.ts');
  3070. expect(files).not.toContain('app/src/skip.ts');
  3071. expect(files).toContain('other/src/skip.ts');
  3072. });
  3073. it('should always skip .git directories', () => {
  3074. const srcDir = path.join(tempDir, 'src');
  3075. const gitDir = path.join(tempDir, '.git', 'objects');
  3076. fs.mkdirSync(srcDir, { recursive: true });
  3077. fs.mkdirSync(gitDir, { recursive: true });
  3078. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3079. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  3080. const files = scanDirectory(tempDir);
  3081. expect(files).toContain('src/index.ts');
  3082. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  3083. });
  3084. it('should return forward-slash paths on all platforms', () => {
  3085. const srcDir = path.join(tempDir, 'src', 'components');
  3086. fs.mkdirSync(srcDir, { recursive: true });
  3087. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  3088. const files = scanDirectory(tempDir);
  3089. expect(files.length).toBe(1);
  3090. expect(files[0]).toBe('src/components/Button.tsx');
  3091. expect(files[0]).not.toContain('\\');
  3092. });
  3093. });
  3094. describe('Git Submodules', () => {
  3095. let tempDir: string;
  3096. beforeEach(() => {
  3097. tempDir = createTempDir();
  3098. });
  3099. afterEach(() => {
  3100. cleanupTempDir(tempDir);
  3101. });
  3102. it('should index files inside git submodules (issue #147)', async () => {
  3103. const { execFileSync } = await import('child_process');
  3104. const git = (cwd: string, ...args: string[]) =>
  3105. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3106. // Build a separate "library" repo to use as a submodule source.
  3107. const libDir = path.join(tempDir, '_lib');
  3108. fs.mkdirSync(libDir, { recursive: true });
  3109. git(libDir, 'init', '-q');
  3110. git(libDir, 'config', 'user.email', 'test@test.com');
  3111. git(libDir, 'config', 'user.name', 'Test');
  3112. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  3113. git(libDir, 'add', '-A');
  3114. git(libDir, 'commit', '-q', '-m', 'lib init');
  3115. // Build the main repo and add the lib repo as a submodule.
  3116. const mainDir = path.join(tempDir, 'main');
  3117. fs.mkdirSync(mainDir, { recursive: true });
  3118. git(mainDir, 'init', '-q');
  3119. git(mainDir, 'config', 'user.email', 'test@test.com');
  3120. git(mainDir, 'config', 'user.name', 'Test');
  3121. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  3122. git(mainDir, 'add', '-A');
  3123. git(mainDir, 'commit', '-q', '-m', 'app init');
  3124. // protocol.file.allow=always is required to add a local-path submodule on
  3125. // recent git versions (CVE-2022-39253 mitigation).
  3126. execFileSync(
  3127. 'git',
  3128. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  3129. { cwd: mainDir, stdio: 'pipe' }
  3130. );
  3131. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  3132. const files = scanDirectory(mainDir);
  3133. expect(files).toContain('app.ts');
  3134. expect(files).toContain('libs/lib/lib.ts');
  3135. });
  3136. });
  3137. describe('Nested non-submodule git repos', () => {
  3138. let tempDir: string;
  3139. beforeEach(() => {
  3140. tempDir = createTempDir();
  3141. });
  3142. afterEach(() => {
  3143. cleanupTempDir(tempDir);
  3144. });
  3145. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  3146. const { execFileSync } = await import('child_process');
  3147. const git = (cwd: string, ...args: string[]) =>
  3148. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3149. // Top-level workspace is itself a git repo, holding no source directly —
  3150. // the CMake "super-repo" layout from the issue.
  3151. const root = path.join(tempDir, 'root');
  3152. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  3153. git(root, 'init', '-q');
  3154. git(root, 'config', 'user.email', 'test@test.com');
  3155. git(root, 'config', 'user.name', 'Test');
  3156. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  3157. // Two independent clones living inside the workspace (NOT submodules):
  3158. // one with committed source, one with only untracked source.
  3159. const sub1 = path.join(root, 'sub_repo1', 'src');
  3160. fs.mkdirSync(sub1, { recursive: true });
  3161. git(path.join(root, 'sub_repo1'), 'init', '-q');
  3162. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  3163. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  3164. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  3165. git(path.join(root, 'sub_repo1'), 'add', '-A');
  3166. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  3167. const sub2 = path.join(root, 'sub_repo2', 'src');
  3168. fs.mkdirSync(sub2, { recursive: true });
  3169. git(path.join(root, 'sub_repo2'), 'init', '-q');
  3170. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  3171. const files = scanDirectory(root);
  3172. // Both committed and untracked source from the nested repos must be found.
  3173. expect(files).toContain('sub_repo1/src/one.ts');
  3174. expect(files).toContain('sub_repo2/src/two.ts');
  3175. });
  3176. it('should respect each embedded repo\'s own .gitignore', async () => {
  3177. const { execFileSync } = await import('child_process');
  3178. const git = (cwd: string, ...args: string[]) =>
  3179. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3180. const root = path.join(tempDir, 'root');
  3181. fs.mkdirSync(root, { recursive: true });
  3182. git(root, 'init', '-q');
  3183. const sub = path.join(root, 'sub_repo', 'src');
  3184. fs.mkdirSync(sub, { recursive: true });
  3185. git(path.join(root, 'sub_repo'), 'init', '-q');
  3186. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  3187. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  3188. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  3189. const files = scanDirectory(root);
  3190. expect(files).toContain('sub_repo/src/real.ts');
  3191. expect(files).not.toContain('sub_repo/src/generated.ts');
  3192. });
  3193. });
  3194. // =============================================================================
  3195. // Scala
  3196. // =============================================================================
  3197. describe('Scala Extraction', () => {
  3198. describe('Language detection', () => {
  3199. it('should detect Scala files', () => {
  3200. expect(detectLanguage('Main.scala')).toBe('scala');
  3201. expect(detectLanguage('script.sc')).toBe('scala');
  3202. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  3203. });
  3204. it('should report Scala as supported', () => {
  3205. expect(isLanguageSupported('scala')).toBe(true);
  3206. expect(getSupportedLanguages()).toContain('scala');
  3207. });
  3208. });
  3209. describe('Class extraction', () => {
  3210. it('should extract class definitions', () => {
  3211. const code = `
  3212. class UserService(private val repo: UserRepository) {
  3213. def findUser(id: String): Option[String] = Some(id)
  3214. }
  3215. `;
  3216. const result = extractFromSource('UserService.scala', code);
  3217. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  3218. expect(cls).toBeDefined();
  3219. expect(cls?.language).toBe('scala');
  3220. });
  3221. it('should extract object definitions as class kind', () => {
  3222. const code = `
  3223. object DatabaseConfig {
  3224. val url = "jdbc:postgresql://localhost/mydb"
  3225. }
  3226. `;
  3227. const result = extractFromSource('Config.scala', code);
  3228. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  3229. expect(obj).toBeDefined();
  3230. });
  3231. it('should extract trait definitions as trait kind', () => {
  3232. const code = `
  3233. trait Repository[A] {
  3234. def findById(id: String): Option[A]
  3235. def save(entity: A): Unit
  3236. }
  3237. `;
  3238. const result = extractFromSource('Repository.scala', code);
  3239. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  3240. expect(trait_).toBeDefined();
  3241. });
  3242. });
  3243. describe('Method and function extraction', () => {
  3244. it('should extract method definitions inside a class', () => {
  3245. const code = `
  3246. class Calculator {
  3247. def add(a: Int, b: Int): Int = a + b
  3248. def divide(a: Double, b: Double): Double = a / b
  3249. }
  3250. `;
  3251. const result = extractFromSource('Calculator.scala', code);
  3252. const methods = result.nodes.filter((n) => n.kind === 'method');
  3253. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  3254. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  3255. });
  3256. it('should extract method signatures', () => {
  3257. const code = `
  3258. class Greeter {
  3259. def greet(name: String): String = s"Hello, \${name}!"
  3260. }
  3261. `;
  3262. const result = extractFromSource('Greeter.scala', code);
  3263. const method = result.nodes.find((n) => n.name === 'greet');
  3264. expect(method?.signature).toContain('name: String');
  3265. expect(method?.signature).toContain('String');
  3266. });
  3267. it('should extract top-level function definitions as functions', () => {
  3268. const code = `
  3269. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  3270. def greet(name: String): String = s"Hello, \${name}!"
  3271. `;
  3272. const result = extractFromSource('utils.scala', code);
  3273. const fns = result.nodes.filter((n) => n.kind === 'function');
  3274. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  3275. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  3276. });
  3277. });
  3278. describe('Val and var extraction', () => {
  3279. it('should extract val inside a class as field', () => {
  3280. const code = `
  3281. class Config {
  3282. val timeout: Int = 30
  3283. val host: String = "localhost"
  3284. }
  3285. `;
  3286. const result = extractFromSource('Config.scala', code);
  3287. const fields = result.nodes.filter((n) => n.kind === 'field');
  3288. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  3289. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  3290. });
  3291. it('should extract var inside a class as field', () => {
  3292. const code = `
  3293. class Counter {
  3294. var count: Int = 0
  3295. }
  3296. `;
  3297. const result = extractFromSource('Counter.scala', code);
  3298. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  3299. expect(field).toBeDefined();
  3300. });
  3301. it('should extract top-level val as constant', () => {
  3302. const code = `
  3303. val MaxConnections: Int = 100
  3304. val DefaultTimeout = 30
  3305. `;
  3306. const result = extractFromSource('constants.scala', code);
  3307. const consts = result.nodes.filter((n) => n.kind === 'constant');
  3308. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  3309. });
  3310. it('should extract top-level var as variable', () => {
  3311. const code = `
  3312. var retries: Int = 3
  3313. `;
  3314. const result = extractFromSource('state.scala', code);
  3315. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  3316. expect(v).toBeDefined();
  3317. });
  3318. it('should include type in val/var signature', () => {
  3319. const code = `
  3320. class Service {
  3321. val timeout: Int = 30
  3322. }
  3323. `;
  3324. const result = extractFromSource('Service.scala', code);
  3325. const field = result.nodes.find((n) => n.name === 'timeout');
  3326. expect(field?.signature).toContain('timeout');
  3327. expect(field?.signature).toContain('Int');
  3328. });
  3329. });
  3330. describe('Enum extraction', () => {
  3331. it('should extract enum definitions', () => {
  3332. const code = `
  3333. enum Color:
  3334. case Red
  3335. case Green
  3336. case Blue
  3337. `;
  3338. const result = extractFromSource('Color.scala', code);
  3339. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  3340. expect(enumNode).toBeDefined();
  3341. });
  3342. it('should extract enum cases as enum_member', () => {
  3343. const code = `
  3344. enum Direction:
  3345. case North
  3346. case South
  3347. case East
  3348. case West
  3349. `;
  3350. const result = extractFromSource('Direction.scala', code);
  3351. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  3352. expect(members.find((m) => m.name === 'North')).toBeDefined();
  3353. expect(members.find((m) => m.name === 'South')).toBeDefined();
  3354. expect(members.length).toBeGreaterThanOrEqual(4);
  3355. });
  3356. });
  3357. describe('Type alias extraction', () => {
  3358. it('should extract type aliases', () => {
  3359. const code = `
  3360. type UserId = String
  3361. type UserMap = Map[String, String]
  3362. `;
  3363. const result = extractFromSource('types.scala', code);
  3364. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3365. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  3366. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  3367. });
  3368. });
  3369. describe('Import extraction', () => {
  3370. it('should extract import declarations', () => {
  3371. const code = `
  3372. import scala.collection.mutable.ListBuffer
  3373. import scala.concurrent.Future
  3374. `;
  3375. const result = extractFromSource('imports.scala', code);
  3376. const imports = result.nodes.filter((n) => n.kind === 'import');
  3377. expect(imports.length).toBeGreaterThanOrEqual(2);
  3378. });
  3379. });
  3380. describe('Visibility modifiers', () => {
  3381. it('should extract private visibility', () => {
  3382. const code = `
  3383. class Service {
  3384. private val secret: String = "abc"
  3385. private def helper(): Unit = {}
  3386. }
  3387. `;
  3388. const result = extractFromSource('Service.scala', code);
  3389. const secretField = result.nodes.find((n) => n.name === 'secret');
  3390. expect(secretField?.visibility).toBe('private');
  3391. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  3392. expect(helperMethod?.visibility).toBe('private');
  3393. });
  3394. it('should extract protected visibility', () => {
  3395. const code = `
  3396. class Base {
  3397. protected def helperMethod(): Unit = {}
  3398. }
  3399. `;
  3400. const result = extractFromSource('Base.scala', code);
  3401. const method = result.nodes.find((n) => n.name === 'helperMethod');
  3402. expect(method?.visibility).toBe('protected');
  3403. });
  3404. it('should default to public visibility', () => {
  3405. const code = `
  3406. class Greeter {
  3407. def hello(): Unit = {}
  3408. }
  3409. `;
  3410. const result = extractFromSource('Greeter.scala', code);
  3411. const method = result.nodes.find((n) => n.name === 'hello');
  3412. expect(method?.visibility).toBe('public');
  3413. });
  3414. });
  3415. describe('Inheritance', () => {
  3416. it('should extract extends relationships', () => {
  3417. const code = `
  3418. class AdminUser extends User {
  3419. def adminAction(): Unit = {}
  3420. }
  3421. `;
  3422. const result = extractFromSource('AdminUser.scala', code);
  3423. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  3424. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  3425. });
  3426. });
  3427. describe('Call extraction', () => {
  3428. it('should extract function call expressions', () => {
  3429. const code = `
  3430. def processData(): Unit = {
  3431. val result = computeResult()
  3432. println(result)
  3433. }
  3434. `;
  3435. const result = extractFromSource('processor.scala', code);
  3436. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  3437. expect(calls.length).toBeGreaterThan(0);
  3438. });
  3439. });
  3440. });
  3441. describe('Vue Extraction', () => {
  3442. it('should detect Vue files', () => {
  3443. expect(detectLanguage('App.vue')).toBe('vue');
  3444. expect(detectLanguage('components/Button.vue')).toBe('vue');
  3445. expect(isLanguageSupported('vue')).toBe(true);
  3446. });
  3447. it('should extract component node from a Vue SFC', () => {
  3448. const code = `<template>
  3449. <div>{{ message }}</div>
  3450. </template>
  3451. <script>
  3452. export default {
  3453. data() {
  3454. return { message: 'Hello' };
  3455. }
  3456. }
  3457. </script>
  3458. `;
  3459. const result = extractFromSource('HelloWorld.vue', code);
  3460. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3461. expect(componentNode).toBeDefined();
  3462. expect(componentNode?.name).toBe('HelloWorld');
  3463. expect(componentNode?.language).toBe('vue');
  3464. expect(componentNode?.isExported).toBe(true);
  3465. });
  3466. it('should extract functions from <script> block', () => {
  3467. const code = `<template>
  3468. <button @click="handleClick">Click</button>
  3469. </template>
  3470. <script>
  3471. function handleClick() {
  3472. console.log('clicked');
  3473. }
  3474. const count = 0;
  3475. </script>
  3476. `;
  3477. const result = extractFromSource('Button.vue', code);
  3478. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3479. expect(componentNode).toBeDefined();
  3480. expect(componentNode?.name).toBe('Button');
  3481. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  3482. expect(funcNode).toBeDefined();
  3483. expect(funcNode?.language).toBe('vue');
  3484. });
  3485. it('should extract from <script setup lang="ts"> block', () => {
  3486. const code = `<template>
  3487. <div>{{ count }}</div>
  3488. </template>
  3489. <script setup lang="ts">
  3490. import { ref } from 'vue';
  3491. const count = ref(0);
  3492. function increment(): void {
  3493. count.value++;
  3494. }
  3495. </script>
  3496. `;
  3497. const result = extractFromSource('Counter.vue', code);
  3498. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3499. expect(componentNode).toBeDefined();
  3500. expect(componentNode?.name).toBe('Counter');
  3501. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  3502. expect(funcNode).toBeDefined();
  3503. expect(funcNode?.language).toBe('vue');
  3504. // All nodes should be marked as vue language
  3505. for (const node of result.nodes) {
  3506. expect(node.language).toBe('vue');
  3507. }
  3508. });
  3509. it('should extract calls from top-level <script setup> initializers', () => {
  3510. const code = `<template>
  3511. <div>{{ token }}</div>
  3512. </template>
  3513. <script setup lang="ts">
  3514. import { getTokenMp } from './api/upload';
  3515. const token = getTokenMp();
  3516. </script>
  3517. `;
  3518. const result = extractFromSource('Issue425Setup.vue', code);
  3519. const call = result.unresolvedReferences.find(
  3520. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3521. );
  3522. expect(call).toBeDefined();
  3523. });
  3524. it('should extract calls from Vue Options API object methods', () => {
  3525. const code = `<template>
  3526. <button @click="save">Save</button>
  3527. </template>
  3528. <script>
  3529. import { getTokenMp } from './api/upload';
  3530. export default {
  3531. methods: {
  3532. save() {
  3533. return getTokenMp();
  3534. }
  3535. },
  3536. setup() {
  3537. return getTokenMp();
  3538. }
  3539. }
  3540. </script>
  3541. `;
  3542. const result = extractFromSource('Issue425Options.vue', code);
  3543. const calls = result.unresolvedReferences.filter(
  3544. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3545. );
  3546. expect(calls).toHaveLength(2);
  3547. });
  3548. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  3549. const code = `<template>
  3550. <div class="wrap">
  3551. <UserCard :user="u" />
  3552. <my-button>Click</my-button>
  3553. <Transition><span>x</span></Transition>
  3554. </div>
  3555. </template>
  3556. <script setup lang="ts">
  3557. import UserCard from './UserCard.vue';
  3558. import MyButton from './MyButton.vue';
  3559. </script>
  3560. `;
  3561. const result = extractFromSource('Host.vue', code);
  3562. const refs = result.unresolvedReferences
  3563. .filter((r) => r.referenceKind === 'references')
  3564. .map((r) => r.referenceName);
  3565. expect(refs).toContain('UserCard'); // PascalCase tag
  3566. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  3567. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  3568. expect(refs).not.toContain('Div'); // native HTML element skipped
  3569. expect(refs).not.toContain('Span');
  3570. });
  3571. it('should extract from both <script> and <script setup> blocks', () => {
  3572. const code = `<template>
  3573. <div>{{ msg }}</div>
  3574. </template>
  3575. <script>
  3576. export default {
  3577. name: 'DualScript'
  3578. }
  3579. </script>
  3580. <script setup>
  3581. const msg = 'hello';
  3582. function greet() {
  3583. return msg;
  3584. }
  3585. </script>
  3586. `;
  3587. const result = extractFromSource('DualScript.vue', code);
  3588. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3589. expect(componentNode).toBeDefined();
  3590. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  3591. expect(greetFunc).toBeDefined();
  3592. });
  3593. it('should create component node for template-only Vue file', () => {
  3594. const code = `<template>
  3595. <div>Static content</div>
  3596. </template>
  3597. `;
  3598. const result = extractFromSource('Static.vue', code);
  3599. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3600. expect(componentNode).toBeDefined();
  3601. expect(componentNode?.name).toBe('Static');
  3602. expect(componentNode?.language).toBe('vue');
  3603. // Only the component node should exist (no script nodes)
  3604. expect(result.nodes.length).toBe(1);
  3605. });
  3606. it('should create containment edges from component to script nodes', () => {
  3607. const code = `<template>
  3608. <div>{{ value }}</div>
  3609. </template>
  3610. <script setup lang="ts">
  3611. const value = 42;
  3612. </script>
  3613. `;
  3614. const result = extractFromSource('Contained.vue', code);
  3615. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3616. expect(componentNode).toBeDefined();
  3617. // Should have containment edges from component to child nodes
  3618. const containEdges = result.edges.filter(
  3619. (e) => e.source === componentNode!.id && e.kind === 'contains'
  3620. );
  3621. expect(containEdges.length).toBeGreaterThan(0);
  3622. });
  3623. });
  3624. describe('Instantiates + Decorates edge extraction', () => {
  3625. it('emits an instantiates ref for `new Foo()`', () => {
  3626. const code = `
  3627. class Foo {}
  3628. function bootstrap() { return new Foo(); }
  3629. `;
  3630. const result = extractFromSource('app.ts', code);
  3631. const ref = result.unresolvedReferences.find(
  3632. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  3633. );
  3634. expect(ref).toBeDefined();
  3635. });
  3636. it('strips type-argument suffix from generic constructors', () => {
  3637. const code = `
  3638. class Container<T> { constructor(_: T) {} }
  3639. function go() { return new Container<string>('x'); }
  3640. `;
  3641. const result = extractFromSource('app.ts', code);
  3642. const ref = result.unresolvedReferences.find(
  3643. (r) => r.referenceKind === 'instantiates'
  3644. );
  3645. expect(ref).toBeDefined();
  3646. // Container<string> must be normalised to "Container" — otherwise
  3647. // resolution can never match the class node.
  3648. expect(ref!.referenceName).toBe('Container');
  3649. });
  3650. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  3651. const code = `
  3652. const ns = { Foo: class {} };
  3653. function go() { return new ns.Foo(); }
  3654. `;
  3655. const result = extractFromSource('app.ts', code);
  3656. const ref = result.unresolvedReferences.find(
  3657. (r) => r.referenceKind === 'instantiates'
  3658. );
  3659. // We can't always resolve which Foo, but the name should be the
  3660. // simple identifier so name-matching has a chance.
  3661. expect(ref?.referenceName).toBe('Foo');
  3662. });
  3663. it('emits a decorates ref for `@Foo class X {}`', () => {
  3664. const code = `
  3665. function Foo(_arg: string) { return (cls: any) => cls; }
  3666. @Foo('x')
  3667. class X {}
  3668. `;
  3669. const result = extractFromSource('app.ts', code);
  3670. const decorClass = result.unresolvedReferences.find(
  3671. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  3672. );
  3673. expect(decorClass).toBeDefined();
  3674. });
  3675. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  3676. // Regression: the sibling-walk must stop at the first non-
  3677. // decorator separator. `@A class Foo {} @B class Bar {}` must
  3678. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  3679. // `decorates(Bar, A)`.
  3680. const code = `
  3681. function A(cls: any) { return cls; }
  3682. function B(cls: any) { return cls; }
  3683. @A
  3684. class Foo {}
  3685. @B
  3686. class Bar {}
  3687. `;
  3688. const result = extractFromSource('app.ts', code);
  3689. const decoratesEdges = result.unresolvedReferences.filter(
  3690. (r) => r.referenceKind === 'decorates'
  3691. );
  3692. // Exactly one decorates ref per decorated class, no cross-attribution.
  3693. const fromBar = decoratesEdges.filter((r) =>
  3694. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  3695. );
  3696. expect(fromBar.length).toBe(1);
  3697. expect(fromBar[0]!.referenceName).toBe('B');
  3698. });
  3699. it('emits a decorates ref for `@Foo method() {}`', () => {
  3700. const code = `
  3701. function Get(p: string) { return (t: any, k: string) => t; }
  3702. class Svc {
  3703. @Get('/x') method() { return 1; }
  3704. }
  3705. `;
  3706. const result = extractFromSource('app.ts', code);
  3707. const decorMethod = result.unresolvedReferences.find(
  3708. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  3709. );
  3710. expect(decorMethod).toBeDefined();
  3711. // The decorated symbol must be `method`, not the constructor or class.
  3712. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  3713. expect(decoratedNode?.name).toBe('method');
  3714. });
  3715. });
  3716. // =============================================================================
  3717. // Lua
  3718. // =============================================================================
  3719. describe('Lua Extraction', () => {
  3720. describe('Language detection', () => {
  3721. it('should detect Lua files', () => {
  3722. expect(detectLanguage('init.lua')).toBe('lua');
  3723. expect(detectLanguage('src/util.lua')).toBe('lua');
  3724. });
  3725. it('should report Lua as supported', () => {
  3726. expect(isLanguageSupported('lua')).toBe(true);
  3727. expect(getSupportedLanguages()).toContain('lua');
  3728. });
  3729. });
  3730. describe('Function extraction', () => {
  3731. it('should extract global and local functions', () => {
  3732. const code = `
  3733. function configure(opts) return opts end
  3734. local function helper(x) return x * 2 end
  3735. `;
  3736. const result = extractFromSource('init.lua', code);
  3737. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  3738. expect(funcs).toContain('configure');
  3739. expect(funcs).toContain('helper');
  3740. const configure = result.nodes.find((n) => n.name === 'configure');
  3741. expect(configure?.language).toBe('lua');
  3742. expect(configure?.signature).toBe('(opts)');
  3743. });
  3744. it('should split table/method functions into a receiver and method name', () => {
  3745. const code = `
  3746. function M.connect(host, port) return host end
  3747. function M:send(data) return self end
  3748. `;
  3749. const result = extractFromSource('init.lua', code);
  3750. const methods = result.nodes.filter((n) => n.kind === 'method');
  3751. const connect = methods.find((m) => m.name === 'connect');
  3752. expect(connect?.qualifiedName).toBe('M::connect');
  3753. const send = methods.find((m) => m.name === 'send');
  3754. expect(send?.qualifiedName).toBe('M::send');
  3755. });
  3756. });
  3757. describe('Variable extraction', () => {
  3758. it('should extract local variable declarations', () => {
  3759. const code = `
  3760. local M = {}
  3761. local count = 0
  3762. `;
  3763. const result = extractFromSource('mod.lua', code);
  3764. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3765. expect(vars).toContain('M');
  3766. expect(vars).toContain('count');
  3767. });
  3768. });
  3769. describe('Import extraction (require)', () => {
  3770. it('should extract require() in local declarations and bare calls', () => {
  3771. const code = `
  3772. local socket = require("socket")
  3773. local http = require "resty.http"
  3774. require("side.effect")
  3775. `;
  3776. const result = extractFromSource('net.lua', code);
  3777. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3778. expect(imports).toContain('socket');
  3779. expect(imports).toContain('resty.http');
  3780. expect(imports).toContain('side.effect');
  3781. const ref = result.unresolvedReferences.find(
  3782. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  3783. );
  3784. expect(ref).toBeDefined();
  3785. });
  3786. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  3787. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  3788. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  3789. // by extracting several sources in sequence and asserting the LAST still works.
  3790. it('should keep extracting require across many sequential parses', () => {
  3791. let last;
  3792. for (let i = 0; i < 8; i++) {
  3793. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  3794. }
  3795. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3796. expect(imports).toContain('module.7');
  3797. });
  3798. });
  3799. describe('Call extraction', () => {
  3800. it('should record intra-file calls as resolvable references', () => {
  3801. const code = `
  3802. local function helper(x) return x end
  3803. local function run(y) return helper(y) end
  3804. `;
  3805. const result = extractFromSource('calls.lua', code);
  3806. const call = result.unresolvedReferences.find(
  3807. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  3808. );
  3809. expect(call).toBeDefined();
  3810. });
  3811. });
  3812. });
  3813. // =============================================================================
  3814. // Luau (typed superset of Lua — https://luau.org)
  3815. // =============================================================================
  3816. describe('Luau Extraction', () => {
  3817. describe('Language detection', () => {
  3818. it('should detect Luau files', () => {
  3819. expect(detectLanguage('init.luau')).toBe('luau');
  3820. expect(detectLanguage('src/Client.luau')).toBe('luau');
  3821. });
  3822. it('should report Luau as supported', () => {
  3823. expect(isLanguageSupported('luau')).toBe(true);
  3824. expect(getSupportedLanguages()).toContain('luau');
  3825. });
  3826. });
  3827. describe('Type aliases', () => {
  3828. it('should extract `type` and `export type` definitions', () => {
  3829. const code = `
  3830. export type Vector = { x: number, y: number }
  3831. type Handler = (msg: string) -> boolean
  3832. `;
  3833. const result = extractFromSource('types.luau', code);
  3834. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3835. const vector = aliases.find((a) => a.name === 'Vector');
  3836. expect(vector).toBeDefined();
  3837. expect(vector?.isExported).toBe(true);
  3838. const handler = aliases.find((a) => a.name === 'Handler');
  3839. expect(handler).toBeDefined();
  3840. expect(handler?.isExported).toBe(false);
  3841. });
  3842. });
  3843. describe('Typed functions and methods', () => {
  3844. it('should capture typed signatures and split methods by receiver', () => {
  3845. const code = `
  3846. function configure(opts: { debug: boolean }): boolean
  3847. return opts.debug
  3848. end
  3849. function Client:fetch(path: string): Response
  3850. return path
  3851. end
  3852. `;
  3853. const result = extractFromSource('client.luau', code);
  3854. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  3855. expect(configure?.language).toBe('luau');
  3856. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  3857. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  3858. expect(fetch?.qualifiedName).toBe('Client::fetch');
  3859. });
  3860. });
  3861. describe('Imports and variables', () => {
  3862. it('should extract string and Roblox instance-path require imports', () => {
  3863. const code = `
  3864. local http = require("http")
  3865. local Signal = require(script.Parent.Signal)
  3866. local count = 0
  3867. `;
  3868. const result = extractFromSource('mod.luau', code);
  3869. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3870. expect(imports).toContain('http'); // string require
  3871. expect(imports).toContain('Signal'); // Roblox instance-path require
  3872. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3873. expect(vars).toContain('count');
  3874. });
  3875. });
  3876. });
  3877. // =============================================================================
  3878. // Objective-C
  3879. // =============================================================================
  3880. describe('Objective-C Extraction', () => {
  3881. const sample = `
  3882. #import <Foundation/Foundation.h>
  3883. #import "MyClass.h"
  3884. @interface MyClass : NSObject <NSCopying>
  3885. @property (nonatomic, copy) NSString *name;
  3886. - (void)greet;
  3887. - (void)doThing:(id)x with:(id)y;
  3888. + (instancetype)shared;
  3889. @end
  3890. @implementation MyClass
  3891. - (void)greet {
  3892. NSLog(@"Hello");
  3893. [self doWork];
  3894. }
  3895. - (void)doThing:(id)x with:(id)y {
  3896. [self notify:x];
  3897. }
  3898. + (instancetype)shared {
  3899. return [[MyClass alloc] init];
  3900. }
  3901. @end
  3902. void helperFunction(int count) {
  3903. MyClass *obj = [MyClass shared];
  3904. [obj greet];
  3905. }
  3906. `;
  3907. it('should extract classes, methods, functions, and imports', () => {
  3908. const result = extractFromSource('App.m', sample);
  3909. const classes = result.nodes.filter((n) => n.kind === 'class');
  3910. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  3911. const methods = result.nodes.filter((n) => n.kind === 'method');
  3912. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  3913. const shared = methods.find((m) => m.name === 'shared');
  3914. expect(shared?.isStatic).toBe(true);
  3915. const properties = result.nodes.filter((n) => n.kind === 'property');
  3916. expect(properties.some((p) => p.name === 'name')).toBe(true);
  3917. const functions = result.nodes.filter((n) => n.kind === 'function');
  3918. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  3919. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3920. expect(imports).toContain('Foundation/Foundation.h');
  3921. expect(imports).toContain('MyClass.h');
  3922. });
  3923. it('should record inheritance and protocol conformance', () => {
  3924. const result = extractFromSource('App.m', sample);
  3925. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  3926. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  3927. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  3928. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  3929. });
  3930. it('should record message sends and C calls', () => {
  3931. const result = extractFromSource('App.m', sample);
  3932. const calls = result.unresolvedReferences
  3933. .filter((r) => r.referenceKind === 'calls')
  3934. .map((r) => r.referenceName);
  3935. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  3936. });
  3937. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  3938. // Regression for the gap discovered post-#165: message_expression's
  3939. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  3940. // so calls never resolved to multi-part method definitions like
  3941. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  3942. // must match the method-definition name with full keywords + trailing colons.
  3943. const code = `
  3944. @implementation Caller
  3945. - (void)demo {
  3946. NSMutableDictionary *d = [NSMutableDictionary new];
  3947. [d setObject:@"v" forKey:@"k"];
  3948. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  3949. [self touchesBegan:nil withEvent:nil];
  3950. }
  3951. @end
  3952. `;
  3953. const result = extractFromSource('Caller.m', code);
  3954. const calls = result.unresolvedReferences
  3955. .filter((r) => r.referenceKind === 'calls')
  3956. .map((r) => r.referenceName);
  3957. expect(calls).toEqual(
  3958. expect.arrayContaining([
  3959. 'd.setObject:forKey:',
  3960. 'd.setObject:forKey:withRetry:',
  3961. 'touchesBegan:withEvent:',
  3962. ])
  3963. );
  3964. });
  3965. it('should not classify pure C headers with @end in comments as objc', () => {
  3966. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  3967. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  3968. });
  3969. it('should extract protocol declarations', () => {
  3970. const code = `
  3971. @protocol DataSource <NSObject>
  3972. - (NSInteger)numberOfItems;
  3973. @end
  3974. `;
  3975. const result = extractFromSource('DataSource.h', code);
  3976. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  3977. expect(protocol).toBeDefined();
  3978. });
  3979. it('should report Objective-C as supported', () => {
  3980. expect(isLanguageSupported('objc')).toBe(true);
  3981. expect(getSupportedLanguages()).toContain('objc');
  3982. });
  3983. });
  3984. describe('Regression: issue-specific extraction fixes', () => {
  3985. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  3986. const code = `
  3987. define(['dep'], function (dep) {
  3988. function innerHelper(x) { return x + 1; }
  3989. function compute(y) { return innerHelper(y); }
  3990. return { compute: compute };
  3991. });
  3992. `;
  3993. const result = extractFromSource('amd-module.js', code);
  3994. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  3995. expect(fns).toContain('innerHelper');
  3996. expect(fns).toContain('compute');
  3997. });
  3998. it('attaches Go methods on generic receivers to their type (#583)', () => {
  3999. const code = `
  4000. package main
  4001. type Stack[T any] struct { items []T }
  4002. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  4003. func (s Stack[T]) Len() int { return len(s.items) }
  4004. `;
  4005. const result = extractFromSource('stack.go', code);
  4006. const methods = result.nodes.filter((n) => n.kind === 'method');
  4007. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  4008. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  4009. });
  4010. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  4011. expect(isSourceFile('mod.mts')).toBe(true);
  4012. expect(isSourceFile('mod.cts')).toBe(true);
  4013. expect(isSourceFile('service.xsjs')).toBe(true);
  4014. expect(isSourceFile('lib.xsjslib')).toBe(true);
  4015. expect(detectLanguage('mod.mts')).toBe('typescript');
  4016. expect(detectLanguage('service.xsjs')).toBe('javascript');
  4017. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  4018. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  4019. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  4020. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  4021. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  4022. });
  4023. });
  4024. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  4025. // An import IS a dependency, but extraction only emits references for calls,
  4026. // instantiations, type annotations, and inheritance — so a symbol imported and
  4027. // then merely re-exported, placed in a registry array, passed as an argument,
  4028. // or used in JSX produced no cross-file edge, leaving the providing file with a
  4029. // false "0 dependents". These tests pin the import/re-export binding linking.
  4030. it('emits an imports reference per named, aliased, and default import binding', () => {
  4031. const code = `
  4032. import { widget, helper as h } from './foo';
  4033. import Thing from './thing';
  4034. import * as NS from './ns';
  4035. export const registry = [widget];
  4036. `;
  4037. const result = extractFromSource('bar.ts', code);
  4038. const names = result.unresolvedReferences
  4039. .filter((r) => r.referenceKind === 'imports')
  4040. .map((r) => r.referenceName);
  4041. expect(names).toContain('widget'); // named import → local name
  4042. expect(names).toContain('h'); // aliased import → local alias
  4043. expect(names).toContain('Thing'); // default import
  4044. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  4045. });
  4046. it('emits an imports reference per re-exported binding', () => {
  4047. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  4048. const names = result.unresolvedReferences
  4049. .filter((r) => r.referenceKind === 'imports')
  4050. .map((r) => r.referenceName);
  4051. // Re-export links the SOURCE-side name, not the local alias.
  4052. expect(names).toContain('alpha');
  4053. expect(names).toContain('beta');
  4054. });
  4055. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  4056. const dir = createTempDir();
  4057. try {
  4058. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4059. fs.writeFileSync(
  4060. path.join(dir, 'src', 'foo.ts'),
  4061. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  4062. );
  4063. // bar uses widget ONLY in an array and re-exports helper — neither is
  4064. // called/typed, so before import-linking bar had no edge to foo at all.
  4065. fs.writeFileSync(
  4066. path.join(dir, 'src', 'bar.ts'),
  4067. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  4068. );
  4069. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  4070. await cg.indexAll();
  4071. cg.resolveReferences();
  4072. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  4073. cg.destroy();
  4074. } finally {
  4075. cleanupTempDir(dir);
  4076. }
  4077. });
  4078. it('a namespace import touched only via a value-member read still links the module file', async () => {
  4079. const dir = createTempDir();
  4080. try {
  4081. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4082. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  4083. // `foo` is imported as a namespace and used ONLY via a value-member read
  4084. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  4085. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  4086. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  4087. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  4088. await cg.indexAll();
  4089. cg.resolveReferences();
  4090. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  4091. cg.destroy();
  4092. } finally {
  4093. cleanupTempDir(dir);
  4094. }
  4095. });
  4096. });
  4097. describe('Python import dependency linking (blast-radius recall)', () => {
  4098. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  4099. // name brought in with `from module import X` and then merely stored, used as
  4100. // a decorator/argument, or re-exported through an `__init__.py` produced no
  4101. // cross-file edge — the providing module showed a false "0 dependents".
  4102. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  4103. const code = [
  4104. 'from foo import helper, widget',
  4105. 'from foo import Thing as T',
  4106. 'from . import sibling',
  4107. 'from bar import *',
  4108. ].join('\n');
  4109. const names = extractFromSource('mod.py', code)
  4110. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  4111. .map((r) => r.referenceName);
  4112. expect(names).toContain('helper');
  4113. expect(names).toContain('widget'); // value import
  4114. expect(names).toContain('T'); // aliased import → local name
  4115. expect(names).toContain('sibling'); // `from . import <name>`
  4116. expect(names).not.toContain('*'); // wildcard import has no names
  4117. });
  4118. it('a Python value imported but never called still makes the importer a dependent', async () => {
  4119. const dir = createTempDir();
  4120. try {
  4121. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4122. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  4123. // bar imports widget+helper but only stores widget in a list — nothing is
  4124. // called, so before import-linking bar had no edge to foo.
  4125. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  4126. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4127. await cg.indexAll();
  4128. cg.resolveReferences();
  4129. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  4130. cg.destroy();
  4131. } finally {
  4132. cleanupTempDir(dir);
  4133. }
  4134. });
  4135. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  4136. const dir = createTempDir();
  4137. try {
  4138. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4139. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  4140. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  4141. // certs is an imported MODULE (a file), and certs.where() is a qualified
  4142. // call through it — the receiver isn't a symbol, so plain name-matching
  4143. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  4144. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  4145. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4146. await cg.indexAll();
  4147. cg.resolveReferences();
  4148. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  4149. cg.destroy();
  4150. } finally {
  4151. cleanupTempDir(dir);
  4152. }
  4153. });
  4154. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  4155. const dir = createTempDir();
  4156. try {
  4157. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4158. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  4159. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  4160. // member resolution can't find it — the module-import backstop must still
  4161. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  4162. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  4163. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  4164. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4165. await cg.indexAll();
  4166. cg.resolveReferences();
  4167. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  4168. cg.destroy();
  4169. } finally {
  4170. cleanupTempDir(dir);
  4171. }
  4172. });
  4173. });
  4174. describe('Go cross-package composite literals (blast-radius recall)', () => {
  4175. // Go function calls and type references across packages already resolved, but
  4176. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  4177. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  4178. // (gin's render/binding implementations) showed 0 dependents.
  4179. it('links a cross-package struct composite literal to the defining package', async () => {
  4180. const dir = createTempDir();
  4181. try {
  4182. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4183. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  4184. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  4185. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  4186. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4187. await cg.indexAll();
  4188. cg.resolveReferences();
  4189. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  4190. cg.destroy();
  4191. } finally {
  4192. cleanupTempDir(dir);
  4193. }
  4194. });
  4195. it('links a composite literal in a package-level var registry', async () => {
  4196. const dir = createTempDir();
  4197. try {
  4198. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4199. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  4200. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  4201. // The implementation is registered only in a top-level `var registry = {...}`
  4202. // map literal — the body walker doesn't cover top-level declarations, so this
  4203. // exercises the var-initializer walking added for Go.
  4204. fs.writeFileSync(path.join(dir, 'reg.go'), `package main\n\nimport "example.com/proj/render"\n\ntype R interface { Render() }\n\nvar registry = map[string]R{ "xml": render.XML{} }\n`);
  4205. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4206. await cg.indexAll();
  4207. cg.resolveReferences();
  4208. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  4209. cg.destroy();
  4210. } finally {
  4211. cleanupTempDir(dir);
  4212. }
  4213. });
  4214. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  4215. const dir = createTempDir();
  4216. try {
  4217. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4218. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  4219. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  4220. // `(*Wrapped)` — without normalization it dropped on the floor.
  4221. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  4222. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4223. await cg.indexAll();
  4224. cg.resolveReferences();
  4225. expect(cg.getFileDependents('types.go')).toContain('use.go');
  4226. cg.destroy();
  4227. } finally {
  4228. cleanupTempDir(dir);
  4229. }
  4230. });
  4231. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  4232. const dir = createTempDir();
  4233. try {
  4234. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4235. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  4236. fs.writeFileSync(path.join(dir, 'codec', 'api.go'), `package codec\n\ntype Core interface {\n\tMarshal(v any) ([]byte, error)\n}\n\nvar API Core\n`);
  4237. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  4238. // reached ONLY through the interface (API.Marshal). Without implicit
  4239. // interface satisfaction + dispatch, json.go shows 0 dependents.
  4240. fs.writeFileSync(path.join(dir, 'codec', 'json.go'), `package codec\n\ntype jsonApi struct{}\n\nfunc (j jsonApi) Marshal(v any) ([]byte, error) { return nil, nil }\n\nfunc init() { API = jsonApi{} }\n`);
  4241. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4242. await cg.indexAll();
  4243. cg.resolveReferences();
  4244. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  4245. cg.destroy();
  4246. } finally {
  4247. cleanupTempDir(dir);
  4248. }
  4249. });
  4250. });
  4251. describe('C# records (blast-radius recall)', () => {
  4252. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  4253. // but `record` / `record struct` declarations weren't extracted as types — so
  4254. // every reference, generic-type-argument, and `new` of a record dropped on the
  4255. // floor and the defining file showed 0 dependents. (#237)
  4256. it('extracts a record as a graph node (record class + record struct)', () => {
  4257. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  4258. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  4259. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  4260. });
  4261. it('resolves references / instantiations of a record across files', async () => {
  4262. const dir = createTempDir();
  4263. try {
  4264. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  4265. // Box is used as a generic type argument and instantiated — both require
  4266. // Box to be a node to resolve.
  4267. fs.writeFileSync(
  4268. path.join(dir, 'use.cs'),
  4269. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  4270. );
  4271. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  4272. await cg.indexAll();
  4273. cg.resolveReferences();
  4274. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  4275. cg.destroy();
  4276. } finally {
  4277. cleanupTempDir(dir);
  4278. }
  4279. });
  4280. });
  4281. describe('Rust cross-module recall', () => {
  4282. function rustProject(files: Record<string, string>): string {
  4283. const dir = createTempDir();
  4284. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  4285. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4286. for (const [rel, content] of Object.entries(files)) {
  4287. const full = path.join(dir, 'src', rel);
  4288. fs.mkdirSync(path.dirname(full), { recursive: true });
  4289. fs.writeFileSync(full, content);
  4290. }
  4291. return dir;
  4292. }
  4293. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  4294. const dir = rustProject({
  4295. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  4296. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  4297. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  4298. });
  4299. try {
  4300. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4301. await cg.indexAll();
  4302. cg.resolveReferences();
  4303. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  4304. cg.destroy();
  4305. } finally { cleanupTempDir(dir); }
  4306. });
  4307. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  4308. const dir = rustProject({
  4309. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  4310. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  4311. // Mine implements Render structurally; reached via &dyn Render dispatch.
  4312. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  4313. });
  4314. try {
  4315. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4316. await cg.indexAll();
  4317. cg.resolveReferences();
  4318. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  4319. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  4320. cg.destroy();
  4321. } finally { cleanupTempDir(dir); }
  4322. });
  4323. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  4324. const dir = rustProject({
  4325. 'lib.rs': 'pub mod api;\n',
  4326. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  4327. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  4328. });
  4329. try {
  4330. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4331. await cg.indexAll();
  4332. cg.resolveReferences();
  4333. // The re-export hub depends on the module it re-exports from.
  4334. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  4335. cg.destroy();
  4336. } finally { cleanupTempDir(dir); }
  4337. });
  4338. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  4339. const dir = rustProject({
  4340. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  4341. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  4342. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  4343. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  4344. // send this re-export to fast.rs specifically, not name-match either.
  4345. 'hub.rs': 'pub use crate::fast::read;\n',
  4346. });
  4347. try {
  4348. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4349. await cg.indexAll();
  4350. cg.resolveReferences();
  4351. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  4352. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  4353. cg.destroy();
  4354. } finally { cleanupTempDir(dir); }
  4355. });
  4356. });
  4357. describe('Java annotations (blast-radius recall)', () => {
  4358. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  4359. const dir = createTempDir();
  4360. try {
  4361. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  4362. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  4363. // live inside a `modifiers` node on the class/field/method) must extract.
  4364. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  4365. fs.writeFileSync(
  4366. path.join(dir, 'p', 'User.java'),
  4367. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  4368. );
  4369. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  4370. await cg.indexAll();
  4371. cg.resolveReferences();
  4372. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  4373. cg.destroy();
  4374. } finally { cleanupTempDir(dir); }
  4375. });
  4376. });
  4377. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  4378. it('links a @propertyWrapper usage to the wrapper type', async () => {
  4379. const dir = createTempDir();
  4380. try {
  4381. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  4382. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  4383. // `@Argument` is a Swift attribute on a stored property — it lives in the
  4384. // property's `modifiers` and Swift doesn't extract instance properties as
  4385. // their own nodes, so without the fix the wrapper type has no users.
  4386. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  4387. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  4388. await cg.indexAll();
  4389. cg.resolveReferences();
  4390. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  4391. cg.destroy();
  4392. } finally { cleanupTempDir(dir); }
  4393. });
  4394. });