extraction.test.ts 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123
  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('Ruby mixins (include/extend/prepend)', () => {
  2862. let tempDir: string;
  2863. let cg: CodeGraph;
  2864. beforeEach(() => {
  2865. tempDir = createTempDir();
  2866. });
  2867. afterEach(() => {
  2868. if (cg) cg.close();
  2869. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2870. });
  2871. it('links include/extend/prepend to the mixed-in module across files', async () => {
  2872. const lib = path.join(tempDir, 'lib');
  2873. fs.mkdirSync(lib, { recursive: true });
  2874. fs.writeFileSync(
  2875. path.join(lib, 'concerns.rb'),
  2876. `module Trackable
  2877. def track; end
  2878. end
  2879. module Cacheable
  2880. def cache; end
  2881. end
  2882. module Loggable
  2883. def log; end
  2884. end
  2885. `
  2886. );
  2887. fs.writeFileSync(
  2888. path.join(lib, 'model.rb'),
  2889. `class Model
  2890. include Trackable
  2891. prepend Cacheable
  2892. extend Loggable
  2893. end
  2894. `
  2895. );
  2896. cg = CodeGraph.initSync(tempDir);
  2897. await cg.indexAll();
  2898. cg.resolveReferences();
  2899. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  2900. expect(model).toBeDefined();
  2901. // All three mixin forms create an `implements` edge Model → module, so
  2902. // editing a concern surfaces every class that mixes it in (across files).
  2903. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  2904. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  2905. expect(mod, moduleName).toBeDefined();
  2906. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  2907. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  2908. }
  2909. });
  2910. it('resolves require / require_relative to the required file', async () => {
  2911. const lib = path.join(tempDir, 'lib');
  2912. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  2913. // A leaf file whose class is referenced only dynamically — so without
  2914. // require resolution it would look like nothing depends on it.
  2915. fs.writeFileSync(
  2916. path.join(lib, 'app', 'fetcher.rb'),
  2917. `module App
  2918. class Fetcher
  2919. def fetch; end
  2920. end
  2921. end
  2922. `
  2923. );
  2924. // Pulled in by a load-path `require` …
  2925. fs.writeFileSync(
  2926. path.join(lib, 'app', 'worker.rb'),
  2927. `require "app/fetcher"
  2928. module App
  2929. class Worker; end
  2930. end
  2931. `
  2932. );
  2933. // … and a sibling pulled in by `require_relative`.
  2934. fs.writeFileSync(
  2935. path.join(lib, 'app', 'boot.rb'),
  2936. `require_relative "fetcher"
  2937. `
  2938. );
  2939. cg = CodeGraph.initSync(tempDir);
  2940. await cg.indexAll();
  2941. cg.resolveReferences();
  2942. // The require edges target fetcher.rb's FILE node. Editing it should reach
  2943. // BOTH the load-path requirer (worker.rb) and the require_relative one
  2944. // (boot.rb) — without require resolution its file would have no dependents.
  2945. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  2946. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  2947. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  2948. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  2949. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  2950. });
  2951. });
  2952. describe('C++ free-function name extraction', () => {
  2953. let tempDir: string;
  2954. let cg: CodeGraph;
  2955. beforeEach(() => {
  2956. tempDir = createTempDir();
  2957. });
  2958. afterEach(() => {
  2959. if (cg) cg.close();
  2960. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2961. });
  2962. it('names a free function correctly when it has qualified-type params or a trailing return type', async () => {
  2963. const src = path.join(tempDir, 'src');
  2964. fs.mkdirSync(src, { recursive: true });
  2965. // TableFileName has a `const std::string&` parameter; BuildName uses an
  2966. // `auto … -> std::string` trailing return type. Both used to be named
  2967. // `string` (picked up from the parameter / return type), so callers never
  2968. // resolved and the defining file looked like nothing depended on it.
  2969. fs.writeFileSync(
  2970. path.join(src, 'names.cc'),
  2971. `#include <string>
  2972. std::string TableFileName(const std::string& dbname, int number) {
  2973. return dbname;
  2974. }
  2975. auto BuildName(const std::string& a) -> std::string {
  2976. return a;
  2977. }
  2978. `
  2979. );
  2980. fs.writeFileSync(
  2981. path.join(src, 'user.cc'),
  2982. `#include <string>
  2983. std::string use() {
  2984. return TableFileName("db", 1) + BuildName("x");
  2985. }
  2986. `
  2987. );
  2988. cg = CodeGraph.initSync(tempDir);
  2989. await cg.indexAll();
  2990. cg.resolveReferences();
  2991. // The functions are extracted under their real names, not `string`.
  2992. const fns = cg.getNodesByKind('function');
  2993. const tableFn = fns.find((n) => n.name === 'TableFileName');
  2994. const buildFn = fns.find((n) => n.name === 'BuildName');
  2995. expect(tableFn, 'TableFileName extracted (not "string")').toBeDefined();
  2996. expect(buildFn, 'BuildName extracted (not "string")').toBeDefined();
  2997. // And the cross-file calls resolve to them, so editing names.cc surfaces user.cc.
  2998. for (const fn of [tableFn!, buildFn!]) {
  2999. const reached = [...cg.getImpactRadius(fn.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3000. expect(reached.some((p) => p.endsWith('user.cc')), `${fn.name} should be called from user.cc`).toBe(true);
  3001. }
  3002. });
  3003. });
  3004. describe('Dart mixins and type references', () => {
  3005. let tempDir: string;
  3006. let cg: CodeGraph;
  3007. beforeEach(() => {
  3008. tempDir = createTempDir();
  3009. });
  3010. afterEach(() => {
  3011. if (cg) cg.close();
  3012. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3013. });
  3014. it('links `with` mixins and method parameter/return types across files', async () => {
  3015. const lib = path.join(tempDir, 'lib');
  3016. fs.mkdirSync(lib, { recursive: true });
  3017. fs.writeFileSync(
  3018. path.join(lib, 'models.dart'),
  3019. `class User {
  3020. final String name;
  3021. User(this.name);
  3022. }
  3023. mixin Loggable {
  3024. void log() {}
  3025. }
  3026. abstract class Repository {
  3027. User find(int id);
  3028. }
  3029. `
  3030. );
  3031. fs.writeFileSync(
  3032. path.join(lib, 'service.dart'),
  3033. `import 'models.dart';
  3034. class UserService extends Repository with Loggable {
  3035. @override
  3036. User find(int id) => User('x');
  3037. List<User> all() => [];
  3038. }
  3039. `
  3040. );
  3041. cg = CodeGraph.initSync(tempDir);
  3042. await cg.indexAll();
  3043. cg.resolveReferences();
  3044. const inModels = (name: string) =>
  3045. cg.getNodesByKind('class').concat(cg.getNodesByKind('module'))
  3046. .find((n) => n.name === name && n.filePath.endsWith('models.dart'));
  3047. // The `with Loggable` mixin records a dependency — editing the mixin surfaces
  3048. // the class that mixes it in (across files). Loggable is a `mixin`, indexed
  3049. // as a class-like node.
  3050. const loggable = cg.getNodesByKind('class').find((n) => n.name === 'Loggable')
  3051. ?? cg.getNodesByKind('module').find((n) => n.name === 'Loggable');
  3052. expect(loggable, 'Loggable mixin indexed').toBeDefined();
  3053. const mixinUsers = [...cg.getImpactRadius(loggable!.id, 3).nodes.values()].map((n) => n.name);
  3054. expect(mixinUsers).toContain('UserService');
  3055. // `User` is used only as a method parameter/return type in service.dart —
  3056. // editing it must still surface service.dart via the type references.
  3057. const user = inModels('User') ?? cg.getNodesByKind('class').find((n) => n.name === 'User');
  3058. expect(user, 'User indexed').toBeDefined();
  3059. const userDeps = [...cg.getImpactRadius(user!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3060. expect(userDeps.some((p) => p.endsWith('service.dart'))).toBe(true);
  3061. });
  3062. });
  3063. describe('Static-member / value-read references', () => {
  3064. let tempDir: string;
  3065. let cg: CodeGraph;
  3066. beforeEach(() => {
  3067. tempDir = createTempDir();
  3068. });
  3069. afterEach(() => {
  3070. if (cg) cg.close();
  3071. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3072. });
  3073. it('links a type referenced only via a static field / enum value (and ignores lowercase receivers)', async () => {
  3074. fs.writeFileSync(
  3075. path.join(tempDir, 'JsonScope.java'),
  3076. `class JsonScope {
  3077. static final int EMPTY_DOCUMENT = 1;
  3078. }
  3079. `
  3080. );
  3081. fs.writeFileSync(
  3082. path.join(tempDir, 'Reader.java'),
  3083. `class Reader {
  3084. private int helper;
  3085. int peek() {
  3086. return JsonScope.EMPTY_DOCUMENT;
  3087. }
  3088. int noop() {
  3089. return this.helper;
  3090. }
  3091. }
  3092. `
  3093. );
  3094. cg = CodeGraph.initSync(tempDir);
  3095. await cg.indexAll();
  3096. cg.resolveReferences();
  3097. // JsonScope is used ONLY as `JsonScope.EMPTY_DOCUMENT` (a static-field value
  3098. // read — never constructed or called), so before the static-member pass it
  3099. // had no dependents. Editing it now surfaces Reader.java.
  3100. const scope = cg.getNodesByKind('class').find((n) => n.name === 'JsonScope');
  3101. expect(scope, 'JsonScope indexed').toBeDefined();
  3102. const reached = [...cg.getImpactRadius(scope!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3103. expect(reached.some((p) => p.endsWith('Reader.java'))).toBe(true);
  3104. // A lowercase receiver (`this.helper`) must NOT be emitted as a type ref —
  3105. // only Capitalized receivers (types) are. No node named `this`/`helper`
  3106. // should appear as a reference target from peek/noop beyond JsonScope.
  3107. const refTargets = cg
  3108. .getNodesByKind('class')
  3109. .filter((n) => n.name === 'this' || n.name === 'helper');
  3110. expect(refTargets.length).toBe(0);
  3111. });
  3112. it('does not link a static-member read across language families (coincidental name)', async () => {
  3113. // A native (Kotlin) `Build.VERSION` reads the Android system class — it must
  3114. // NOT link to a coincidentally same-named TS class (the cross-language false
  3115. // positive that name-matching produces; `references` edges are language-local).
  3116. fs.writeFileSync(
  3117. path.join(tempDir, 'Build.ts'),
  3118. `export class Build {\n static version = 1;\n}\n`
  3119. );
  3120. fs.writeFileSync(
  3121. path.join(tempDir, 'Device.kt'),
  3122. `package app\nclass Device {\n fun sdk(): Int = Build.VERSION\n}\n`
  3123. );
  3124. cg = CodeGraph.initSync(tempDir);
  3125. await cg.indexAll();
  3126. cg.resolveReferences();
  3127. const tsBuild = cg.getNodesByKind('class').find((n) => n.name === 'Build' && n.filePath.endsWith('Build.ts'));
  3128. expect(tsBuild).toBeDefined();
  3129. // The Kotlin file is `app/Device.kt`; the TS Build must have NO dependent there.
  3130. const deps = [...cg.getImpactRadius(tsBuild!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3131. expect(deps.some((p) => p.endsWith('Device.kt'))).toBe(false);
  3132. });
  3133. });
  3134. describe('Cross-language type/import gate (RN name collisions)', () => {
  3135. let tempDir: string;
  3136. let cg: CodeGraph;
  3137. beforeEach(() => {
  3138. tempDir = createTempDir();
  3139. });
  3140. afterEach(() => {
  3141. if (cg) cg.close();
  3142. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3143. });
  3144. it('a TS PascalCase type ref lands on the TS type, never a same-named native class', async () => {
  3145. // react-native-async-storage's example app has a TS `type TestRunner` AND a
  3146. // Kotlin `class TestRunner`. The React PascalCase resolver name-matched the
  3147. // Kotlin `class` (its COMPONENT_KINDS includes `class`) with no language
  3148. // check at confidence 0.8, outranking the (cross-language-penalized 0.5)
  3149. // TS name-match — so a TS ref to `TestRunner` crossed web→jvm. The ref here
  3150. // is intentionally NOT imported: a clean relative import would mask the bug
  3151. // by resolving via the import map before the framework strategy can win.
  3152. fs.writeFileSync(
  3153. path.join(tempDir, 'package.json'),
  3154. JSON.stringify({ dependencies: { 'react-native': '*' } })
  3155. );
  3156. fs.writeFileSync(
  3157. path.join(tempDir, 'useTests.ts'),
  3158. `export type TestRunner = { run: () => void };\n`
  3159. );
  3160. fs.writeFileSync(
  3161. path.join(tempDir, 'basic.tsx'),
  3162. `export function useBasicTest(r: TestRunner): TestRunner {\n return r;\n}\n`
  3163. );
  3164. fs.writeFileSync(
  3165. path.join(tempDir, 'TestUtils.kt'),
  3166. `package app\nclass TestRunner {\n fun run() {}\n}\n`
  3167. );
  3168. cg = CodeGraph.initSync(tempDir);
  3169. await cg.indexAll();
  3170. cg.resolveReferences();
  3171. const ktRunner = cg
  3172. .getNodesByKind('class')
  3173. .find((n) => n.name === 'TestRunner' && n.filePath.endsWith('TestUtils.kt'));
  3174. expect(ktRunner, 'Kotlin TestRunner class').toBeDefined();
  3175. const ktDeps = [...cg.getImpactRadius(ktRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3176. expect(ktDeps.some((p) => p.endsWith('basic.tsx')), 'Kotlin class has NO TS dependent').toBe(false);
  3177. const tsRunner = cg.getNodesByKind('type_alias').find((n) => n.name === 'TestRunner');
  3178. expect(tsRunner, 'TS TestRunner type_alias').toBeDefined();
  3179. const tsDeps = [...cg.getImpactRadius(tsRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3180. expect(tsDeps.some((p) => p.endsWith('basic.tsx')), 'TS type captured the ref (re-pointed)').toBe(true);
  3181. });
  3182. it('gates a cross-family import name collision but keeps same-family imports', async () => {
  3183. // A TS `import { Widget }` that only matches a Swift `class Widget` must not
  3184. // create a web→apple dependency — but a sibling TS module imported by
  3185. // another TS file (same family) must still resolve (no over-gating).
  3186. fs.writeFileSync(path.join(tempDir, 'Widget.swift'), `class Widget {\n func render() {}\n}\n`);
  3187. fs.writeFileSync(
  3188. path.join(tempDir, 'widget.ts'),
  3189. `import { Widget } from './native';\nexport function mount(w: Widget) {}\n`
  3190. );
  3191. fs.writeFileSync(path.join(tempDir, 'util.ts'), `export class Helper {}\n`);
  3192. fs.writeFileSync(
  3193. path.join(tempDir, 'app.ts'),
  3194. `import { Helper } from './util';\nexport const h = new Helper();\n`
  3195. );
  3196. cg = CodeGraph.initSync(tempDir);
  3197. await cg.indexAll();
  3198. cg.resolveReferences();
  3199. const swiftWidget = cg
  3200. .getNodesByKind('class')
  3201. .find((n) => n.name === 'Widget' && n.filePath.endsWith('.swift'));
  3202. expect(swiftWidget, 'Swift Widget class').toBeDefined();
  3203. const wDeps = [...cg.getImpactRadius(swiftWidget!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3204. expect(wDeps.some((p) => p.endsWith('widget.ts')), 'Swift class has NO TS dependent').toBe(false);
  3205. // Same-family control — the TS Helper must still see its TS dependent.
  3206. const helper = cg.getNodesByKind('class').find((n) => n.name === 'Helper');
  3207. expect(helper, 'TS Helper class').toBeDefined();
  3208. const hDeps = [...cg.getImpactRadius(helper!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3209. expect(hDeps.some((p) => p.endsWith('app.ts')), 'same-family TS import preserved').toBe(true);
  3210. });
  3211. });
  3212. describe('Python absolute module import resolution', () => {
  3213. let tempDir: string;
  3214. let cg: CodeGraph;
  3215. beforeEach(() => {
  3216. tempDir = createTempDir();
  3217. });
  3218. afterEach(() => {
  3219. if (cg) cg.close();
  3220. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3221. });
  3222. it('links a bare `import pkg.module` of an internal module to its file', async () => {
  3223. // `import conduit.apps.signals` (a Django-style side-effect import, and any
  3224. // dotted absolute module import) had no edge to the module file — only
  3225. // `from x import y` was linked — so a module imported by its dotted path
  3226. // looked like nothing depended on it.
  3227. fs.mkdirSync(path.join(tempDir, 'conduit/apps'), { recursive: true });
  3228. fs.writeFileSync(path.join(tempDir, 'conduit/__init__.py'), '');
  3229. fs.writeFileSync(path.join(tempDir, 'conduit/apps/__init__.py'), '');
  3230. fs.writeFileSync(path.join(tempDir, 'conduit/apps/signals.py'), `def handler():\n pass\n`);
  3231. fs.writeFileSync(
  3232. path.join(tempDir, 'conduit/apps/app.py'),
  3233. `import conduit.apps.signals\nimport os\n\nVALUE = 1\n`
  3234. );
  3235. cg = CodeGraph.initSync(tempDir);
  3236. await cg.indexAll();
  3237. cg.resolveReferences();
  3238. const signals = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('conduit/apps/signals.py'));
  3239. expect(signals, 'signals.py indexed').toBeDefined();
  3240. const deps = [...cg.getImpactRadius(signals!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3241. expect(deps.some((p) => p.endsWith('app.py')), 'importer depends on the module').toBe(true);
  3242. // `import os` (stdlib) must NOT fabricate an edge — no os.py file in the repo.
  3243. const osNode = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('/os.py'));
  3244. expect(osNode, 'no stdlib os.py node').toBeUndefined();
  3245. });
  3246. it('Django include() links the root URLconf to the included app urls module', async () => {
  3247. // `url(r'^api/', include('app.urls'))` should record a dependency from the
  3248. // root urlconf onto the included app's `urls.py` — so editing an app's routes
  3249. // surfaces the project urlconf that mounts them.
  3250. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3251. fs.writeFileSync(path.join(tempDir, 'requirements.txt'), `django==4.0\n`);
  3252. fs.writeFileSync(path.join(tempDir, 'app/__init__.py'), '');
  3253. fs.writeFileSync(path.join(tempDir, 'app/views.py'), `def home(request):\n return None\n`);
  3254. fs.writeFileSync(
  3255. path.join(tempDir, 'app/urls.py'),
  3256. `from django.conf.urls import url\nfrom . import views\nurlpatterns = [url(r'^$', views.home)]\n`
  3257. );
  3258. fs.writeFileSync(
  3259. path.join(tempDir, 'urls.py'),
  3260. `from django.conf.urls import include, url\nurlpatterns = [url(r'^app/', include('app.urls'))]\n`
  3261. );
  3262. cg = CodeGraph.initSync(tempDir);
  3263. await cg.indexAll();
  3264. cg.resolveReferences();
  3265. const appUrls = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/urls.py'));
  3266. expect(appUrls, 'app/urls.py indexed').toBeDefined();
  3267. const deps = [...cg.getImpactRadius(appUrls!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3268. expect(deps.some((p) => p.endsWith('urls.py') && !p.endsWith('app/urls.py')), 'root urlconf depends on the included app urls').toBe(true);
  3269. });
  3270. it('resolves `from pkg import submodule` to the submodule under that package, not a same-named one', async () => {
  3271. // FastAPI router-aggregator pattern: `from app.api.routes import authentication`
  3272. // with same-named modules in sibling packages must resolve via the import's
  3273. // SOURCE (the package), not a coincidental same-basename file elsewhere.
  3274. fs.mkdirSync(path.join(tempDir, 'app/api/routes'), { recursive: true });
  3275. fs.mkdirSync(path.join(tempDir, 'app/api/dependencies'), { recursive: true });
  3276. for (const p of ['app/__init__.py', 'app/api/__init__.py', 'app/api/routes/__init__.py', 'app/api/dependencies/__init__.py']) {
  3277. fs.writeFileSync(path.join(tempDir, p), '');
  3278. }
  3279. fs.writeFileSync(path.join(tempDir, 'app/api/routes/authentication.py'), `def login():\n pass\n`);
  3280. fs.writeFileSync(path.join(tempDir, 'app/api/dependencies/authentication.py'), `def get_user():\n pass\n`);
  3281. fs.writeFileSync(
  3282. path.join(tempDir, 'app/api/routes/api.py'),
  3283. `from app.api.routes import authentication\n\nROUTER = authentication\n`
  3284. );
  3285. cg = CodeGraph.initSync(tempDir);
  3286. await cg.indexAll();
  3287. cg.resolveReferences();
  3288. const routesAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('routes/authentication.py'));
  3289. const depsAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('dependencies/authentication.py'));
  3290. expect(routesAuth && depsAuth).toBeTruthy();
  3291. const routesDeps = [...cg.getImpactRadius(routesAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3292. const depsDeps = [...cg.getImpactRadius(depsAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3293. expect(routesDeps.some((p) => p.endsWith('routes/api.py')), 'submodule under the imported package is the dependent').toBe(true);
  3294. expect(depsDeps.some((p) => p.endsWith('routes/api.py')), 'same-named module in a sibling package is NOT').toBe(false);
  3295. });
  3296. });
  3297. describe('Razor / Blazor markup extraction', () => {
  3298. let tempDir: string;
  3299. let cg: CodeGraph;
  3300. beforeEach(() => {
  3301. tempDir = createTempDir();
  3302. });
  3303. afterEach(() => {
  3304. if (cg) cg.close();
  3305. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3306. });
  3307. it('links @model and Blazor component tags to their C# types; ignores HTML elements', async () => {
  3308. fs.mkdirSync(path.join(tempDir, 'Views'), { recursive: true });
  3309. fs.writeFileSync(
  3310. path.join(tempDir, 'LoginViewModel.cs'),
  3311. `namespace App { public class LoginViewModel { public string Email { get; set; } } }`
  3312. );
  3313. fs.writeFileSync(
  3314. path.join(tempDir, 'ToastComponent.cs'),
  3315. `namespace App { public class ToastComponent { } }`
  3316. );
  3317. fs.writeFileSync(
  3318. path.join(tempDir, 'Views/Login.cshtml'),
  3319. `@model LoginViewModel\n<div class="form">\n <input asp-for="Email" />\n</div>\n`
  3320. );
  3321. fs.writeFileSync(
  3322. path.join(tempDir, 'Index.razor'),
  3323. `<div>\n <ToastComponent />\n</div>\n`
  3324. );
  3325. cg = CodeGraph.initSync(tempDir);
  3326. await cg.indexAll();
  3327. cg.resolveReferences();
  3328. // `@model LoginViewModel` → the view-model class.
  3329. const vm = cg.getNodesByKind('class').find((n) => n.name === 'LoginViewModel');
  3330. expect(vm, 'LoginViewModel class').toBeDefined();
  3331. const vmDeps = [...cg.getImpactRadius(vm!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3332. expect(vmDeps.some((p) => p.endsWith('Login.cshtml')), '@model links the view').toBe(true);
  3333. // `<ToastComponent />` → the component class.
  3334. const toast = cg.getNodesByKind('class').find((n) => n.name === 'ToastComponent');
  3335. expect(toast, 'ToastComponent class').toBeDefined();
  3336. const toastDeps = [...cg.getImpactRadius(toast!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3337. expect(toastDeps.some((p) => p.endsWith('Index.razor')), 'Blazor tag links the component').toBe(true);
  3338. // HTML elements (`<div>`, `<input>`) must NOT become component references.
  3339. const htmlNodes = cg.getNodesByKind('class').filter((n) => n.name === 'div' || n.name === 'input');
  3340. expect(htmlNodes.length, 'no node for HTML elements').toBe(0);
  3341. });
  3342. it('C# namespaces qualify type names so same-named types are distinct', async () => {
  3343. fs.writeFileSync(path.join(tempDir, 'entity.cs'), `namespace App.Entities { public class CatalogBrand { } }`);
  3344. fs.writeFileSync(path.join(tempDir, 'dto.cs'), `namespace App.Models { public class CatalogBrand { } }`);
  3345. cg = CodeGraph.initSync(tempDir);
  3346. await cg.indexAll();
  3347. const brands = cg.getNodesByKind('class').filter((n) => n.name === 'CatalogBrand');
  3348. expect(brands.length, 'both CatalogBrand classes indexed').toBe(2);
  3349. const qns = brands.map((b) => b.qualifiedName).sort();
  3350. expect(qns[0]).not.toBe(qns[1]); // distinct qualified names (namespace-scoped)
  3351. expect(qns.some((q) => q.includes('Entities') && q.endsWith('CatalogBrand'))).toBe(true);
  3352. expect(qns.some((q) => q.includes('Models') && q.endsWith('CatalogBrand'))).toBe(true);
  3353. });
  3354. it('disambiguates a Razor type ref via @using (incl. folder _Imports.razor)', async () => {
  3355. // `CatalogBrand` exists as both a domain entity and a DTO; the component
  3356. // `@using`s the DTO's namespace (here via the folder _Imports.razor), so the
  3357. // ref must resolve to the DTO, not the same-named entity.
  3358. fs.mkdirSync(path.join(tempDir, 'Models'), { recursive: true });
  3359. fs.mkdirSync(path.join(tempDir, 'Entities'), { recursive: true });
  3360. fs.mkdirSync(path.join(tempDir, 'Pages'), { recursive: true });
  3361. fs.writeFileSync(path.join(tempDir, 'Models/CatalogBrand.cs'), `namespace App.Models { public class CatalogBrand { public int Id { get; set; } } }`);
  3362. fs.writeFileSync(path.join(tempDir, 'Entities/CatalogBrand.cs'), `namespace App.Entities { public class CatalogBrand { public int Id { get; set; } } }`);
  3363. fs.writeFileSync(path.join(tempDir, 'Pages/_Imports.razor'), `@using App.Models\n`);
  3364. fs.writeFileSync(
  3365. path.join(tempDir, 'Pages/List.razor'),
  3366. `<h1>List</h1>\n@code {\n private CatalogBrand _b = new CatalogBrand();\n}\n`
  3367. );
  3368. cg = CodeGraph.initSync(tempDir);
  3369. await cg.indexAll();
  3370. cg.resolveReferences();
  3371. const dto = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Models::CatalogBrand');
  3372. const entity = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Entities::CatalogBrand');
  3373. expect(dto && entity, 'both CatalogBrand classes').toBeTruthy();
  3374. const dtoDeps = [...cg.getImpactRadius(dto!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3375. const entityDeps = [...cg.getImpactRadius(entity!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3376. expect(dtoDeps.some((p) => p.endsWith('List.razor')), 'resolves to the @using\'d DTO').toBe(true);
  3377. expect(entityDeps.some((p) => p.endsWith('List.razor')), 'NOT the same-named entity').toBe(false);
  3378. });
  3379. it('delegates Blazor @code block C# to cover types used in component logic', async () => {
  3380. fs.writeFileSync(
  3381. path.join(tempDir, 'CatalogService.cs'),
  3382. `namespace App { public class CatalogService { public void Load() { } } }`
  3383. );
  3384. fs.writeFileSync(
  3385. path.join(tempDir, 'List.razor'),
  3386. `<h1>Catalog</h1>\n\n@code {\n private CatalogService _svc = new CatalogService();\n void Refresh() { _svc.Load(); }\n}\n`
  3387. );
  3388. cg = CodeGraph.initSync(tempDir);
  3389. await cg.indexAll();
  3390. cg.resolveReferences();
  3391. const svc = cg.getNodesByKind('class').find((n) => n.name === 'CatalogService');
  3392. expect(svc, 'CatalogService class').toBeDefined();
  3393. const deps = [...cg.getImpactRadius(svc!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3394. expect(deps.some((p) => p.endsWith('List.razor')), '@code usage links the component to the service').toBe(true);
  3395. });
  3396. });
  3397. describe('Default import resolution (renamed default export)', () => {
  3398. let tempDir: string;
  3399. let cg: CodeGraph;
  3400. beforeEach(() => {
  3401. tempDir = createTempDir();
  3402. });
  3403. afterEach(() => {
  3404. if (cg) cg.close();
  3405. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3406. });
  3407. it('links a renamed default import to the module file', async () => {
  3408. // Express route aggregator: `import articlesController from './controller'`
  3409. // where the module does `export default router`. The renamed local can't be
  3410. // found as a symbol, so the controller file had no dependent — the dependency
  3411. // is on the module file regardless of the default export's name.
  3412. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3413. fs.writeFileSync(path.join(tempDir, 'app/controller.ts'), `const router = { get() {} };\nexport default router;\n`);
  3414. fs.writeFileSync(path.join(tempDir, 'app/routes.ts'), `import myController from './controller';\nexport const api = myController;\n`);
  3415. cg = CodeGraph.initSync(tempDir);
  3416. await cg.indexAll();
  3417. cg.resolveReferences();
  3418. const controller = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/controller.ts'));
  3419. expect(controller, 'controller.ts indexed').toBeDefined();
  3420. const deps = [...cg.getImpactRadius(controller!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3421. expect(deps.some((p) => p.endsWith('routes.ts')), 'importer depends on the default-exporting module').toBe(true);
  3422. });
  3423. });
  3424. describe('Chained method-call resolution (C# extension methods)', () => {
  3425. let tempDir: string;
  3426. let cg: CodeGraph;
  3427. beforeEach(() => {
  3428. tempDir = createTempDir();
  3429. });
  3430. afterEach(() => {
  3431. if (cg) cg.close();
  3432. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3433. });
  3434. it('resolves a chained extension-method call (a.b.Method()) to its definition', async () => {
  3435. // ASP.NET DI registration: `builder.Services.AddCoreServices(...)` calls a
  3436. // static extension method elsewhere. A multi-dot receiver chain matched no
  3437. // method-call pattern before, so the extension method had no caller.
  3438. fs.mkdirSync(path.join(tempDir, 'cfg'), { recursive: true });
  3439. fs.writeFileSync(
  3440. path.join(tempDir, 'cfg/Ext.cs'),
  3441. `namespace App {\n public static class Ext {\n public static object AddCoreServices(this object services, int x) { return services; }\n }\n}\n`
  3442. );
  3443. fs.writeFileSync(
  3444. path.join(tempDir, 'Program.cs'),
  3445. `namespace App {\n public class Program {\n public void Run(object builder) {\n builder.Services.AddCoreServices(1);\n }\n }\n}\n`
  3446. );
  3447. cg = CodeGraph.initSync(tempDir);
  3448. await cg.indexAll();
  3449. cg.resolveReferences();
  3450. const ext = cg
  3451. .getNodesByKind('method')
  3452. .find((n) => n.name === 'AddCoreServices')
  3453. ?? cg.getNodesByKind('function').find((n) => n.name === 'AddCoreServices');
  3454. expect(ext, 'AddCoreServices defined').toBeDefined();
  3455. const callers = [...cg.getImpactRadius(ext!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3456. expect(callers.some((p) => p.endsWith('Program.cs')), 'chained extension call resolves to its definition').toBe(true);
  3457. });
  3458. });
  3459. describe('Same-directory include + KMP import resolution', () => {
  3460. let tempDir: string;
  3461. let cg: CodeGraph;
  3462. beforeEach(() => {
  3463. tempDir = createTempDir();
  3464. });
  3465. afterEach(() => {
  3466. if (cg) cg.close();
  3467. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3468. });
  3469. it('a C/C++ #include resolves to the same-directory header, not a same-named one elsewhere', async () => {
  3470. // A multi-platform native module has a header of the same basename per
  3471. // platform. `windows/Provider.cpp`'s `#include "Storage.h"` means its OWN
  3472. // sibling header — not `apple/Storage.h` (which sorts first and so was
  3473. // picked arbitrarily before, leaving the real local header with 0 deps).
  3474. fs.mkdirSync(path.join(tempDir, 'apple'), { recursive: true });
  3475. fs.mkdirSync(path.join(tempDir, 'windows'), { recursive: true });
  3476. fs.writeFileSync(path.join(tempDir, 'apple', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3477. fs.writeFileSync(path.join(tempDir, 'windows', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3478. fs.writeFileSync(
  3479. path.join(tempDir, 'windows', 'Provider.cpp'),
  3480. `#include "Storage.h"\nint use() { Storage s; return s.n; }\n`
  3481. );
  3482. cg = CodeGraph.initSync(tempDir);
  3483. await cg.indexAll();
  3484. cg.resolveReferences();
  3485. const winHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('windows/Storage.h'));
  3486. const appleHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('apple/Storage.h'));
  3487. expect(winHeader, 'windows/Storage.h indexed').toBeDefined();
  3488. expect(appleHeader, 'apple/Storage.h indexed').toBeDefined();
  3489. const winDeps = [...cg.getImpactRadius(winHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3490. const appleDeps = [...cg.getImpactRadius(appleHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3491. expect(winDeps.some((p) => p.endsWith('Provider.cpp')), 'same-dir header gets the includer').toBe(true);
  3492. expect(appleDeps.some((p) => p.endsWith('Provider.cpp')), 'other-platform header does NOT').toBe(false);
  3493. });
  3494. it('a Kotlin Multiplatform commonMain import resolves to the expect, not a platform actual', async () => {
  3495. const common = path.join(tempDir, 'src/commonMain/kotlin/app');
  3496. const android = path.join(tempDir, 'src/androidMain/kotlin/app');
  3497. fs.mkdirSync(common, { recursive: true });
  3498. fs.mkdirSync(android, { recursive: true });
  3499. fs.writeFileSync(path.join(common, 'Platform.kt'), `package app\nexpect class PlatformContext\n`);
  3500. fs.writeFileSync(path.join(android, 'Platform.android.kt'), `package app\nactual class PlatformContext\n`);
  3501. fs.writeFileSync(
  3502. path.join(common, 'Db.kt'),
  3503. `package app\nimport app.PlatformContext\nclass Db {\n fun open(ctx: PlatformContext) {}\n}\n`
  3504. );
  3505. cg = CodeGraph.initSync(tempDir);
  3506. await cg.indexAll();
  3507. cg.resolveReferences();
  3508. const expectCtx = cg
  3509. .getNodesByKind('class')
  3510. .find((n) => n.name === 'PlatformContext' && n.filePath.endsWith('commonMain/kotlin/app/Platform.kt'));
  3511. expect(expectCtx, 'commonMain expect PlatformContext').toBeDefined();
  3512. const deps = [...cg.getImpactRadius(expectCtx!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3513. expect(deps.some((p) => p.endsWith('Db.kt')), 'commonMain import lands on the expect, not the actual').toBe(true);
  3514. });
  3515. });
  3516. describe('Rust module-path call resolution', () => {
  3517. let tempDir: string;
  3518. let cg: CodeGraph;
  3519. beforeEach(() => {
  3520. tempDir = createTempDir();
  3521. });
  3522. afterEach(() => {
  3523. if (cg) cg.close();
  3524. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3525. });
  3526. it('a bare submodule call (`users::router()`) resolves self-relative to the submodule fn', async () => {
  3527. // The canonical Axum router-assembly pattern: a parent module calls each
  3528. // submodule's `router()`. `users::` / `profiles::` are SELF-relative
  3529. // submodule prefixes (2018 edition) — `mod users;` makes `users` a child of
  3530. // the CURRENT module, NOT `crate::users`. Before the fix the bare prefix was
  3531. // resolved crate-relative only (looking for `src/users.rs`), so it found
  3532. // nothing and the handler modules looked dependent-less.
  3533. const http = path.join(tempDir, 'src/http');
  3534. fs.mkdirSync(http, { recursive: true });
  3535. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod http;\n`);
  3536. fs.writeFileSync(
  3537. path.join(http, 'mod.rs'),
  3538. `mod users;\nmod profiles;\npub fn api_router() {\n users::router();\n profiles::router();\n}\n`
  3539. );
  3540. fs.writeFileSync(path.join(http, 'users.rs'), `pub fn router() -> i32 { 1 }\n`);
  3541. fs.writeFileSync(path.join(http, 'profiles.rs'), `pub fn router() -> i32 { 2 }\n`);
  3542. cg = CodeGraph.initSync(tempDir);
  3543. await cg.indexAll();
  3544. cg.resolveReferences();
  3545. // Each submodule's same-named `router` fn must get mod.rs as a dependent —
  3546. // proving the bare prefix resolved self-relative AND disambiguated the
  3547. // colliding `router` name to the correct file (not an arbitrary one).
  3548. const routers = cg.getNodesByKind('function').filter((n) => n.name === 'router');
  3549. const usersRouter = routers.find((n) => n.filePath.endsWith('http/users.rs'));
  3550. const profilesRouter = routers.find((n) => n.filePath.endsWith('http/profiles.rs'));
  3551. expect(usersRouter, 'users.rs router fn').toBeDefined();
  3552. expect(profilesRouter, 'profiles.rs router fn').toBeDefined();
  3553. const usersDeps = [...cg.getImpactRadius(usersRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3554. const profilesDeps = [...cg.getImpactRadius(profilesRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3555. expect(usersDeps.some((p) => p.endsWith('http/mod.rs')), 'users::router() lands on users.rs').toBe(true);
  3556. expect(profilesDeps.some((p) => p.endsWith('http/mod.rs')), 'profiles::router() lands on profiles.rs').toBe(true);
  3557. });
  3558. it('a 3-segment module-path call (`database::profiles::find()`) resolves to the leaf fn', async () => {
  3559. // A 2-level module path — the common `db.run(move |c| database::profiles::find(c))`
  3560. // / `crate::a::b::func()` shape. The reference-resolver pre-filter used to drop any
  3561. // `a::b::c` whose leaf it never checked (it tested only the first segment and the
  3562. // `b::c` remainder, neither of which names a symbol), so the call never reached the
  3563. // Rust path resolver and the leaf module looked dependent-less.
  3564. const routes = path.join(tempDir, 'src/routes');
  3565. const database = path.join(tempDir, 'src/database');
  3566. fs.mkdirSync(routes, { recursive: true });
  3567. fs.mkdirSync(database, { recursive: true });
  3568. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod routes;\npub mod database;\n`);
  3569. fs.writeFileSync(path.join(database, 'mod.rs'), `pub mod profiles;\n`);
  3570. fs.writeFileSync(path.join(database, 'profiles.rs'), `pub fn find(id: i32) -> i32 { id }\n`);
  3571. fs.writeFileSync(
  3572. path.join(routes, 'mod.rs'),
  3573. `use crate::database;\npub fn get_profile(id: i32) -> i32 {\n database::profiles::find(id)\n}\n`
  3574. );
  3575. cg = CodeGraph.initSync(tempDir);
  3576. await cg.indexAll();
  3577. cg.resolveReferences();
  3578. const find = cg
  3579. .getNodesByKind('function')
  3580. .find((n) => n.name === 'find' && n.filePath.endsWith('database/profiles.rs'));
  3581. expect(find, 'database/profiles.rs find fn').toBeDefined();
  3582. const deps = [...cg.getImpactRadius(find!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3583. expect(deps.some((p) => p.endsWith('routes/mod.rs')), 'database::profiles::find() resolves to the leaf fn').toBe(true);
  3584. });
  3585. });
  3586. describe('Objective-C messages, class receivers, and #import', () => {
  3587. let tempDir: string;
  3588. let cg: CodeGraph;
  3589. beforeEach(() => {
  3590. tempDir = createTempDir();
  3591. });
  3592. afterEach(() => {
  3593. if (cg) cg.close();
  3594. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3595. });
  3596. it('resolves single-arg selectors, class-message receivers, and #import headers', async () => {
  3597. fs.writeFileSync(
  3598. path.join(tempDir, 'SDImageCache.h'),
  3599. `#import <Foundation/Foundation.h>
  3600. @interface SDImageCache : NSObject
  3601. + (instancetype)sharedCache;
  3602. + (void)storeImage:(NSString *)key;
  3603. @end
  3604. `
  3605. );
  3606. fs.writeFileSync(
  3607. path.join(tempDir, 'SDImageCache.m'),
  3608. `#import "SDImageCache.h"
  3609. @implementation SDImageCache
  3610. + (instancetype)sharedCache { return nil; }
  3611. + (void)storeImage:(NSString *)key { }
  3612. @end
  3613. `
  3614. );
  3615. fs.writeFileSync(
  3616. path.join(tempDir, 'SDManager.m'),
  3617. `#import "SDImageCache.h"
  3618. @interface SDManager : NSObject
  3619. @end
  3620. @implementation SDManager
  3621. - (void)run {
  3622. [SDImageCache sharedCache];
  3623. [SDImageCache storeImage:@"k"];
  3624. }
  3625. @end
  3626. `
  3627. );
  3628. cg = CodeGraph.initSync(tempDir);
  3629. await cg.indexAll();
  3630. cg.resolveReferences();
  3631. // 1. The single-argument selector `[SDImageCache storeImage:@"k"]` resolves
  3632. // to the `storeImage:` method — named WITH its colon both at the call site
  3633. // and the definition (before the fix the call site dropped the colon).
  3634. const storeImage = cg.getNodesByKind('method').find((n) => n.name === 'storeImage:');
  3635. expect(storeImage, 'storeImage: method').toBeDefined();
  3636. const storeCallers = [...cg.getImpactRadius(storeImage!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3637. expect(storeCallers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3638. // 2. The class-message receiver `[SDImageCache sharedCache]` references the
  3639. // SDImageCache class (whose @interface lives in the header).
  3640. const cache = cg.getNodesByKind('class').find((n) => n.name === 'SDImageCache');
  3641. expect(cache, 'SDImageCache class').toBeDefined();
  3642. const classDeps = [...cg.getImpactRadius(cache!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3643. expect(classDeps.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3644. // 3. `#import "SDImageCache.h"` resolves to the header FILE — editing it
  3645. // surfaces both importers.
  3646. const header = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('SDImageCache.h'));
  3647. expect(header, 'SDImageCache.h indexed').toBeDefined();
  3648. const importers = [...cg.getImpactRadius(header!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3649. expect(importers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3650. });
  3651. });
  3652. describe('Full Indexing', () => {
  3653. let tempDir: string;
  3654. beforeEach(() => {
  3655. tempDir = createTempDir();
  3656. });
  3657. afterEach(() => {
  3658. cleanupTempDir(tempDir);
  3659. });
  3660. it('should index a TypeScript file', async () => {
  3661. // Create test file
  3662. const srcDir = path.join(tempDir, 'src');
  3663. fs.mkdirSync(srcDir);
  3664. fs.writeFileSync(
  3665. path.join(srcDir, 'utils.ts'),
  3666. `
  3667. export function add(a: number, b: number): number {
  3668. return a + b;
  3669. }
  3670. export function multiply(a: number, b: number): number {
  3671. return a * b;
  3672. }
  3673. `
  3674. );
  3675. // Initialize and index
  3676. const cg = CodeGraph.initSync(tempDir);
  3677. const result = await cg.indexAll();
  3678. expect(result.success).toBe(true);
  3679. expect(result.filesIndexed).toBe(1);
  3680. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  3681. // Check nodes were stored
  3682. const nodes = cg.getNodesInFile('src/utils.ts');
  3683. expect(nodes.length).toBeGreaterThanOrEqual(2);
  3684. const addFunc = nodes.find((n) => n.name === 'add');
  3685. expect(addFunc).toBeDefined();
  3686. expect(addFunc?.kind).toBe('function');
  3687. cg.close();
  3688. });
  3689. it('should index multiple files', async () => {
  3690. // Create test files
  3691. const srcDir = path.join(tempDir, 'src');
  3692. fs.mkdirSync(srcDir);
  3693. fs.writeFileSync(
  3694. path.join(srcDir, 'math.ts'),
  3695. `export function add(a: number, b: number) { return a + b; }`
  3696. );
  3697. fs.writeFileSync(
  3698. path.join(srcDir, 'string.ts'),
  3699. `export function capitalize(s: string) { return s.toUpperCase(); }`
  3700. );
  3701. // Initialize and index
  3702. const cg = CodeGraph.initSync(tempDir);
  3703. const result = await cg.indexAll();
  3704. expect(result.success).toBe(true);
  3705. expect(result.filesIndexed).toBe(2);
  3706. const files = cg.getFiles();
  3707. expect(files.length).toBe(2);
  3708. cg.close();
  3709. });
  3710. it('should track file hashes for incremental updates', async () => {
  3711. // Create initial file
  3712. const srcDir = path.join(tempDir, 'src');
  3713. fs.mkdirSync(srcDir);
  3714. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  3715. // Initialize and index
  3716. const cg = CodeGraph.initSync(tempDir);
  3717. await cg.indexAll();
  3718. // Check file is tracked
  3719. const file = cg.getFile('src/main.ts');
  3720. expect(file).toBeDefined();
  3721. expect(file?.contentHash).toBeDefined();
  3722. // Modify file
  3723. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  3724. // Check for changes
  3725. const changes = cg.getChangedFiles();
  3726. expect(changes.modified).toContain('src/main.ts');
  3727. cg.close();
  3728. });
  3729. it('should sync and detect changes', async () => {
  3730. // Create initial file
  3731. const srcDir = path.join(tempDir, 'src');
  3732. fs.mkdirSync(srcDir);
  3733. fs.writeFileSync(
  3734. path.join(srcDir, 'main.ts'),
  3735. `export function original() { return 1; }`
  3736. );
  3737. // Initialize and index
  3738. const cg = CodeGraph.initSync(tempDir);
  3739. await cg.indexAll();
  3740. const initialNodes = cg.getNodesInFile('src/main.ts');
  3741. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  3742. // Modify file
  3743. fs.writeFileSync(
  3744. path.join(srcDir, 'main.ts'),
  3745. `export function updated() { return 2; }`
  3746. );
  3747. // Sync
  3748. const syncResult = await cg.sync();
  3749. expect(syncResult.filesModified).toBe(1);
  3750. // Check nodes were updated
  3751. const updatedNodes = cg.getNodesInFile('src/main.ts');
  3752. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  3753. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  3754. cg.close();
  3755. });
  3756. it('should count file-level tracked YAML files as indexed', async () => {
  3757. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3758. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  3759. const cg = CodeGraph.initSync(tempDir);
  3760. const result = await cg.indexAll();
  3761. expect(result.success).toBe(true);
  3762. expect(result.filesIndexed).toBe(2);
  3763. expect(result.filesSkipped).toBe(0);
  3764. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  3765. cg.close();
  3766. });
  3767. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  3768. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3769. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  3770. const cg = CodeGraph.initSync(tempDir);
  3771. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  3772. expect(result.success).toBe(true);
  3773. expect(result.filesIndexed).toBe(2);
  3774. expect(result.filesSkipped).toBe(0);
  3775. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  3776. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  3777. cg.close();
  3778. });
  3779. it('should count file-level tracked .properties files as indexed', async () => {
  3780. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  3781. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  3782. const cg = CodeGraph.initSync(tempDir);
  3783. const result = await cg.indexAll();
  3784. expect(result.success).toBe(true);
  3785. expect(result.filesIndexed).toBe(2);
  3786. expect(result.filesSkipped).toBe(0);
  3787. cg.close();
  3788. });
  3789. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  3790. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3791. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  3792. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  3793. const cg = CodeGraph.initSync(tempDir);
  3794. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  3795. expect(result.success).toBe(true);
  3796. expect(result.filesIndexed).toBe(3);
  3797. expect(result.filesSkipped).toBe(0);
  3798. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  3799. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  3800. cg.close();
  3801. });
  3802. });
  3803. describe('Path Normalization', () => {
  3804. it('should convert backslashes to forward slashes', () => {
  3805. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  3806. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  3807. });
  3808. it('should leave forward-slash paths unchanged', () => {
  3809. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  3810. });
  3811. it('should handle empty string', () => {
  3812. expect(normalizePath('')).toBe('');
  3813. });
  3814. });
  3815. describe('Directory Exclusion', () => {
  3816. let tempDir: string;
  3817. beforeEach(() => {
  3818. tempDir = createTempDir();
  3819. });
  3820. afterEach(() => {
  3821. cleanupTempDir(tempDir);
  3822. });
  3823. it('should exclude directories listed in .gitignore', () => {
  3824. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  3825. const srcDir = path.join(tempDir, 'src');
  3826. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  3827. fs.mkdirSync(srcDir, { recursive: true });
  3828. fs.mkdirSync(nmDir, { recursive: true });
  3829. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3830. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  3831. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  3832. const files = scanDirectory(tempDir);
  3833. expect(files).toContain('src/index.ts');
  3834. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  3835. });
  3836. it('should exclude nested node_modules via a root .gitignore', () => {
  3837. // A trailing-slash pattern with no leading slash matches at any depth.
  3838. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  3839. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  3840. fs.mkdirSync(srcDir, { recursive: true });
  3841. fs.mkdirSync(nmDir, { recursive: true });
  3842. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3843. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  3844. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  3845. const files = scanDirectory(tempDir);
  3846. expect(files).toContain('packages/app/src/index.ts');
  3847. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  3848. });
  3849. it('should apply a nested .gitignore only to its own subtree', () => {
  3850. const appSrc = path.join(tempDir, 'app', 'src');
  3851. fs.mkdirSync(appSrc, { recursive: true });
  3852. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  3853. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  3854. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  3855. // A sibling with the same name outside app/ must NOT be ignored.
  3856. const otherDir = path.join(tempDir, 'other', 'src');
  3857. fs.mkdirSync(otherDir, { recursive: true });
  3858. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  3859. const files = scanDirectory(tempDir);
  3860. expect(files).toContain('app/src/keep.ts');
  3861. expect(files).not.toContain('app/src/skip.ts');
  3862. expect(files).toContain('other/src/skip.ts');
  3863. });
  3864. it('should always skip .git directories', () => {
  3865. const srcDir = path.join(tempDir, 'src');
  3866. const gitDir = path.join(tempDir, '.git', 'objects');
  3867. fs.mkdirSync(srcDir, { recursive: true });
  3868. fs.mkdirSync(gitDir, { recursive: true });
  3869. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3870. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  3871. const files = scanDirectory(tempDir);
  3872. expect(files).toContain('src/index.ts');
  3873. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  3874. });
  3875. it('should return forward-slash paths on all platforms', () => {
  3876. const srcDir = path.join(tempDir, 'src', 'components');
  3877. fs.mkdirSync(srcDir, { recursive: true });
  3878. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  3879. const files = scanDirectory(tempDir);
  3880. expect(files.length).toBe(1);
  3881. expect(files[0]).toBe('src/components/Button.tsx');
  3882. expect(files[0]).not.toContain('\\');
  3883. });
  3884. });
  3885. describe('Git Submodules', () => {
  3886. let tempDir: string;
  3887. beforeEach(() => {
  3888. tempDir = createTempDir();
  3889. });
  3890. afterEach(() => {
  3891. cleanupTempDir(tempDir);
  3892. });
  3893. it('should index files inside git submodules (issue #147)', async () => {
  3894. const { execFileSync } = await import('child_process');
  3895. const git = (cwd: string, ...args: string[]) =>
  3896. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3897. // Build a separate "library" repo to use as a submodule source.
  3898. const libDir = path.join(tempDir, '_lib');
  3899. fs.mkdirSync(libDir, { recursive: true });
  3900. git(libDir, 'init', '-q');
  3901. git(libDir, 'config', 'user.email', 'test@test.com');
  3902. git(libDir, 'config', 'user.name', 'Test');
  3903. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  3904. git(libDir, 'add', '-A');
  3905. git(libDir, 'commit', '-q', '-m', 'lib init');
  3906. // Build the main repo and add the lib repo as a submodule.
  3907. const mainDir = path.join(tempDir, 'main');
  3908. fs.mkdirSync(mainDir, { recursive: true });
  3909. git(mainDir, 'init', '-q');
  3910. git(mainDir, 'config', 'user.email', 'test@test.com');
  3911. git(mainDir, 'config', 'user.name', 'Test');
  3912. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  3913. git(mainDir, 'add', '-A');
  3914. git(mainDir, 'commit', '-q', '-m', 'app init');
  3915. // protocol.file.allow=always is required to add a local-path submodule on
  3916. // recent git versions (CVE-2022-39253 mitigation).
  3917. execFileSync(
  3918. 'git',
  3919. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  3920. { cwd: mainDir, stdio: 'pipe' }
  3921. );
  3922. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  3923. const files = scanDirectory(mainDir);
  3924. expect(files).toContain('app.ts');
  3925. expect(files).toContain('libs/lib/lib.ts');
  3926. });
  3927. });
  3928. describe('Nested non-submodule git repos', () => {
  3929. let tempDir: string;
  3930. beforeEach(() => {
  3931. tempDir = createTempDir();
  3932. });
  3933. afterEach(() => {
  3934. cleanupTempDir(tempDir);
  3935. });
  3936. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  3937. const { execFileSync } = await import('child_process');
  3938. const git = (cwd: string, ...args: string[]) =>
  3939. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3940. // Top-level workspace is itself a git repo, holding no source directly —
  3941. // the CMake "super-repo" layout from the issue.
  3942. const root = path.join(tempDir, 'root');
  3943. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  3944. git(root, 'init', '-q');
  3945. git(root, 'config', 'user.email', 'test@test.com');
  3946. git(root, 'config', 'user.name', 'Test');
  3947. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  3948. // Two independent clones living inside the workspace (NOT submodules):
  3949. // one with committed source, one with only untracked source.
  3950. const sub1 = path.join(root, 'sub_repo1', 'src');
  3951. fs.mkdirSync(sub1, { recursive: true });
  3952. git(path.join(root, 'sub_repo1'), 'init', '-q');
  3953. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  3954. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  3955. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  3956. git(path.join(root, 'sub_repo1'), 'add', '-A');
  3957. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  3958. const sub2 = path.join(root, 'sub_repo2', 'src');
  3959. fs.mkdirSync(sub2, { recursive: true });
  3960. git(path.join(root, 'sub_repo2'), 'init', '-q');
  3961. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  3962. const files = scanDirectory(root);
  3963. // Both committed and untracked source from the nested repos must be found.
  3964. expect(files).toContain('sub_repo1/src/one.ts');
  3965. expect(files).toContain('sub_repo2/src/two.ts');
  3966. });
  3967. it('should respect each embedded repo\'s own .gitignore', async () => {
  3968. const { execFileSync } = await import('child_process');
  3969. const git = (cwd: string, ...args: string[]) =>
  3970. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3971. const root = path.join(tempDir, 'root');
  3972. fs.mkdirSync(root, { recursive: true });
  3973. git(root, 'init', '-q');
  3974. const sub = path.join(root, 'sub_repo', 'src');
  3975. fs.mkdirSync(sub, { recursive: true });
  3976. git(path.join(root, 'sub_repo'), 'init', '-q');
  3977. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  3978. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  3979. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  3980. const files = scanDirectory(root);
  3981. expect(files).toContain('sub_repo/src/real.ts');
  3982. expect(files).not.toContain('sub_repo/src/generated.ts');
  3983. });
  3984. });
  3985. // =============================================================================
  3986. // Scala
  3987. // =============================================================================
  3988. describe('Scala Extraction', () => {
  3989. describe('Language detection', () => {
  3990. it('should detect Scala files', () => {
  3991. expect(detectLanguage('Main.scala')).toBe('scala');
  3992. expect(detectLanguage('script.sc')).toBe('scala');
  3993. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  3994. });
  3995. it('should report Scala as supported', () => {
  3996. expect(isLanguageSupported('scala')).toBe(true);
  3997. expect(getSupportedLanguages()).toContain('scala');
  3998. });
  3999. });
  4000. describe('Class extraction', () => {
  4001. it('should extract class definitions', () => {
  4002. const code = `
  4003. class UserService(private val repo: UserRepository) {
  4004. def findUser(id: String): Option[String] = Some(id)
  4005. }
  4006. `;
  4007. const result = extractFromSource('UserService.scala', code);
  4008. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  4009. expect(cls).toBeDefined();
  4010. expect(cls?.language).toBe('scala');
  4011. });
  4012. it('should extract object definitions as class kind', () => {
  4013. const code = `
  4014. object DatabaseConfig {
  4015. val url = "jdbc:postgresql://localhost/mydb"
  4016. }
  4017. `;
  4018. const result = extractFromSource('Config.scala', code);
  4019. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  4020. expect(obj).toBeDefined();
  4021. });
  4022. it('should extract trait definitions as trait kind', () => {
  4023. const code = `
  4024. trait Repository[A] {
  4025. def findById(id: String): Option[A]
  4026. def save(entity: A): Unit
  4027. }
  4028. `;
  4029. const result = extractFromSource('Repository.scala', code);
  4030. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  4031. expect(trait_).toBeDefined();
  4032. });
  4033. });
  4034. describe('Method and function extraction', () => {
  4035. it('should extract method definitions inside a class', () => {
  4036. const code = `
  4037. class Calculator {
  4038. def add(a: Int, b: Int): Int = a + b
  4039. def divide(a: Double, b: Double): Double = a / b
  4040. }
  4041. `;
  4042. const result = extractFromSource('Calculator.scala', code);
  4043. const methods = result.nodes.filter((n) => n.kind === 'method');
  4044. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  4045. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  4046. });
  4047. it('should extract method signatures', () => {
  4048. const code = `
  4049. class Greeter {
  4050. def greet(name: String): String = s"Hello, \${name}!"
  4051. }
  4052. `;
  4053. const result = extractFromSource('Greeter.scala', code);
  4054. const method = result.nodes.find((n) => n.name === 'greet');
  4055. expect(method?.signature).toContain('name: String');
  4056. expect(method?.signature).toContain('String');
  4057. });
  4058. it('should extract top-level function definitions as functions', () => {
  4059. const code = `
  4060. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  4061. def greet(name: String): String = s"Hello, \${name}!"
  4062. `;
  4063. const result = extractFromSource('utils.scala', code);
  4064. const fns = result.nodes.filter((n) => n.kind === 'function');
  4065. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  4066. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  4067. });
  4068. });
  4069. describe('Val and var extraction', () => {
  4070. it('should extract val inside a class as field', () => {
  4071. const code = `
  4072. class Config {
  4073. val timeout: Int = 30
  4074. val host: String = "localhost"
  4075. }
  4076. `;
  4077. const result = extractFromSource('Config.scala', code);
  4078. const fields = result.nodes.filter((n) => n.kind === 'field');
  4079. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  4080. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  4081. });
  4082. it('should extract var inside a class as field', () => {
  4083. const code = `
  4084. class Counter {
  4085. var count: Int = 0
  4086. }
  4087. `;
  4088. const result = extractFromSource('Counter.scala', code);
  4089. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  4090. expect(field).toBeDefined();
  4091. });
  4092. it('should extract top-level val as constant', () => {
  4093. const code = `
  4094. val MaxConnections: Int = 100
  4095. val DefaultTimeout = 30
  4096. `;
  4097. const result = extractFromSource('constants.scala', code);
  4098. const consts = result.nodes.filter((n) => n.kind === 'constant');
  4099. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  4100. });
  4101. it('should extract top-level var as variable', () => {
  4102. const code = `
  4103. var retries: Int = 3
  4104. `;
  4105. const result = extractFromSource('state.scala', code);
  4106. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  4107. expect(v).toBeDefined();
  4108. });
  4109. it('should include type in val/var signature', () => {
  4110. const code = `
  4111. class Service {
  4112. val timeout: Int = 30
  4113. }
  4114. `;
  4115. const result = extractFromSource('Service.scala', code);
  4116. const field = result.nodes.find((n) => n.name === 'timeout');
  4117. expect(field?.signature).toContain('timeout');
  4118. expect(field?.signature).toContain('Int');
  4119. });
  4120. });
  4121. describe('Enum extraction', () => {
  4122. it('should extract enum definitions', () => {
  4123. const code = `
  4124. enum Color:
  4125. case Red
  4126. case Green
  4127. case Blue
  4128. `;
  4129. const result = extractFromSource('Color.scala', code);
  4130. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  4131. expect(enumNode).toBeDefined();
  4132. });
  4133. it('should extract enum cases as enum_member', () => {
  4134. const code = `
  4135. enum Direction:
  4136. case North
  4137. case South
  4138. case East
  4139. case West
  4140. `;
  4141. const result = extractFromSource('Direction.scala', code);
  4142. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  4143. expect(members.find((m) => m.name === 'North')).toBeDefined();
  4144. expect(members.find((m) => m.name === 'South')).toBeDefined();
  4145. expect(members.length).toBeGreaterThanOrEqual(4);
  4146. });
  4147. });
  4148. describe('Type alias extraction', () => {
  4149. it('should extract type aliases', () => {
  4150. const code = `
  4151. type UserId = String
  4152. type UserMap = Map[String, String]
  4153. `;
  4154. const result = extractFromSource('types.scala', code);
  4155. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  4156. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  4157. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  4158. });
  4159. });
  4160. describe('Import extraction', () => {
  4161. it('should extract import declarations', () => {
  4162. const code = `
  4163. import scala.collection.mutable.ListBuffer
  4164. import scala.concurrent.Future
  4165. `;
  4166. const result = extractFromSource('imports.scala', code);
  4167. const imports = result.nodes.filter((n) => n.kind === 'import');
  4168. expect(imports.length).toBeGreaterThanOrEqual(2);
  4169. });
  4170. });
  4171. describe('Visibility modifiers', () => {
  4172. it('should extract private visibility', () => {
  4173. const code = `
  4174. class Service {
  4175. private val secret: String = "abc"
  4176. private def helper(): Unit = {}
  4177. }
  4178. `;
  4179. const result = extractFromSource('Service.scala', code);
  4180. const secretField = result.nodes.find((n) => n.name === 'secret');
  4181. expect(secretField?.visibility).toBe('private');
  4182. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  4183. expect(helperMethod?.visibility).toBe('private');
  4184. });
  4185. it('should extract protected visibility', () => {
  4186. const code = `
  4187. class Base {
  4188. protected def helperMethod(): Unit = {}
  4189. }
  4190. `;
  4191. const result = extractFromSource('Base.scala', code);
  4192. const method = result.nodes.find((n) => n.name === 'helperMethod');
  4193. expect(method?.visibility).toBe('protected');
  4194. });
  4195. it('should default to public visibility', () => {
  4196. const code = `
  4197. class Greeter {
  4198. def hello(): Unit = {}
  4199. }
  4200. `;
  4201. const result = extractFromSource('Greeter.scala', code);
  4202. const method = result.nodes.find((n) => n.name === 'hello');
  4203. expect(method?.visibility).toBe('public');
  4204. });
  4205. });
  4206. describe('Inheritance', () => {
  4207. it('should extract extends relationships', () => {
  4208. const code = `
  4209. class AdminUser extends User {
  4210. def adminAction(): Unit = {}
  4211. }
  4212. `;
  4213. const result = extractFromSource('AdminUser.scala', code);
  4214. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  4215. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  4216. });
  4217. });
  4218. describe('Call extraction', () => {
  4219. it('should extract function call expressions', () => {
  4220. const code = `
  4221. def processData(): Unit = {
  4222. val result = computeResult()
  4223. println(result)
  4224. }
  4225. `;
  4226. const result = extractFromSource('processor.scala', code);
  4227. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  4228. expect(calls.length).toBeGreaterThan(0);
  4229. });
  4230. });
  4231. });
  4232. describe('Vue Extraction', () => {
  4233. it('should detect Vue files', () => {
  4234. expect(detectLanguage('App.vue')).toBe('vue');
  4235. expect(detectLanguage('components/Button.vue')).toBe('vue');
  4236. expect(isLanguageSupported('vue')).toBe(true);
  4237. });
  4238. it('should extract component node from a Vue SFC', () => {
  4239. const code = `<template>
  4240. <div>{{ message }}</div>
  4241. </template>
  4242. <script>
  4243. export default {
  4244. data() {
  4245. return { message: 'Hello' };
  4246. }
  4247. }
  4248. </script>
  4249. `;
  4250. const result = extractFromSource('HelloWorld.vue', code);
  4251. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4252. expect(componentNode).toBeDefined();
  4253. expect(componentNode?.name).toBe('HelloWorld');
  4254. expect(componentNode?.language).toBe('vue');
  4255. expect(componentNode?.isExported).toBe(true);
  4256. });
  4257. it('should extract functions from <script> block', () => {
  4258. const code = `<template>
  4259. <button @click="handleClick">Click</button>
  4260. </template>
  4261. <script>
  4262. function handleClick() {
  4263. console.log('clicked');
  4264. }
  4265. const count = 0;
  4266. </script>
  4267. `;
  4268. const result = extractFromSource('Button.vue', code);
  4269. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4270. expect(componentNode).toBeDefined();
  4271. expect(componentNode?.name).toBe('Button');
  4272. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  4273. expect(funcNode).toBeDefined();
  4274. expect(funcNode?.language).toBe('vue');
  4275. });
  4276. it('should extract from <script setup lang="ts"> block', () => {
  4277. const code = `<template>
  4278. <div>{{ count }}</div>
  4279. </template>
  4280. <script setup lang="ts">
  4281. import { ref } from 'vue';
  4282. const count = ref(0);
  4283. function increment(): void {
  4284. count.value++;
  4285. }
  4286. </script>
  4287. `;
  4288. const result = extractFromSource('Counter.vue', code);
  4289. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4290. expect(componentNode).toBeDefined();
  4291. expect(componentNode?.name).toBe('Counter');
  4292. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  4293. expect(funcNode).toBeDefined();
  4294. expect(funcNode?.language).toBe('vue');
  4295. // All nodes should be marked as vue language
  4296. for (const node of result.nodes) {
  4297. expect(node.language).toBe('vue');
  4298. }
  4299. });
  4300. it('should extract calls from top-level <script setup> initializers', () => {
  4301. const code = `<template>
  4302. <div>{{ token }}</div>
  4303. </template>
  4304. <script setup lang="ts">
  4305. import { getTokenMp } from './api/upload';
  4306. const token = getTokenMp();
  4307. </script>
  4308. `;
  4309. const result = extractFromSource('Issue425Setup.vue', code);
  4310. const call = result.unresolvedReferences.find(
  4311. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  4312. );
  4313. expect(call).toBeDefined();
  4314. });
  4315. it('should extract calls from Vue Options API object methods', () => {
  4316. const code = `<template>
  4317. <button @click="save">Save</button>
  4318. </template>
  4319. <script>
  4320. import { getTokenMp } from './api/upload';
  4321. export default {
  4322. methods: {
  4323. save() {
  4324. return getTokenMp();
  4325. }
  4326. },
  4327. setup() {
  4328. return getTokenMp();
  4329. }
  4330. }
  4331. </script>
  4332. `;
  4333. const result = extractFromSource('Issue425Options.vue', code);
  4334. const calls = result.unresolvedReferences.filter(
  4335. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  4336. );
  4337. expect(calls).toHaveLength(2);
  4338. });
  4339. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  4340. const code = `<template>
  4341. <div class="wrap">
  4342. <UserCard :user="u" />
  4343. <my-button>Click</my-button>
  4344. <Transition><span>x</span></Transition>
  4345. </div>
  4346. </template>
  4347. <script setup lang="ts">
  4348. import UserCard from './UserCard.vue';
  4349. import MyButton from './MyButton.vue';
  4350. </script>
  4351. `;
  4352. const result = extractFromSource('Host.vue', code);
  4353. const refs = result.unresolvedReferences
  4354. .filter((r) => r.referenceKind === 'references')
  4355. .map((r) => r.referenceName);
  4356. expect(refs).toContain('UserCard'); // PascalCase tag
  4357. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  4358. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  4359. expect(refs).not.toContain('Div'); // native HTML element skipped
  4360. expect(refs).not.toContain('Span');
  4361. });
  4362. it('should extract from both <script> and <script setup> blocks', () => {
  4363. const code = `<template>
  4364. <div>{{ msg }}</div>
  4365. </template>
  4366. <script>
  4367. export default {
  4368. name: 'DualScript'
  4369. }
  4370. </script>
  4371. <script setup>
  4372. const msg = 'hello';
  4373. function greet() {
  4374. return msg;
  4375. }
  4376. </script>
  4377. `;
  4378. const result = extractFromSource('DualScript.vue', code);
  4379. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4380. expect(componentNode).toBeDefined();
  4381. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  4382. expect(greetFunc).toBeDefined();
  4383. });
  4384. it('should create component node for template-only Vue file', () => {
  4385. const code = `<template>
  4386. <div>Static content</div>
  4387. </template>
  4388. `;
  4389. const result = extractFromSource('Static.vue', code);
  4390. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4391. expect(componentNode).toBeDefined();
  4392. expect(componentNode?.name).toBe('Static');
  4393. expect(componentNode?.language).toBe('vue');
  4394. // Only the component node should exist (no script nodes)
  4395. expect(result.nodes.length).toBe(1);
  4396. });
  4397. it('should create containment edges from component to script nodes', () => {
  4398. const code = `<template>
  4399. <div>{{ value }}</div>
  4400. </template>
  4401. <script setup lang="ts">
  4402. const value = 42;
  4403. </script>
  4404. `;
  4405. const result = extractFromSource('Contained.vue', code);
  4406. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4407. expect(componentNode).toBeDefined();
  4408. // Should have containment edges from component to child nodes
  4409. const containEdges = result.edges.filter(
  4410. (e) => e.source === componentNode!.id && e.kind === 'contains'
  4411. );
  4412. expect(containEdges.length).toBeGreaterThan(0);
  4413. });
  4414. });
  4415. describe('Instantiates + Decorates edge extraction', () => {
  4416. it('emits an instantiates ref for `new Foo()`', () => {
  4417. const code = `
  4418. class Foo {}
  4419. function bootstrap() { return new Foo(); }
  4420. `;
  4421. const result = extractFromSource('app.ts', code);
  4422. const ref = result.unresolvedReferences.find(
  4423. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  4424. );
  4425. expect(ref).toBeDefined();
  4426. });
  4427. it('strips type-argument suffix from generic constructors', () => {
  4428. const code = `
  4429. class Container<T> { constructor(_: T) {} }
  4430. function go() { return new Container<string>('x'); }
  4431. `;
  4432. const result = extractFromSource('app.ts', code);
  4433. const ref = result.unresolvedReferences.find(
  4434. (r) => r.referenceKind === 'instantiates'
  4435. );
  4436. expect(ref).toBeDefined();
  4437. // Container<string> must be normalised to "Container" — otherwise
  4438. // resolution can never match the class node.
  4439. expect(ref!.referenceName).toBe('Container');
  4440. });
  4441. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  4442. const code = `
  4443. const ns = { Foo: class {} };
  4444. function go() { return new ns.Foo(); }
  4445. `;
  4446. const result = extractFromSource('app.ts', code);
  4447. const ref = result.unresolvedReferences.find(
  4448. (r) => r.referenceKind === 'instantiates'
  4449. );
  4450. // We can't always resolve which Foo, but the name should be the
  4451. // simple identifier so name-matching has a chance.
  4452. expect(ref?.referenceName).toBe('Foo');
  4453. });
  4454. it('emits a decorates ref for `@Foo class X {}`', () => {
  4455. const code = `
  4456. function Foo(_arg: string) { return (cls: any) => cls; }
  4457. @Foo('x')
  4458. class X {}
  4459. `;
  4460. const result = extractFromSource('app.ts', code);
  4461. const decorClass = result.unresolvedReferences.find(
  4462. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  4463. );
  4464. expect(decorClass).toBeDefined();
  4465. });
  4466. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  4467. // Regression: the sibling-walk must stop at the first non-
  4468. // decorator separator. `@A class Foo {} @B class Bar {}` must
  4469. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  4470. // `decorates(Bar, A)`.
  4471. const code = `
  4472. function A(cls: any) { return cls; }
  4473. function B(cls: any) { return cls; }
  4474. @A
  4475. class Foo {}
  4476. @B
  4477. class Bar {}
  4478. `;
  4479. const result = extractFromSource('app.ts', code);
  4480. const decoratesEdges = result.unresolvedReferences.filter(
  4481. (r) => r.referenceKind === 'decorates'
  4482. );
  4483. // Exactly one decorates ref per decorated class, no cross-attribution.
  4484. const fromBar = decoratesEdges.filter((r) =>
  4485. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  4486. );
  4487. expect(fromBar.length).toBe(1);
  4488. expect(fromBar[0]!.referenceName).toBe('B');
  4489. });
  4490. it('emits a decorates ref for `@Foo method() {}`', () => {
  4491. const code = `
  4492. function Get(p: string) { return (t: any, k: string) => t; }
  4493. class Svc {
  4494. @Get('/x') method() { return 1; }
  4495. }
  4496. `;
  4497. const result = extractFromSource('app.ts', code);
  4498. const decorMethod = result.unresolvedReferences.find(
  4499. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  4500. );
  4501. expect(decorMethod).toBeDefined();
  4502. // The decorated symbol must be `method`, not the constructor or class.
  4503. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  4504. expect(decoratedNode?.name).toBe('method');
  4505. });
  4506. });
  4507. // =============================================================================
  4508. // Lua
  4509. // =============================================================================
  4510. describe('Lua Extraction', () => {
  4511. describe('Language detection', () => {
  4512. it('should detect Lua files', () => {
  4513. expect(detectLanguage('init.lua')).toBe('lua');
  4514. expect(detectLanguage('src/util.lua')).toBe('lua');
  4515. });
  4516. it('should report Lua as supported', () => {
  4517. expect(isLanguageSupported('lua')).toBe(true);
  4518. expect(getSupportedLanguages()).toContain('lua');
  4519. });
  4520. });
  4521. describe('Function extraction', () => {
  4522. it('should extract global and local functions', () => {
  4523. const code = `
  4524. function configure(opts) return opts end
  4525. local function helper(x) return x * 2 end
  4526. `;
  4527. const result = extractFromSource('init.lua', code);
  4528. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  4529. expect(funcs).toContain('configure');
  4530. expect(funcs).toContain('helper');
  4531. const configure = result.nodes.find((n) => n.name === 'configure');
  4532. expect(configure?.language).toBe('lua');
  4533. expect(configure?.signature).toBe('(opts)');
  4534. });
  4535. it('should split table/method functions into a receiver and method name', () => {
  4536. const code = `
  4537. function M.connect(host, port) return host end
  4538. function M:send(data) return self end
  4539. `;
  4540. const result = extractFromSource('init.lua', code);
  4541. const methods = result.nodes.filter((n) => n.kind === 'method');
  4542. const connect = methods.find((m) => m.name === 'connect');
  4543. expect(connect?.qualifiedName).toBe('M::connect');
  4544. const send = methods.find((m) => m.name === 'send');
  4545. expect(send?.qualifiedName).toBe('M::send');
  4546. });
  4547. });
  4548. describe('Variable extraction', () => {
  4549. it('should extract local variable declarations', () => {
  4550. const code = `
  4551. local M = {}
  4552. local count = 0
  4553. `;
  4554. const result = extractFromSource('mod.lua', code);
  4555. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  4556. expect(vars).toContain('M');
  4557. expect(vars).toContain('count');
  4558. });
  4559. });
  4560. describe('Import extraction (require)', () => {
  4561. it('should extract require() in local declarations and bare calls', () => {
  4562. const code = `
  4563. local socket = require("socket")
  4564. local http = require "resty.http"
  4565. require("side.effect")
  4566. `;
  4567. const result = extractFromSource('net.lua', code);
  4568. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4569. expect(imports).toContain('socket');
  4570. expect(imports).toContain('resty.http');
  4571. expect(imports).toContain('side.effect');
  4572. const ref = result.unresolvedReferences.find(
  4573. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  4574. );
  4575. expect(ref).toBeDefined();
  4576. });
  4577. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  4578. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  4579. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  4580. // by extracting several sources in sequence and asserting the LAST still works.
  4581. it('should keep extracting require across many sequential parses', () => {
  4582. let last;
  4583. for (let i = 0; i < 8; i++) {
  4584. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  4585. }
  4586. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4587. expect(imports).toContain('module.7');
  4588. });
  4589. });
  4590. describe('Call extraction', () => {
  4591. it('should record intra-file calls as resolvable references', () => {
  4592. const code = `
  4593. local function helper(x) return x end
  4594. local function run(y) return helper(y) end
  4595. `;
  4596. const result = extractFromSource('calls.lua', code);
  4597. const call = result.unresolvedReferences.find(
  4598. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  4599. );
  4600. expect(call).toBeDefined();
  4601. });
  4602. });
  4603. });
  4604. // =============================================================================
  4605. // Luau (typed superset of Lua — https://luau.org)
  4606. // =============================================================================
  4607. describe('Luau Extraction', () => {
  4608. describe('Language detection', () => {
  4609. it('should detect Luau files', () => {
  4610. expect(detectLanguage('init.luau')).toBe('luau');
  4611. expect(detectLanguage('src/Client.luau')).toBe('luau');
  4612. });
  4613. it('should report Luau as supported', () => {
  4614. expect(isLanguageSupported('luau')).toBe(true);
  4615. expect(getSupportedLanguages()).toContain('luau');
  4616. });
  4617. });
  4618. describe('Type aliases', () => {
  4619. it('should extract `type` and `export type` definitions', () => {
  4620. const code = `
  4621. export type Vector = { x: number, y: number }
  4622. type Handler = (msg: string) -> boolean
  4623. `;
  4624. const result = extractFromSource('types.luau', code);
  4625. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  4626. const vector = aliases.find((a) => a.name === 'Vector');
  4627. expect(vector).toBeDefined();
  4628. expect(vector?.isExported).toBe(true);
  4629. const handler = aliases.find((a) => a.name === 'Handler');
  4630. expect(handler).toBeDefined();
  4631. expect(handler?.isExported).toBe(false);
  4632. });
  4633. });
  4634. describe('Typed functions and methods', () => {
  4635. it('should capture typed signatures and split methods by receiver', () => {
  4636. const code = `
  4637. function configure(opts: { debug: boolean }): boolean
  4638. return opts.debug
  4639. end
  4640. function Client:fetch(path: string): Response
  4641. return path
  4642. end
  4643. `;
  4644. const result = extractFromSource('client.luau', code);
  4645. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  4646. expect(configure?.language).toBe('luau');
  4647. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  4648. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  4649. expect(fetch?.qualifiedName).toBe('Client::fetch');
  4650. });
  4651. });
  4652. describe('Imports and variables', () => {
  4653. it('should extract string and Roblox instance-path require imports', () => {
  4654. const code = `
  4655. local http = require("http")
  4656. local Signal = require(script.Parent.Signal)
  4657. local count = 0
  4658. `;
  4659. const result = extractFromSource('mod.luau', code);
  4660. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4661. expect(imports).toContain('http'); // string require
  4662. expect(imports).toContain('Signal'); // Roblox instance-path require
  4663. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  4664. expect(vars).toContain('count');
  4665. });
  4666. });
  4667. });
  4668. // =============================================================================
  4669. // Objective-C
  4670. // =============================================================================
  4671. describe('Objective-C Extraction', () => {
  4672. const sample = `
  4673. #import <Foundation/Foundation.h>
  4674. #import "MyClass.h"
  4675. @interface MyClass : NSObject <NSCopying>
  4676. @property (nonatomic, copy) NSString *name;
  4677. - (void)greet;
  4678. - (void)doThing:(id)x with:(id)y;
  4679. + (instancetype)shared;
  4680. @end
  4681. @implementation MyClass
  4682. - (void)greet {
  4683. NSLog(@"Hello");
  4684. [self doWork];
  4685. }
  4686. - (void)doThing:(id)x with:(id)y {
  4687. [self notify:x];
  4688. }
  4689. + (instancetype)shared {
  4690. return [[MyClass alloc] init];
  4691. }
  4692. @end
  4693. void helperFunction(int count) {
  4694. MyClass *obj = [MyClass shared];
  4695. [obj greet];
  4696. }
  4697. `;
  4698. it('should extract classes, methods, functions, and imports', () => {
  4699. const result = extractFromSource('App.m', sample);
  4700. const classes = result.nodes.filter((n) => n.kind === 'class');
  4701. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  4702. const methods = result.nodes.filter((n) => n.kind === 'method');
  4703. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  4704. const shared = methods.find((m) => m.name === 'shared');
  4705. expect(shared?.isStatic).toBe(true);
  4706. const properties = result.nodes.filter((n) => n.kind === 'property');
  4707. expect(properties.some((p) => p.name === 'name')).toBe(true);
  4708. const functions = result.nodes.filter((n) => n.kind === 'function');
  4709. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  4710. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4711. expect(imports).toContain('Foundation/Foundation.h');
  4712. expect(imports).toContain('MyClass.h');
  4713. });
  4714. it('should record inheritance and protocol conformance', () => {
  4715. const result = extractFromSource('App.m', sample);
  4716. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  4717. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  4718. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  4719. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  4720. });
  4721. it('should record message sends and C calls', () => {
  4722. const result = extractFromSource('App.m', sample);
  4723. const calls = result.unresolvedReferences
  4724. .filter((r) => r.referenceKind === 'calls')
  4725. .map((r) => r.referenceName);
  4726. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  4727. });
  4728. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  4729. // Regression for the gap discovered post-#165: message_expression's
  4730. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  4731. // so calls never resolved to multi-part method definitions like
  4732. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  4733. // must match the method-definition name with full keywords + trailing colons.
  4734. const code = `
  4735. @implementation Caller
  4736. - (void)demo {
  4737. NSMutableDictionary *d = [NSMutableDictionary new];
  4738. [d setObject:@"v" forKey:@"k"];
  4739. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  4740. [self touchesBegan:nil withEvent:nil];
  4741. }
  4742. @end
  4743. `;
  4744. const result = extractFromSource('Caller.m', code);
  4745. const calls = result.unresolvedReferences
  4746. .filter((r) => r.referenceKind === 'calls')
  4747. .map((r) => r.referenceName);
  4748. expect(calls).toEqual(
  4749. expect.arrayContaining([
  4750. 'd.setObject:forKey:',
  4751. 'd.setObject:forKey:withRetry:',
  4752. 'touchesBegan:withEvent:',
  4753. ])
  4754. );
  4755. });
  4756. it('should not classify pure C headers with @end in comments as objc', () => {
  4757. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  4758. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  4759. });
  4760. it('should extract protocol declarations', () => {
  4761. const code = `
  4762. @protocol DataSource <NSObject>
  4763. - (NSInteger)numberOfItems;
  4764. @end
  4765. `;
  4766. const result = extractFromSource('DataSource.h', code);
  4767. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  4768. expect(protocol).toBeDefined();
  4769. });
  4770. it('should report Objective-C as supported', () => {
  4771. expect(isLanguageSupported('objc')).toBe(true);
  4772. expect(getSupportedLanguages()).toContain('objc');
  4773. });
  4774. });
  4775. describe('Regression: issue-specific extraction fixes', () => {
  4776. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  4777. const code = `
  4778. define(['dep'], function (dep) {
  4779. function innerHelper(x) { return x + 1; }
  4780. function compute(y) { return innerHelper(y); }
  4781. return { compute: compute };
  4782. });
  4783. `;
  4784. const result = extractFromSource('amd-module.js', code);
  4785. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  4786. expect(fns).toContain('innerHelper');
  4787. expect(fns).toContain('compute');
  4788. });
  4789. it('attaches Go methods on generic receivers to their type (#583)', () => {
  4790. const code = `
  4791. package main
  4792. type Stack[T any] struct { items []T }
  4793. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  4794. func (s Stack[T]) Len() int { return len(s.items) }
  4795. `;
  4796. const result = extractFromSource('stack.go', code);
  4797. const methods = result.nodes.filter((n) => n.kind === 'method');
  4798. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  4799. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  4800. });
  4801. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  4802. expect(isSourceFile('mod.mts')).toBe(true);
  4803. expect(isSourceFile('mod.cts')).toBe(true);
  4804. expect(isSourceFile('service.xsjs')).toBe(true);
  4805. expect(isSourceFile('lib.xsjslib')).toBe(true);
  4806. expect(detectLanguage('mod.mts')).toBe('typescript');
  4807. expect(detectLanguage('service.xsjs')).toBe('javascript');
  4808. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  4809. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  4810. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  4811. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  4812. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  4813. });
  4814. });
  4815. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  4816. // An import IS a dependency, but extraction only emits references for calls,
  4817. // instantiations, type annotations, and inheritance — so a symbol imported and
  4818. // then merely re-exported, placed in a registry array, passed as an argument,
  4819. // or used in JSX produced no cross-file edge, leaving the providing file with a
  4820. // false "0 dependents". These tests pin the import/re-export binding linking.
  4821. it('emits an imports reference per named, aliased, and default import binding', () => {
  4822. const code = `
  4823. import { widget, helper as h } from './foo';
  4824. import Thing from './thing';
  4825. import * as NS from './ns';
  4826. export const registry = [widget];
  4827. `;
  4828. const result = extractFromSource('bar.ts', code);
  4829. const names = result.unresolvedReferences
  4830. .filter((r) => r.referenceKind === 'imports')
  4831. .map((r) => r.referenceName);
  4832. expect(names).toContain('widget'); // named import → local name
  4833. expect(names).toContain('h'); // aliased import → local alias
  4834. expect(names).toContain('Thing'); // default import
  4835. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  4836. });
  4837. it('emits an imports reference per re-exported binding', () => {
  4838. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  4839. const names = result.unresolvedReferences
  4840. .filter((r) => r.referenceKind === 'imports')
  4841. .map((r) => r.referenceName);
  4842. // Re-export links the SOURCE-side name, not the local alias.
  4843. expect(names).toContain('alpha');
  4844. expect(names).toContain('beta');
  4845. });
  4846. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  4847. const dir = createTempDir();
  4848. try {
  4849. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4850. fs.writeFileSync(
  4851. path.join(dir, 'src', 'foo.ts'),
  4852. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  4853. );
  4854. // bar uses widget ONLY in an array and re-exports helper — neither is
  4855. // called/typed, so before import-linking bar had no edge to foo at all.
  4856. fs.writeFileSync(
  4857. path.join(dir, 'src', 'bar.ts'),
  4858. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  4859. );
  4860. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  4861. await cg.indexAll();
  4862. cg.resolveReferences();
  4863. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  4864. cg.destroy();
  4865. } finally {
  4866. cleanupTempDir(dir);
  4867. }
  4868. });
  4869. it('a namespace import touched only via a value-member read still links the module file', async () => {
  4870. const dir = createTempDir();
  4871. try {
  4872. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4873. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  4874. // `foo` is imported as a namespace and used ONLY via a value-member read
  4875. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  4876. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  4877. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  4878. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  4879. await cg.indexAll();
  4880. cg.resolveReferences();
  4881. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  4882. cg.destroy();
  4883. } finally {
  4884. cleanupTempDir(dir);
  4885. }
  4886. });
  4887. });
  4888. describe('Python import dependency linking (blast-radius recall)', () => {
  4889. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  4890. // name brought in with `from module import X` and then merely stored, used as
  4891. // a decorator/argument, or re-exported through an `__init__.py` produced no
  4892. // cross-file edge — the providing module showed a false "0 dependents".
  4893. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  4894. const code = [
  4895. 'from foo import helper, widget',
  4896. 'from foo import Thing as T',
  4897. 'from . import sibling',
  4898. 'from bar import *',
  4899. ].join('\n');
  4900. const names = extractFromSource('mod.py', code)
  4901. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  4902. .map((r) => r.referenceName);
  4903. expect(names).toContain('helper');
  4904. expect(names).toContain('widget'); // value import
  4905. expect(names).toContain('T'); // aliased import → local name
  4906. expect(names).toContain('sibling'); // `from . import <name>`
  4907. expect(names).not.toContain('*'); // wildcard import has no names
  4908. });
  4909. it('a Python value imported but never called still makes the importer a dependent', async () => {
  4910. const dir = createTempDir();
  4911. try {
  4912. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4913. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  4914. // bar imports widget+helper but only stores widget in a list — nothing is
  4915. // called, so before import-linking bar had no edge to foo.
  4916. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  4917. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4918. await cg.indexAll();
  4919. cg.resolveReferences();
  4920. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  4921. cg.destroy();
  4922. } finally {
  4923. cleanupTempDir(dir);
  4924. }
  4925. });
  4926. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  4927. const dir = createTempDir();
  4928. try {
  4929. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4930. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  4931. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  4932. // certs is an imported MODULE (a file), and certs.where() is a qualified
  4933. // call through it — the receiver isn't a symbol, so plain name-matching
  4934. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  4935. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  4936. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4937. await cg.indexAll();
  4938. cg.resolveReferences();
  4939. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  4940. cg.destroy();
  4941. } finally {
  4942. cleanupTempDir(dir);
  4943. }
  4944. });
  4945. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  4946. const dir = createTempDir();
  4947. try {
  4948. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4949. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  4950. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  4951. // member resolution can't find it — the module-import backstop must still
  4952. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  4953. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  4954. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  4955. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4956. await cg.indexAll();
  4957. cg.resolveReferences();
  4958. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  4959. cg.destroy();
  4960. } finally {
  4961. cleanupTempDir(dir);
  4962. }
  4963. });
  4964. });
  4965. describe('Go cross-package composite literals (blast-radius recall)', () => {
  4966. // Go function calls and type references across packages already resolved, but
  4967. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  4968. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  4969. // (gin's render/binding implementations) showed 0 dependents.
  4970. it('links a cross-package struct composite literal to the defining package', async () => {
  4971. const dir = createTempDir();
  4972. try {
  4973. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4974. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  4975. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  4976. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  4977. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4978. await cg.indexAll();
  4979. cg.resolveReferences();
  4980. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  4981. cg.destroy();
  4982. } finally {
  4983. cleanupTempDir(dir);
  4984. }
  4985. });
  4986. it('links a composite literal in a package-level var registry', async () => {
  4987. const dir = createTempDir();
  4988. try {
  4989. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4990. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  4991. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  4992. // The implementation is registered only in a top-level `var registry = {...}`
  4993. // map literal — the body walker doesn't cover top-level declarations, so this
  4994. // exercises the var-initializer walking added for Go.
  4995. 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`);
  4996. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4997. await cg.indexAll();
  4998. cg.resolveReferences();
  4999. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  5000. cg.destroy();
  5001. } finally {
  5002. cleanupTempDir(dir);
  5003. }
  5004. });
  5005. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  5006. const dir = createTempDir();
  5007. try {
  5008. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5009. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  5010. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  5011. // `(*Wrapped)` — without normalization it dropped on the floor.
  5012. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  5013. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5014. await cg.indexAll();
  5015. cg.resolveReferences();
  5016. expect(cg.getFileDependents('types.go')).toContain('use.go');
  5017. cg.destroy();
  5018. } finally {
  5019. cleanupTempDir(dir);
  5020. }
  5021. });
  5022. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  5023. const dir = createTempDir();
  5024. try {
  5025. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5026. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  5027. 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`);
  5028. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  5029. // reached ONLY through the interface (API.Marshal). Without implicit
  5030. // interface satisfaction + dispatch, json.go shows 0 dependents.
  5031. 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`);
  5032. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5033. await cg.indexAll();
  5034. cg.resolveReferences();
  5035. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  5036. cg.destroy();
  5037. } finally {
  5038. cleanupTempDir(dir);
  5039. }
  5040. });
  5041. });
  5042. describe('C# records (blast-radius recall)', () => {
  5043. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  5044. // but `record` / `record struct` declarations weren't extracted as types — so
  5045. // every reference, generic-type-argument, and `new` of a record dropped on the
  5046. // floor and the defining file showed 0 dependents. (#237)
  5047. it('extracts a record as a graph node (record class + record struct)', () => {
  5048. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  5049. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  5050. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  5051. });
  5052. it('resolves references / instantiations of a record across files', async () => {
  5053. const dir = createTempDir();
  5054. try {
  5055. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  5056. // Box is used as a generic type argument and instantiated — both require
  5057. // Box to be a node to resolve.
  5058. fs.writeFileSync(
  5059. path.join(dir, 'use.cs'),
  5060. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  5061. );
  5062. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  5063. await cg.indexAll();
  5064. cg.resolveReferences();
  5065. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  5066. cg.destroy();
  5067. } finally {
  5068. cleanupTempDir(dir);
  5069. }
  5070. });
  5071. });
  5072. describe('Rust cross-module recall', () => {
  5073. function rustProject(files: Record<string, string>): string {
  5074. const dir = createTempDir();
  5075. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  5076. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5077. for (const [rel, content] of Object.entries(files)) {
  5078. const full = path.join(dir, 'src', rel);
  5079. fs.mkdirSync(path.dirname(full), { recursive: true });
  5080. fs.writeFileSync(full, content);
  5081. }
  5082. return dir;
  5083. }
  5084. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  5085. const dir = rustProject({
  5086. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  5087. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  5088. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  5089. });
  5090. try {
  5091. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5092. await cg.indexAll();
  5093. cg.resolveReferences();
  5094. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  5095. cg.destroy();
  5096. } finally { cleanupTempDir(dir); }
  5097. });
  5098. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  5099. const dir = rustProject({
  5100. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  5101. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  5102. // Mine implements Render structurally; reached via &dyn Render dispatch.
  5103. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  5104. });
  5105. try {
  5106. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5107. await cg.indexAll();
  5108. cg.resolveReferences();
  5109. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  5110. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  5111. cg.destroy();
  5112. } finally { cleanupTempDir(dir); }
  5113. });
  5114. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  5115. const dir = rustProject({
  5116. 'lib.rs': 'pub mod api;\n',
  5117. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  5118. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  5119. });
  5120. try {
  5121. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5122. await cg.indexAll();
  5123. cg.resolveReferences();
  5124. // The re-export hub depends on the module it re-exports from.
  5125. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  5126. cg.destroy();
  5127. } finally { cleanupTempDir(dir); }
  5128. });
  5129. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  5130. const dir = rustProject({
  5131. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  5132. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  5133. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  5134. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  5135. // send this re-export to fast.rs specifically, not name-match either.
  5136. 'hub.rs': 'pub use crate::fast::read;\n',
  5137. });
  5138. try {
  5139. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5140. await cg.indexAll();
  5141. cg.resolveReferences();
  5142. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  5143. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  5144. cg.destroy();
  5145. } finally { cleanupTempDir(dir); }
  5146. });
  5147. });
  5148. describe('Java annotations (blast-radius recall)', () => {
  5149. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  5150. const dir = createTempDir();
  5151. try {
  5152. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  5153. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  5154. // live inside a `modifiers` node on the class/field/method) must extract.
  5155. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  5156. fs.writeFileSync(
  5157. path.join(dir, 'p', 'User.java'),
  5158. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  5159. );
  5160. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  5161. await cg.indexAll();
  5162. cg.resolveReferences();
  5163. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  5164. cg.destroy();
  5165. } finally { cleanupTempDir(dir); }
  5166. });
  5167. });
  5168. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  5169. it('links a @propertyWrapper usage to the wrapper type', async () => {
  5170. const dir = createTempDir();
  5171. try {
  5172. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  5173. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  5174. // `@Argument` is a Swift attribute on a stored property — it lives in the
  5175. // property's `modifiers` and Swift doesn't extract instance properties as
  5176. // their own nodes, so without the fix the wrapper type has no users.
  5177. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  5178. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  5179. await cg.indexAll();
  5180. cg.resolveReferences();
  5181. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  5182. cg.destroy();
  5183. } finally { cleanupTempDir(dir); }
  5184. });
  5185. });