extraction.test.ts 228 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458
  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. it('indexes primary-constructor classes, including keyed-DI attribute params (#237)', () => {
  859. // C# 12 primary constructors (`class Foo(IDep dep) { … }`) are parsed
  860. // natively by the vendored tree-sitter-c-sharp 0.23.x grammar. The worst
  861. // shape under the previous (older) grammar — an attribute-with-args on a
  862. // ctor param (`[FromKeyedServices("primary")] …`, the ASP.NET keyed-DI
  863. // pattern) — used to parse as an ERROR that swallowed the whole class, so
  864. // the class and all its methods vanished. They now index in every case.
  865. const code = `
  866. public class DataService(IMemoryCache cache)
  867. {
  868. public void Warm() { }
  869. }
  870. public class InstanceService(InstanceManager m, ProfileManager p)
  871. {
  872. public void DeployAndLaunchAsync() { }
  873. public void Deploy() { }
  874. }
  875. public partial class UpdateService(int x) : ILifetimeService
  876. {
  877. public void Run() { }
  878. }
  879. public class K1KeyedDi([FromKeyedServices("primary")] IMemoryCache cache)
  880. {
  881. public void Warm() { }
  882. }
  883. public record CatalogBrand(int Id, string Name);
  884. `;
  885. const result = extractFromSource('Services.cs', code);
  886. const classNames = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  887. expect(classNames).toContain('DataService');
  888. expect(classNames).toContain('InstanceService');
  889. expect(classNames).toContain('UpdateService'); // partial + base list
  890. expect(classNames).toContain('K1KeyedDi'); // attribute-arg ctor param — used to vanish entirely
  891. expect(classNames).toContain('CatalogBrand'); // record
  892. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  893. expect(methods).toContain('DeployAndLaunchAsync');
  894. expect(methods).toContain('Deploy');
  895. expect(methods).toContain('Run');
  896. });
  897. it('keeps a class indexable when a nested enum has #if-guarded members (#237)', () => {
  898. // A `#if` directive inside an enum member list (the multi-targeting pattern
  899. // in libraries like Newtonsoft.Json) makes the grammar emit an ERROR that,
  900. // for a nested enum, detaches the enclosing class's member list — dropping
  901. // most of the class's methods. A pre-parse pass blanks the directive lines
  902. // (keeping both branches), so the class and all its methods still index.
  903. const code = `
  904. public class Reader
  905. {
  906. private enum ReadType
  907. {
  908. #if HAVE_DATE_TIME_OFFSET
  909. ReadAsDateTimeOffset,
  910. #endif
  911. ReadAsDouble,
  912. ReadAsString,
  913. }
  914. public void Open() { }
  915. public void Close() { }
  916. public int ReadInt() { return 0; }
  917. }
  918. `;
  919. const result = extractFromSource('Reader.cs', code);
  920. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  921. // All three methods after the #if-bearing enum must survive.
  922. expect(methods).toContain('Open');
  923. expect(methods).toContain('Close');
  924. expect(methods).toContain('ReadInt');
  925. // Both enum branches are kept.
  926. const enumMembers = result.nodes.filter((n) => n.kind === 'enum_member').map((n) => n.name);
  927. expect(enumMembers).toContain('ReadAsDateTimeOffset');
  928. expect(enumMembers).toContain('ReadAsDouble');
  929. });
  930. });
  931. describe('PHP Extraction', () => {
  932. it('should extract class declarations', () => {
  933. const code = `<?php
  934. class UserController
  935. {
  936. private UserService $userService;
  937. public function __construct(UserService $userService)
  938. {
  939. $this->userService = $userService;
  940. }
  941. public function show(string $id): User
  942. {
  943. return $this->userService->find($id);
  944. }
  945. }
  946. `;
  947. const result = extractFromSource('UserController.php', code);
  948. const classNode = result.nodes.find((n) => n.kind === 'class');
  949. expect(classNode).toBeDefined();
  950. expect(classNode?.name).toBe('UserController');
  951. });
  952. it('should extract class inheritance (extends) and interface implementation', () => {
  953. const code = `<?php
  954. class ChildController extends BaseController implements Serializable, JsonSerializable
  955. {
  956. public function serialize(): string
  957. {
  958. return json_encode($this);
  959. }
  960. }
  961. `;
  962. const result = extractFromSource('ChildController.php', code);
  963. const classNode = result.nodes.find((n) => n.kind === 'class');
  964. expect(classNode).toBeDefined();
  965. expect(classNode?.name).toBe('ChildController');
  966. const extendsRef = result.unresolvedReferences.find(
  967. (r) => r.referenceKind === 'extends'
  968. );
  969. expect(extendsRef).toBeDefined();
  970. expect(extendsRef?.referenceName).toBe('BaseController');
  971. const implementsRefs = result.unresolvedReferences.filter(
  972. (r) => r.referenceKind === 'implements'
  973. );
  974. expect(implementsRefs.length).toBe(2);
  975. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  976. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  977. });
  978. });
  979. describe('Swift Extraction', () => {
  980. it('should extract class declarations', () => {
  981. const code = `
  982. public class NetworkManager {
  983. private let session: URLSession
  984. public init(session: URLSession = .shared) {
  985. self.session = session
  986. }
  987. public func fetchData(from url: URL) async throws -> Data {
  988. let (data, _) = try await session.data(from: url)
  989. return data
  990. }
  991. }
  992. `;
  993. const result = extractFromSource('NetworkManager.swift', code);
  994. const classNode = result.nodes.find((n) => n.kind === 'class');
  995. expect(classNode).toBeDefined();
  996. expect(classNode?.name).toBe('NetworkManager');
  997. });
  998. it('should extract function declarations', () => {
  999. const code = `
  1000. func calculateSum(_ numbers: [Int]) -> Int {
  1001. return numbers.reduce(0, +)
  1002. }
  1003. public func formatCurrency(amount: Double) -> String {
  1004. return String(format: "$%.2f", amount)
  1005. }
  1006. `;
  1007. const result = extractFromSource('utils.swift', code);
  1008. const functions = result.nodes.filter((n) => n.kind === 'function');
  1009. expect(functions.length).toBeGreaterThanOrEqual(1);
  1010. });
  1011. it('should extract struct declarations', () => {
  1012. const code = `
  1013. public struct User {
  1014. let id: UUID
  1015. var name: String
  1016. var email: String
  1017. func displayName() -> String {
  1018. return name
  1019. }
  1020. }
  1021. `;
  1022. const result = extractFromSource('User.swift', code);
  1023. const structNode = result.nodes.find((n) => n.kind === 'struct');
  1024. expect(structNode).toBeDefined();
  1025. expect(structNode?.name).toBe('User');
  1026. });
  1027. it('should extract protocol declarations', () => {
  1028. const code = `
  1029. public protocol Repository {
  1030. associatedtype Entity
  1031. func find(id: String) async throws -> Entity?
  1032. func save(_ entity: Entity) async throws
  1033. }
  1034. `;
  1035. const result = extractFromSource('Repository.swift', code);
  1036. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  1037. expect(protocolNode).toBeDefined();
  1038. expect(protocolNode?.name).toBe('Repository');
  1039. });
  1040. it('should extract class inheritance and protocol conformance', () => {
  1041. const code = `
  1042. class DataRequest: Request {
  1043. func validate() {}
  1044. }
  1045. class UploadRequest: DataRequest, Sendable {
  1046. func upload() {}
  1047. }
  1048. enum AFError: Error {
  1049. case invalidURL
  1050. }
  1051. struct HTTPMethod: RawRepresentable {
  1052. let rawValue: String
  1053. }
  1054. protocol UploadConvertible: URLRequestConvertible {
  1055. func asURLRequest() throws -> URLRequest
  1056. }
  1057. `;
  1058. const result = extractFromSource('Inheritance.swift', code);
  1059. const extendsRefs = result.unresolvedReferences.filter(
  1060. (r) => r.referenceKind === 'extends'
  1061. );
  1062. // DataRequest extends Request
  1063. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  1064. // UploadRequest extends DataRequest and Sendable
  1065. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  1066. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  1067. // AFError extends Error
  1068. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  1069. // HTTPMethod extends RawRepresentable
  1070. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  1071. // UploadConvertible extends URLRequestConvertible
  1072. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  1073. });
  1074. });
  1075. describe('Kotlin Extraction', () => {
  1076. it('should extract class declarations', () => {
  1077. const code = `
  1078. class UserRepository(private val database: Database) {
  1079. fun findById(id: String): User? {
  1080. return database.query("SELECT * FROM users WHERE id = ?", id)
  1081. }
  1082. suspend fun save(user: User) {
  1083. database.insert(user)
  1084. }
  1085. }
  1086. `;
  1087. const result = extractFromSource('UserRepository.kt', code);
  1088. const classNode = result.nodes.find((n) => n.kind === 'class');
  1089. expect(classNode).toBeDefined();
  1090. expect(classNode?.name).toBe('UserRepository');
  1091. });
  1092. it('should extract function declarations', () => {
  1093. const code = `
  1094. fun calculateTotal(items: List<Item>): Double {
  1095. return items.sumOf { it.price }
  1096. }
  1097. suspend fun fetchUserData(userId: String): User {
  1098. return api.getUser(userId)
  1099. }
  1100. `;
  1101. const result = extractFromSource('utils.kt', code);
  1102. const functions = result.nodes.filter((n) => n.kind === 'function');
  1103. expect(functions.length).toBeGreaterThanOrEqual(1);
  1104. });
  1105. it('should detect suspend functions as async', () => {
  1106. const code = `
  1107. suspend fun loadData(): List<String> {
  1108. delay(1000)
  1109. return listOf("a", "b", "c")
  1110. }
  1111. `;
  1112. const result = extractFromSource('loader.kt', code);
  1113. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1114. expect(funcNode).toBeDefined();
  1115. expect(funcNode?.isAsync).toBe(true);
  1116. });
  1117. it('should extract fun interface declarations', () => {
  1118. const code = `
  1119. fun interface OnObjectRetainedListener {
  1120. fun onObjectRetained()
  1121. }
  1122. `;
  1123. const result = extractFromSource('listener.kt', code);
  1124. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1125. expect(ifaceNode).toBeDefined();
  1126. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  1127. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1128. expect(methodNode).toBeDefined();
  1129. expect(methodNode?.name).toBe('onObjectRetained');
  1130. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  1131. });
  1132. it('should extract complex fun interface with nested classes', () => {
  1133. const code = `
  1134. fun interface EventListener {
  1135. fun onEvent(event: Event)
  1136. sealed class Event {
  1137. class DumpingHeap : Event()
  1138. }
  1139. }
  1140. `;
  1141. const result = extractFromSource('events.kt', code);
  1142. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1143. expect(ifaceNode).toBeDefined();
  1144. expect(ifaceNode?.name).toBe('EventListener');
  1145. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  1146. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  1147. expect(eventClass).toBeDefined();
  1148. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  1149. expect(dumpingHeap).toBeDefined();
  1150. });
  1151. it('should not affect regular function declarations', () => {
  1152. const code = `
  1153. fun interface MyCallback {
  1154. fun invoke(value: Int)
  1155. }
  1156. fun regularFunction(): String {
  1157. return "hello"
  1158. }
  1159. `;
  1160. const result = extractFromSource('mixed.kt', code);
  1161. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1162. expect(ifaceNode).toBeDefined();
  1163. expect(ifaceNode?.name).toBe('MyCallback');
  1164. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1165. expect(funcNode).toBeDefined();
  1166. expect(funcNode?.name).toBe('regularFunction');
  1167. });
  1168. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  1169. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  1170. // misparse: function_declaration > ERROR("interface Name {") instead of
  1171. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  1172. const code = `
  1173. import java.io.IOException
  1174. fun interface Interceptor {
  1175. @Throws(IOException::class)
  1176. fun intercept(chain: Chain): Response
  1177. }
  1178. `;
  1179. const result = extractFromSource('interceptor.kt', code);
  1180. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1181. expect(ifaceNode).toBeDefined();
  1182. expect(ifaceNode?.name).toBe('Interceptor');
  1183. });
  1184. it('should extract methods from interface with nested fun interface', () => {
  1185. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  1186. // the parent body as ERROR. Methods inside should still be extracted.
  1187. const code = `
  1188. interface WebSocket {
  1189. fun request(): Request
  1190. fun send(text: String): Boolean
  1191. fun cancel()
  1192. fun interface Factory {
  1193. fun newWebSocket(request: Request): WebSocket
  1194. }
  1195. }
  1196. `;
  1197. const result = extractFromSource('websocket.kt', code);
  1198. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  1199. expect(wsIface).toBeDefined();
  1200. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  1201. const methodNames = methods.map((m) => m.name);
  1202. expect(methodNames).toContain('request');
  1203. expect(methodNames).toContain('send');
  1204. expect(methodNames).toContain('cancel');
  1205. });
  1206. it('wraps top-level declarations in a namespace from package_header', () => {
  1207. const code = `
  1208. package com.example.foo
  1209. class Bar {
  1210. fun greet(): String = "hi"
  1211. }
  1212. fun util(): Int = 42
  1213. `;
  1214. const result = extractFromSource('Bar.kt', code);
  1215. const ns = result.nodes.find((n) => n.kind === 'namespace');
  1216. expect(ns?.name).toBe('com.example.foo');
  1217. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1218. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  1219. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  1220. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  1221. const util = result.nodes.find((n) => n.kind === 'function' && n.name === 'util');
  1222. expect(util?.qualifiedName).toBe('com.example.foo::util');
  1223. });
  1224. it('handles a single-segment package', () => {
  1225. const code = `
  1226. package foo
  1227. class Bar
  1228. `;
  1229. const result = extractFromSource('Bar.kt', code);
  1230. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1231. expect(cls?.qualifiedName).toBe('foo::Bar');
  1232. });
  1233. it('does not wrap when no package is declared', () => {
  1234. const code = `
  1235. class Bar {
  1236. fun greet() = "hi"
  1237. }
  1238. `;
  1239. const result = extractFromSource('Bar.kt', code);
  1240. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  1241. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1242. expect(cls?.qualifiedName).toBe('Bar');
  1243. });
  1244. });
  1245. describe('Dart Extraction', () => {
  1246. it('should extract class declarations', () => {
  1247. const code = `
  1248. class UserService {
  1249. final Database _db;
  1250. Future<User> findById(String id) async {
  1251. return await _db.query(id);
  1252. }
  1253. void _privateMethod() {}
  1254. }
  1255. `;
  1256. const result = extractFromSource('service.dart', code);
  1257. const classNode = result.nodes.find((n) => n.kind === 'class');
  1258. expect(classNode).toBeDefined();
  1259. expect(classNode?.name).toBe('UserService');
  1260. expect(classNode?.visibility).toBe('public');
  1261. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1262. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1263. const findById = methodNodes.find((m) => m.name === 'findById');
  1264. expect(findById).toBeDefined();
  1265. expect(findById?.isAsync).toBe(true);
  1266. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1267. expect(privateMethod).toBeDefined();
  1268. expect(privateMethod?.visibility).toBe('private');
  1269. // Dart models a method body as a SIBLING of the signature, so the method
  1270. // node must be extended to span its body (not just the signature line) —
  1271. // required for body-level analysis (callees, the callback synthesizer).
  1272. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1273. });
  1274. it('should extract top-level function declarations', () => {
  1275. const code = `
  1276. void topLevelFunction(String name) {
  1277. print(name);
  1278. }
  1279. `;
  1280. const result = extractFromSource('utils.dart', code);
  1281. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1282. expect(funcNode).toBeDefined();
  1283. expect(funcNode?.name).toBe('topLevelFunction');
  1284. expect(funcNode?.language).toBe('dart');
  1285. });
  1286. it('should extract enum declarations', () => {
  1287. const code = `
  1288. enum Status { active, inactive, pending }
  1289. `;
  1290. const result = extractFromSource('models.dart', code);
  1291. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1292. expect(enumNode).toBeDefined();
  1293. expect(enumNode?.name).toBe('Status');
  1294. });
  1295. it('should extract mixin declarations', () => {
  1296. const code = `
  1297. mixin LoggerMixin {
  1298. void log(String message) {}
  1299. }
  1300. `;
  1301. const result = extractFromSource('mixins.dart', code);
  1302. const classNode = result.nodes.find((n) => n.kind === 'class');
  1303. expect(classNode).toBeDefined();
  1304. expect(classNode?.name).toBe('LoggerMixin');
  1305. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1306. expect(methodNode).toBeDefined();
  1307. expect(methodNode?.name).toBe('log');
  1308. });
  1309. it('should extract extension declarations', () => {
  1310. const code = `
  1311. extension StringExt on String {
  1312. bool get isBlank => trim().isEmpty;
  1313. }
  1314. `;
  1315. const result = extractFromSource('extensions.dart', code);
  1316. const classNode = result.nodes.find((n) => n.kind === 'class');
  1317. expect(classNode).toBeDefined();
  1318. expect(classNode?.name).toBe('StringExt');
  1319. });
  1320. it('should detect static methods', () => {
  1321. const code = `
  1322. class Utils {
  1323. static void doWork() {}
  1324. }
  1325. `;
  1326. const result = extractFromSource('utils.dart', code);
  1327. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1328. expect(methodNode).toBeDefined();
  1329. expect(methodNode?.name).toBe('doWork');
  1330. expect(methodNode?.isStatic).toBe(true);
  1331. });
  1332. it('should detect async functions', () => {
  1333. const code = `
  1334. Future<String> fetchData() async {
  1335. return await http.get('/data');
  1336. }
  1337. `;
  1338. const result = extractFromSource('api.dart', code);
  1339. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1340. expect(funcNode).toBeDefined();
  1341. expect(funcNode?.name).toBe('fetchData');
  1342. expect(funcNode?.isAsync).toBe(true);
  1343. });
  1344. it('should detect private visibility via underscore convention', () => {
  1345. const code = `
  1346. void _privateHelper() {}
  1347. void publicFunction() {}
  1348. `;
  1349. const result = extractFromSource('helpers.dart', code);
  1350. const functions = result.nodes.filter((n) => n.kind === 'function');
  1351. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1352. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1353. expect(privateFunc?.visibility).toBe('private');
  1354. expect(publicFunc?.visibility).toBe('public');
  1355. });
  1356. });
  1357. describe('Import Extraction', () => {
  1358. describe('TypeScript/JavaScript imports', () => {
  1359. it('should extract default imports', () => {
  1360. const code = `import React from 'react';`;
  1361. const result = extractFromSource('app.tsx', code);
  1362. const importNode = result.nodes.find((n) => n.kind === 'import');
  1363. expect(importNode).toBeDefined();
  1364. expect(importNode?.name).toBe('react');
  1365. expect(importNode?.signature).toBe("import React from 'react';");
  1366. });
  1367. it('should extract named imports', () => {
  1368. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1369. const result = extractFromSource('icons.tsx', code);
  1370. const importNode = result.nodes.find((n) => n.kind === 'import');
  1371. expect(importNode).toBeDefined();
  1372. expect(importNode?.name).toBe('@phosphor-icons/react');
  1373. expect(importNode?.signature).toContain('Bug');
  1374. expect(importNode?.signature).toContain('Database');
  1375. });
  1376. it('should extract namespace imports', () => {
  1377. const code = `import * as Icons from '@phosphor-icons/react';`;
  1378. const result = extractFromSource('icons.tsx', code);
  1379. const importNode = result.nodes.find((n) => n.kind === 'import');
  1380. expect(importNode).toBeDefined();
  1381. expect(importNode?.name).toBe('@phosphor-icons/react');
  1382. expect(importNode?.signature).toContain('* as Icons');
  1383. });
  1384. it('should extract side-effect imports', () => {
  1385. const code = `import './styles.css';`;
  1386. const result = extractFromSource('app.tsx', code);
  1387. const importNode = result.nodes.find((n) => n.kind === 'import');
  1388. expect(importNode).toBeDefined();
  1389. expect(importNode?.name).toBe('./styles.css');
  1390. });
  1391. it('should extract mixed imports (default + named)', () => {
  1392. const code = `import React, { useState, useEffect } from 'react';`;
  1393. const result = extractFromSource('app.tsx', code);
  1394. const importNode = result.nodes.find((n) => n.kind === 'import');
  1395. expect(importNode).toBeDefined();
  1396. expect(importNode?.name).toBe('react');
  1397. expect(importNode?.signature).toContain('React');
  1398. expect(importNode?.signature).toContain('useState');
  1399. expect(importNode?.signature).toContain('useEffect');
  1400. });
  1401. it('should extract multiple import statements', () => {
  1402. const code = `
  1403. import React from 'react';
  1404. import { Button } from './components';
  1405. import './styles.css';
  1406. `;
  1407. const result = extractFromSource('app.tsx', code);
  1408. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1409. expect(importNodes.length).toBe(3);
  1410. const names = importNodes.map((n) => n.name);
  1411. expect(names).toContain('react');
  1412. expect(names).toContain('./components');
  1413. expect(names).toContain('./styles.css');
  1414. });
  1415. it('should extract type imports', () => {
  1416. const code = `import type { FC, ReactNode } from 'react';`;
  1417. const result = extractFromSource('types.ts', code);
  1418. const importNode = result.nodes.find((n) => n.kind === 'import');
  1419. expect(importNode).toBeDefined();
  1420. expect(importNode?.name).toBe('react');
  1421. expect(importNode?.signature).toContain('type');
  1422. expect(importNode?.signature).toContain('FC');
  1423. });
  1424. it('should extract aliased named imports', () => {
  1425. const code = `import { useState as useStateAlias } from 'react';`;
  1426. const result = extractFromSource('hooks.ts', code);
  1427. const importNode = result.nodes.find((n) => n.kind === 'import');
  1428. expect(importNode).toBeDefined();
  1429. expect(importNode?.name).toBe('react');
  1430. expect(importNode?.signature).toContain('useState');
  1431. expect(importNode?.signature).toContain('useStateAlias');
  1432. });
  1433. it('should extract relative path imports', () => {
  1434. const code = `import { helper } from '../utils/helper';`;
  1435. const result = extractFromSource('components/Button.tsx', code);
  1436. const importNode = result.nodes.find((n) => n.kind === 'import');
  1437. expect(importNode).toBeDefined();
  1438. expect(importNode?.name).toBe('../utils/helper');
  1439. expect(importNode?.signature).toContain('helper');
  1440. });
  1441. });
  1442. describe('Python imports', () => {
  1443. it('should extract simple import statement', () => {
  1444. const code = `import json`;
  1445. const result = extractFromSource('utils.py', code);
  1446. const importNode = result.nodes.find((n) => n.kind === 'import');
  1447. expect(importNode).toBeDefined();
  1448. expect(importNode?.name).toBe('json');
  1449. });
  1450. it('should extract from import statement', () => {
  1451. const code = `from os import path`;
  1452. const result = extractFromSource('utils.py', code);
  1453. const importNode = result.nodes.find((n) => n.kind === 'import');
  1454. expect(importNode).toBeDefined();
  1455. expect(importNode?.name).toBe('os');
  1456. expect(importNode?.signature).toContain('path');
  1457. });
  1458. it('should extract multiple imports from same module', () => {
  1459. const code = `from typing import List, Dict, Optional`;
  1460. const result = extractFromSource('types.py', code);
  1461. const importNode = result.nodes.find((n) => n.kind === 'import');
  1462. expect(importNode).toBeDefined();
  1463. expect(importNode?.name).toBe('typing');
  1464. expect(importNode?.signature).toContain('List');
  1465. expect(importNode?.signature).toContain('Dict');
  1466. });
  1467. it('should extract multiple import statements', () => {
  1468. const code = `
  1469. import os
  1470. import sys
  1471. `;
  1472. const result = extractFromSource('main.py', code);
  1473. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1474. expect(importNodes.length).toBe(2);
  1475. const names = importNodes.map((n) => n.name);
  1476. expect(names).toContain('os');
  1477. expect(names).toContain('sys');
  1478. });
  1479. it('should extract aliased import', () => {
  1480. const code = `import numpy as np`;
  1481. const result = extractFromSource('data.py', code);
  1482. const importNode = result.nodes.find((n) => n.kind === 'import');
  1483. expect(importNode).toBeDefined();
  1484. expect(importNode?.name).toBe('numpy');
  1485. expect(importNode?.signature).toContain('as np');
  1486. });
  1487. it('should extract relative import', () => {
  1488. const code = `from .utils import helper`;
  1489. const result = extractFromSource('module.py', code);
  1490. const importNode = result.nodes.find((n) => n.kind === 'import');
  1491. expect(importNode).toBeDefined();
  1492. expect(importNode?.name).toBe('.utils');
  1493. expect(importNode?.signature).toContain('helper');
  1494. });
  1495. it('should extract wildcard import', () => {
  1496. const code = `from typing import *`;
  1497. const result = extractFromSource('types.py', code);
  1498. const importNode = result.nodes.find((n) => n.kind === 'import');
  1499. expect(importNode).toBeDefined();
  1500. expect(importNode?.name).toBe('typing');
  1501. expect(importNode?.signature).toContain('*');
  1502. });
  1503. });
  1504. describe('Rust imports', () => {
  1505. it('should extract simple use declaration', () => {
  1506. const code = `use std::io;`;
  1507. const result = extractFromSource('main.rs', code);
  1508. const importNode = result.nodes.find((n) => n.kind === 'import');
  1509. expect(importNode).toBeDefined();
  1510. expect(importNode?.name).toBe('std');
  1511. expect(importNode?.signature).toBe('use std::io;');
  1512. });
  1513. it('should extract scoped use list', () => {
  1514. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1515. const result = extractFromSource('main.rs', code);
  1516. const importNode = result.nodes.find((n) => n.kind === 'import');
  1517. expect(importNode).toBeDefined();
  1518. expect(importNode?.name).toBe('std');
  1519. expect(importNode?.signature).toContain('ffi::OsStr');
  1520. expect(importNode?.signature).toContain('path::Path');
  1521. });
  1522. it('should extract crate imports', () => {
  1523. const code = `use crate::error::Error;`;
  1524. const result = extractFromSource('lib.rs', code);
  1525. const importNode = result.nodes.find((n) => n.kind === 'import');
  1526. expect(importNode).toBeDefined();
  1527. expect(importNode?.name).toBe('crate');
  1528. });
  1529. it('should extract super imports', () => {
  1530. const code = `use super::utils;`;
  1531. const result = extractFromSource('submod.rs', code);
  1532. const importNode = result.nodes.find((n) => n.kind === 'import');
  1533. expect(importNode).toBeDefined();
  1534. expect(importNode?.name).toBe('super');
  1535. });
  1536. it('should extract external crate imports', () => {
  1537. const code = `use serde::{Serialize, Deserialize};`;
  1538. const result = extractFromSource('types.rs', code);
  1539. const importNode = result.nodes.find((n) => n.kind === 'import');
  1540. expect(importNode).toBeDefined();
  1541. expect(importNode?.name).toBe('serde');
  1542. expect(importNode?.signature).toContain('Serialize');
  1543. expect(importNode?.signature).toContain('Deserialize');
  1544. });
  1545. });
  1546. describe('Go imports', () => {
  1547. it('should extract single import', () => {
  1548. const code = `
  1549. package main
  1550. import "fmt"
  1551. `;
  1552. const result = extractFromSource('main.go', code);
  1553. const importNode = result.nodes.find((n) => n.kind === 'import');
  1554. expect(importNode).toBeDefined();
  1555. expect(importNode?.name).toBe('fmt');
  1556. });
  1557. it('should extract grouped imports', () => {
  1558. const code = `
  1559. package main
  1560. import (
  1561. "fmt"
  1562. "os"
  1563. "encoding/json"
  1564. )
  1565. `;
  1566. const result = extractFromSource('main.go', 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('fmt');
  1571. expect(names).toContain('os');
  1572. expect(names).toContain('encoding/json');
  1573. });
  1574. it('should extract aliased import', () => {
  1575. const code = `
  1576. package main
  1577. import f "fmt"
  1578. `;
  1579. const result = extractFromSource('main.go', code);
  1580. const importNode = result.nodes.find((n) => n.kind === 'import');
  1581. expect(importNode).toBeDefined();
  1582. expect(importNode?.name).toBe('fmt');
  1583. expect(importNode?.signature).toContain('f');
  1584. });
  1585. it('should extract dot import', () => {
  1586. const code = `
  1587. package main
  1588. import . "math"
  1589. `;
  1590. const result = extractFromSource('main.go', code);
  1591. const importNode = result.nodes.find((n) => n.kind === 'import');
  1592. expect(importNode).toBeDefined();
  1593. expect(importNode?.name).toBe('math');
  1594. expect(importNode?.signature).toContain('.');
  1595. });
  1596. it('should extract blank import', () => {
  1597. const code = `
  1598. package main
  1599. import _ "github.com/go-sql-driver/mysql"
  1600. `;
  1601. const result = extractFromSource('main.go', code);
  1602. const importNode = result.nodes.find((n) => n.kind === 'import');
  1603. expect(importNode).toBeDefined();
  1604. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1605. expect(importNode?.signature).toContain('_');
  1606. });
  1607. });
  1608. describe('Swift imports', () => {
  1609. it('should extract simple import', () => {
  1610. const code = `import Foundation`;
  1611. const result = extractFromSource('main.swift', code);
  1612. const importNode = result.nodes.find((n) => n.kind === 'import');
  1613. expect(importNode).toBeDefined();
  1614. expect(importNode?.name).toBe('Foundation');
  1615. expect(importNode?.signature).toBe('import Foundation');
  1616. });
  1617. it('should extract @testable import', () => {
  1618. const code = `@testable import Alamofire`;
  1619. const result = extractFromSource('Tests.swift', code);
  1620. const importNode = result.nodes.find((n) => n.kind === 'import');
  1621. expect(importNode).toBeDefined();
  1622. expect(importNode?.name).toBe('Alamofire');
  1623. expect(importNode?.signature).toContain('@testable');
  1624. });
  1625. it('should extract @preconcurrency import', () => {
  1626. const code = `@preconcurrency import Security`;
  1627. const result = extractFromSource('Auth.swift', code);
  1628. const importNode = result.nodes.find((n) => n.kind === 'import');
  1629. expect(importNode).toBeDefined();
  1630. expect(importNode?.name).toBe('Security');
  1631. });
  1632. it('should extract multiple imports', () => {
  1633. const code = `
  1634. import Foundation
  1635. import UIKit
  1636. import Alamofire
  1637. `;
  1638. const result = extractFromSource('App.swift', code);
  1639. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1640. expect(importNodes.length).toBe(3);
  1641. const names = importNodes.map((n) => n.name);
  1642. expect(names).toContain('Foundation');
  1643. expect(names).toContain('UIKit');
  1644. expect(names).toContain('Alamofire');
  1645. });
  1646. });
  1647. describe('Kotlin imports', () => {
  1648. it('should extract simple import', () => {
  1649. const code = `import java.io.IOException`;
  1650. const result = extractFromSource('Main.kt', code);
  1651. const importNode = result.nodes.find((n) => n.kind === 'import');
  1652. expect(importNode).toBeDefined();
  1653. expect(importNode?.name).toBe('java.io.IOException');
  1654. expect(importNode?.signature).toBe('import java.io.IOException');
  1655. });
  1656. it('should extract aliased import', () => {
  1657. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1658. const result = extractFromSource('Utils.kt', code);
  1659. const importNode = result.nodes.find((n) => n.kind === 'import');
  1660. expect(importNode).toBeDefined();
  1661. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1662. expect(importNode?.signature).toContain('as RequestBuilder');
  1663. });
  1664. it('should extract wildcard import', () => {
  1665. const code = `import java.util.concurrent.TimeUnit.*`;
  1666. const result = extractFromSource('Time.kt', code);
  1667. const importNode = result.nodes.find((n) => n.kind === 'import');
  1668. expect(importNode).toBeDefined();
  1669. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1670. expect(importNode?.signature).toContain('.*');
  1671. });
  1672. it('should extract multiple imports', () => {
  1673. const code = `
  1674. import java.io.IOException
  1675. import kotlin.test.assertFailsWith
  1676. import okhttp3.OkHttpClient
  1677. `;
  1678. const result = extractFromSource('Test.kt', code);
  1679. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1680. expect(importNodes.length).toBe(3);
  1681. const names = importNodes.map((n) => n.name);
  1682. expect(names).toContain('java.io.IOException');
  1683. expect(names).toContain('kotlin.test.assertFailsWith');
  1684. expect(names).toContain('okhttp3.OkHttpClient');
  1685. });
  1686. });
  1687. describe('Java imports', () => {
  1688. it('should extract simple import', () => {
  1689. const code = `import java.util.List;`;
  1690. const result = extractFromSource('Main.java', code);
  1691. const importNode = result.nodes.find((n) => n.kind === 'import');
  1692. expect(importNode).toBeDefined();
  1693. expect(importNode?.name).toBe('java.util.List');
  1694. expect(importNode?.signature).toBe('import java.util.List;');
  1695. });
  1696. it('should extract static import', () => {
  1697. const code = `import static java.util.Collections.emptyList;`;
  1698. const result = extractFromSource('Utils.java', code);
  1699. const importNode = result.nodes.find((n) => n.kind === 'import');
  1700. expect(importNode).toBeDefined();
  1701. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1702. expect(importNode?.signature).toContain('static');
  1703. });
  1704. it('should extract wildcard import', () => {
  1705. const code = `import java.util.*;`;
  1706. const result = extractFromSource('App.java', code);
  1707. const importNode = result.nodes.find((n) => n.kind === 'import');
  1708. expect(importNode).toBeDefined();
  1709. expect(importNode?.name).toBe('java.util');
  1710. expect(importNode?.signature).toContain('.*');
  1711. });
  1712. it('should extract nested class import', () => {
  1713. const code = `import java.util.Map.Entry;`;
  1714. const result = extractFromSource('MapUtil.java', code);
  1715. const importNode = result.nodes.find((n) => n.kind === 'import');
  1716. expect(importNode).toBeDefined();
  1717. expect(importNode?.name).toBe('java.util.Map.Entry');
  1718. });
  1719. it('should extract multiple imports', () => {
  1720. const code = `
  1721. import java.util.List;
  1722. import java.util.Map;
  1723. import java.io.IOException;
  1724. `;
  1725. const result = extractFromSource('Service.java', code);
  1726. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1727. expect(importNodes.length).toBe(3);
  1728. const names = importNodes.map((n) => n.name);
  1729. expect(names).toContain('java.util.List');
  1730. expect(names).toContain('java.util.Map');
  1731. expect(names).toContain('java.io.IOException');
  1732. });
  1733. });
  1734. describe('C# imports', () => {
  1735. it('should extract simple using', () => {
  1736. const code = `using System;`;
  1737. const result = extractFromSource('Program.cs', code);
  1738. const importNode = result.nodes.find((n) => n.kind === 'import');
  1739. expect(importNode).toBeDefined();
  1740. expect(importNode?.name).toBe('System');
  1741. expect(importNode?.signature).toBe('using System;');
  1742. });
  1743. it('should extract qualified using', () => {
  1744. const code = `using System.Collections.Generic;`;
  1745. const result = extractFromSource('Utils.cs', code);
  1746. const importNode = result.nodes.find((n) => n.kind === 'import');
  1747. expect(importNode).toBeDefined();
  1748. expect(importNode?.name).toBe('System.Collections.Generic');
  1749. });
  1750. it('should extract static using', () => {
  1751. const code = `using static System.Console;`;
  1752. const result = extractFromSource('App.cs', code);
  1753. const importNode = result.nodes.find((n) => n.kind === 'import');
  1754. expect(importNode).toBeDefined();
  1755. expect(importNode?.name).toBe('System.Console');
  1756. expect(importNode?.signature).toContain('static');
  1757. });
  1758. it('should extract alias using', () => {
  1759. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1760. const result = extractFromSource('Types.cs', code);
  1761. const importNode = result.nodes.find((n) => n.kind === 'import');
  1762. expect(importNode).toBeDefined();
  1763. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1764. expect(importNode?.signature).toContain('MyList =');
  1765. });
  1766. it('should extract multiple usings', () => {
  1767. const code = `
  1768. using System;
  1769. using System.Threading.Tasks;
  1770. using Microsoft.Extensions.DependencyInjection;
  1771. `;
  1772. const result = extractFromSource('Service.cs', code);
  1773. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1774. expect(importNodes.length).toBe(3);
  1775. const names = importNodes.map((n) => n.name);
  1776. expect(names).toContain('System');
  1777. expect(names).toContain('System.Threading.Tasks');
  1778. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1779. });
  1780. });
  1781. describe('PHP imports', () => {
  1782. it('should extract simple use', () => {
  1783. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1784. const result = extractFromSource('Test.php', code);
  1785. const importNode = result.nodes.find((n) => n.kind === 'import');
  1786. expect(importNode).toBeDefined();
  1787. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1788. });
  1789. it('should extract aliased use', () => {
  1790. const code = `<?php use Mockery as m;`;
  1791. const result = extractFromSource('Test.php', code);
  1792. const importNode = result.nodes.find((n) => n.kind === 'import');
  1793. expect(importNode).toBeDefined();
  1794. expect(importNode?.name).toBe('Mockery');
  1795. expect(importNode?.signature).toContain('as m');
  1796. });
  1797. it('should extract function use', () => {
  1798. const code = `<?php use function Illuminate\\Support\\env;`;
  1799. const result = extractFromSource('helpers.php', code);
  1800. const importNode = result.nodes.find((n) => n.kind === 'import');
  1801. expect(importNode).toBeDefined();
  1802. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1803. expect(importNode?.signature).toContain('function');
  1804. });
  1805. it('should extract grouped use', () => {
  1806. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1807. const result = extractFromSource('Models.php', code);
  1808. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1809. expect(importNodes.length).toBe(2);
  1810. const names = importNodes.map((n) => n.name);
  1811. expect(names).toContain('Illuminate\\Database\\Model');
  1812. expect(names).toContain('Illuminate\\Database\\Builder');
  1813. });
  1814. it('should extract multiple uses', () => {
  1815. const code = `<?php
  1816. use Illuminate\\Support\\Collection;
  1817. use Illuminate\\Support\\Str;
  1818. use Closure;
  1819. `;
  1820. const result = extractFromSource('Service.php', code);
  1821. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1822. expect(importNodes.length).toBe(3);
  1823. const names = importNodes.map((n) => n.name);
  1824. expect(names).toContain('Illuminate\\Support\\Collection');
  1825. expect(names).toContain('Illuminate\\Support\\Str');
  1826. expect(names).toContain('Closure');
  1827. });
  1828. });
  1829. describe('Ruby imports', () => {
  1830. it('should extract require', () => {
  1831. const code = `require 'json'`;
  1832. const result = extractFromSource('app.rb', code);
  1833. const importNode = result.nodes.find((n) => n.kind === 'import');
  1834. expect(importNode).toBeDefined();
  1835. expect(importNode?.name).toBe('json');
  1836. expect(importNode?.signature).toBe("require 'json'");
  1837. });
  1838. it('should extract require with path', () => {
  1839. const code = `require 'active_support/core_ext/string'`;
  1840. const result = extractFromSource('config.rb', code);
  1841. const importNode = result.nodes.find((n) => n.kind === 'import');
  1842. expect(importNode).toBeDefined();
  1843. expect(importNode?.name).toBe('active_support/core_ext/string');
  1844. });
  1845. it('should extract require_relative', () => {
  1846. const code = `require_relative '../test_helper'`;
  1847. const result = extractFromSource('test/my_test.rb', code);
  1848. const importNode = result.nodes.find((n) => n.kind === 'import');
  1849. expect(importNode).toBeDefined();
  1850. expect(importNode?.name).toBe('../test_helper');
  1851. expect(importNode?.signature).toContain('require_relative');
  1852. });
  1853. it('should not extract non-require calls', () => {
  1854. const code = `puts 'hello'`;
  1855. const result = extractFromSource('app.rb', code);
  1856. const importNode = result.nodes.find((n) => n.kind === 'import');
  1857. expect(importNode).toBeUndefined();
  1858. });
  1859. it('should extract multiple requires', () => {
  1860. const code = `
  1861. require 'json'
  1862. require 'yaml'
  1863. require_relative 'helper'
  1864. `;
  1865. const result = extractFromSource('lib.rb', code);
  1866. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1867. expect(importNodes.length).toBe(3);
  1868. const names = importNodes.map((n) => n.name);
  1869. expect(names).toContain('json');
  1870. expect(names).toContain('yaml');
  1871. expect(names).toContain('helper');
  1872. });
  1873. });
  1874. describe('Ruby modules', () => {
  1875. it('should extract module as module node with containment', () => {
  1876. const code = `
  1877. module CachedCounting
  1878. def self.disable
  1879. @enabled = false
  1880. end
  1881. def perform_increment!(key, count)
  1882. write_cache!(key, count)
  1883. end
  1884. end
  1885. `;
  1886. const result = extractFromSource('concerns/cached_counting.rb', code);
  1887. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1888. expect(moduleNode).toBeDefined();
  1889. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1890. // Methods inside module should have module-qualified names
  1891. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1892. expect(disableMethod).toBeDefined();
  1893. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1894. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1895. expect(incrementMethod).toBeDefined();
  1896. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1897. // Containment edge from module to methods
  1898. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1899. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1900. });
  1901. it('should handle nested modules with classes', () => {
  1902. const code = `
  1903. module Discourse
  1904. module Auth
  1905. class AuthProvider
  1906. def authenticate(params)
  1907. validate(params)
  1908. end
  1909. end
  1910. end
  1911. end
  1912. `;
  1913. const result = extractFromSource('lib/auth.rb', code);
  1914. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1915. expect(discourseModule).toBeDefined();
  1916. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1917. expect(authModule).toBeDefined();
  1918. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1919. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1920. expect(authProvider).toBeDefined();
  1921. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1922. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1923. expect(authMethod).toBeDefined();
  1924. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1925. });
  1926. });
  1927. describe('C/C++ imports', () => {
  1928. it('should extract system include', () => {
  1929. const code = `#include <iostream>`;
  1930. const result = extractFromSource('main.cpp', code);
  1931. const importNode = result.nodes.find((n) => n.kind === 'import');
  1932. expect(importNode).toBeDefined();
  1933. expect(importNode?.name).toBe('iostream');
  1934. expect(importNode?.signature).toBe('#include <iostream>');
  1935. });
  1936. it('should extract system include with path', () => {
  1937. const code = `#include <nlohmann/json.hpp>`;
  1938. const result = extractFromSource('app.cpp', code);
  1939. const importNode = result.nodes.find((n) => n.kind === 'import');
  1940. expect(importNode).toBeDefined();
  1941. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1942. });
  1943. it('should extract local include', () => {
  1944. const code = `#include "myheader.h"`;
  1945. const result = extractFromSource('main.cpp', code);
  1946. const importNode = result.nodes.find((n) => n.kind === 'import');
  1947. expect(importNode).toBeDefined();
  1948. expect(importNode?.name).toBe('myheader.h');
  1949. });
  1950. it('should extract C header', () => {
  1951. const code = `#include <stdio.h>`;
  1952. const result = extractFromSource('main.c', code);
  1953. const importNode = result.nodes.find((n) => n.kind === 'import');
  1954. expect(importNode).toBeDefined();
  1955. expect(importNode?.name).toBe('stdio.h');
  1956. });
  1957. it('should extract multiple includes', () => {
  1958. const code = `
  1959. #include <iostream>
  1960. #include <vector>
  1961. #include "config.h"
  1962. `;
  1963. const result = extractFromSource('app.cpp', code);
  1964. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1965. expect(importNodes.length).toBe(3);
  1966. const names = importNodes.map((n) => n.name);
  1967. expect(names).toContain('iostream');
  1968. expect(names).toContain('vector');
  1969. expect(names).toContain('config.h');
  1970. });
  1971. it('should create unresolved references for local includes', () => {
  1972. const code = `#include "myheader.h"`;
  1973. const result = extractFromSource('main.cpp', code);
  1974. const importRef = result.unresolvedReferences.find(
  1975. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  1976. );
  1977. expect(importRef).toBeDefined();
  1978. expect(importRef?.line).toBe(1);
  1979. });
  1980. it('should create unresolved references for system includes', () => {
  1981. const code = `#include <iostream>`;
  1982. const result = extractFromSource('main.cpp', code);
  1983. const importRef = result.unresolvedReferences.find(
  1984. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  1985. );
  1986. expect(importRef).toBeDefined();
  1987. });
  1988. });
  1989. describe('Dart imports', () => {
  1990. it('should extract dart: import', () => {
  1991. const code = `import 'dart:async';`;
  1992. const result = extractFromSource('main.dart', code);
  1993. const importNode = result.nodes.find((n) => n.kind === 'import');
  1994. expect(importNode).toBeDefined();
  1995. expect(importNode?.name).toBe('dart:async');
  1996. expect(importNode?.signature).toBe("import 'dart:async';");
  1997. });
  1998. it('should extract package import', () => {
  1999. const code = `import 'package:flutter/material.dart';`;
  2000. const result = extractFromSource('app.dart', code);
  2001. const importNode = result.nodes.find((n) => n.kind === 'import');
  2002. expect(importNode).toBeDefined();
  2003. expect(importNode?.name).toBe('package:flutter/material.dart');
  2004. });
  2005. it('should extract aliased import', () => {
  2006. const code = `import 'package:http/http.dart' as http;`;
  2007. const result = extractFromSource('api.dart', code);
  2008. const importNode = result.nodes.find((n) => n.kind === 'import');
  2009. expect(importNode).toBeDefined();
  2010. expect(importNode?.name).toBe('package:http/http.dart');
  2011. expect(importNode?.signature).toContain('as http');
  2012. });
  2013. it('should extract multiple imports', () => {
  2014. const code = `
  2015. import 'dart:async';
  2016. import 'dart:convert';
  2017. import 'package:flutter/material.dart';
  2018. `;
  2019. const result = extractFromSource('main.dart', code);
  2020. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2021. expect(importNodes.length).toBe(3);
  2022. const names = importNodes.map((n) => n.name);
  2023. expect(names).toContain('dart:async');
  2024. expect(names).toContain('dart:convert');
  2025. expect(names).toContain('package:flutter/material.dart');
  2026. });
  2027. it('should extract relative import', () => {
  2028. const code = `import '../utils/helpers.dart';`;
  2029. const result = extractFromSource('lib/main.dart', code);
  2030. const importNode = result.nodes.find((n) => n.kind === 'import');
  2031. expect(importNode).toBeDefined();
  2032. expect(importNode?.name).toBe('../utils/helpers.dart');
  2033. });
  2034. });
  2035. describe('Liquid imports', () => {
  2036. it('should extract render tag', () => {
  2037. const code = `{% render 'loading-spinner' %}`;
  2038. const result = extractFromSource('template.liquid', code);
  2039. const importNode = result.nodes.find((n) => n.kind === 'import');
  2040. expect(importNode).toBeDefined();
  2041. expect(importNode?.name).toBe('loading-spinner');
  2042. expect(importNode?.signature).toContain('render');
  2043. });
  2044. it('should extract section tag', () => {
  2045. const code = `{% section 'header' %}`;
  2046. const result = extractFromSource('layout/theme.liquid', code);
  2047. const importNode = result.nodes.find((n) => n.kind === 'import');
  2048. expect(importNode).toBeDefined();
  2049. expect(importNode?.name).toBe('header');
  2050. expect(importNode?.signature).toContain('section');
  2051. });
  2052. it('should extract include tag', () => {
  2053. const code = `{% include 'icon-cart' %}`;
  2054. const result = extractFromSource('snippets/header.liquid', code);
  2055. const importNode = result.nodes.find((n) => n.kind === 'import');
  2056. expect(importNode).toBeDefined();
  2057. expect(importNode?.name).toBe('icon-cart');
  2058. expect(importNode?.signature).toContain('include');
  2059. });
  2060. it('should extract render with whitespace control', () => {
  2061. const code = `{%- render 'price' -%}`;
  2062. const result = extractFromSource('snippets/product.liquid', code);
  2063. const importNode = result.nodes.find((n) => n.kind === 'import');
  2064. expect(importNode).toBeDefined();
  2065. expect(importNode?.name).toBe('price');
  2066. });
  2067. it('should extract multiple imports', () => {
  2068. const code = `
  2069. {% section 'header' %}
  2070. {% render 'loading-spinner' %}
  2071. {% render 'cart-drawer' %}
  2072. `;
  2073. const result = extractFromSource('layout/theme.liquid', code);
  2074. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2075. expect(importNodes.length).toBe(3);
  2076. const names = importNodes.map((n) => n.name);
  2077. expect(names).toContain('header');
  2078. expect(names).toContain('loading-spinner');
  2079. expect(names).toContain('cart-drawer');
  2080. });
  2081. });
  2082. });
  2083. // =============================================================================
  2084. // Pascal / Delphi Extraction
  2085. // =============================================================================
  2086. describe('Pascal / Delphi Extraction', () => {
  2087. describe('Language detection', () => {
  2088. it('should detect Pascal files', () => {
  2089. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2090. expect(detectLanguage('App.dpr')).toBe('pascal');
  2091. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2092. expect(detectLanguage('App.lpr')).toBe('pascal');
  2093. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2094. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2095. });
  2096. it('should report Pascal as supported', () => {
  2097. expect(isLanguageSupported('pascal')).toBe(true);
  2098. expect(getSupportedLanguages()).toContain('pascal');
  2099. });
  2100. });
  2101. describe('Unit extraction', () => {
  2102. it('should extract unit as module', () => {
  2103. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2104. const result = extractFromSource('MyUnit.pas', code);
  2105. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2106. expect(moduleNode).toBeDefined();
  2107. expect(moduleNode?.name).toBe('MyUnit');
  2108. expect(moduleNode?.language).toBe('pascal');
  2109. });
  2110. it('should extract program as module', () => {
  2111. const code = `program MyApp;\nbegin\nend.`;
  2112. const result = extractFromSource('MyApp.dpr', code);
  2113. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2114. expect(moduleNode).toBeDefined();
  2115. expect(moduleNode?.name).toBe('MyApp');
  2116. });
  2117. it('should fallback to filename when module name is empty', () => {
  2118. // Some .dpr templates use "program;" without a name
  2119. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2120. const result = extractFromSource('Console.dpr', code);
  2121. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2122. expect(moduleNode).toBeDefined();
  2123. expect(moduleNode?.name).toBe('Console');
  2124. });
  2125. });
  2126. describe('Uses clause (imports)', () => {
  2127. it('should extract uses as individual imports', () => {
  2128. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2129. const result = extractFromSource('Test.pas', code);
  2130. const imports = result.nodes.filter((n) => n.kind === 'import');
  2131. expect(imports.length).toBe(2);
  2132. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2133. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2134. });
  2135. it('should create unresolved references for imports', () => {
  2136. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2137. const result = extractFromSource('Test.pas', code);
  2138. const importRef = result.unresolvedReferences.find(
  2139. (r) => r.referenceKind === 'imports'
  2140. );
  2141. expect(importRef).toBeDefined();
  2142. expect(importRef?.referenceName).toBe('UAuth');
  2143. });
  2144. });
  2145. describe('Class extraction', () => {
  2146. it('should extract class declarations', () => {
  2147. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2148. const result = extractFromSource('Test.pas', code);
  2149. const classNode = result.nodes.find((n) => n.kind === 'class');
  2150. expect(classNode).toBeDefined();
  2151. expect(classNode?.name).toBe('TMyClass');
  2152. });
  2153. it('should extract class with inheritance', () => {
  2154. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2155. const result = extractFromSource('Test.pas', code);
  2156. const extendsRef = result.unresolvedReferences.find(
  2157. (r) => r.referenceKind === 'extends'
  2158. );
  2159. expect(extendsRef).toBeDefined();
  2160. expect(extendsRef?.referenceName).toBe('TParent');
  2161. });
  2162. it('should extract class with interface implementation', () => {
  2163. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2164. const result = extractFromSource('Test.pas', code);
  2165. const extendsRef = result.unresolvedReferences.find(
  2166. (r) => r.referenceKind === 'extends'
  2167. );
  2168. const implementsRef = result.unresolvedReferences.find(
  2169. (r) => r.referenceKind === 'implements'
  2170. );
  2171. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2172. expect(implementsRef?.referenceName).toBe('ILogger');
  2173. });
  2174. });
  2175. describe('Record extraction', () => {
  2176. it('should extract records as class nodes', () => {
  2177. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2178. const result = extractFromSource('Test.pas', code);
  2179. const classNode = result.nodes.find((n) => n.kind === 'class');
  2180. expect(classNode).toBeDefined();
  2181. expect(classNode?.name).toBe('TPoint');
  2182. const fields = result.nodes.filter((n) => n.kind === 'field');
  2183. expect(fields.length).toBe(2);
  2184. expect(fields.map((f) => f.name)).toContain('X');
  2185. expect(fields.map((f) => f.name)).toContain('Y');
  2186. });
  2187. });
  2188. describe('Interface extraction', () => {
  2189. it('should extract interface declarations', () => {
  2190. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2191. const result = extractFromSource('Test.pas', code);
  2192. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2193. expect(ifaceNode).toBeDefined();
  2194. expect(ifaceNode?.name).toBe('ILogger');
  2195. });
  2196. });
  2197. describe('Method extraction', () => {
  2198. it('should extract methods with visibility', () => {
  2199. 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.`;
  2200. const result = extractFromSource('Test.pas', code);
  2201. const methods = result.nodes.filter((n) => n.kind === 'method');
  2202. expect(methods.length).toBe(2);
  2203. const createMethod = methods.find((m) => m.name === 'Create');
  2204. expect(createMethod?.visibility).toBe('public');
  2205. const getValue = methods.find((m) => m.name === 'GetValue');
  2206. expect(getValue?.visibility).toBe('public');
  2207. const fields = result.nodes.filter((n) => n.kind === 'field');
  2208. const fValue = fields.find((f) => f.name === 'FValue');
  2209. expect(fValue?.visibility).toBe('private');
  2210. });
  2211. it('should detect static methods (class methods)', () => {
  2212. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2213. const result = extractFromSource('Test.pas', code);
  2214. const methods = result.nodes.filter((n) => n.kind === 'method');
  2215. const staticMethod = methods.find((m) => m.name === 'Create');
  2216. expect(staticMethod?.isStatic).toBe(true);
  2217. });
  2218. });
  2219. describe('Enum extraction', () => {
  2220. it('should extract enums with members', () => {
  2221. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2222. const result = extractFromSource('Test.pas', code);
  2223. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2224. expect(enumNode).toBeDefined();
  2225. expect(enumNode?.name).toBe('TColor');
  2226. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2227. expect(members.length).toBe(3);
  2228. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2229. });
  2230. });
  2231. describe('Property extraction', () => {
  2232. it('should extract properties', () => {
  2233. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2234. const result = extractFromSource('Test.pas', code);
  2235. const propNode = result.nodes.find((n) => n.kind === 'property');
  2236. expect(propNode).toBeDefined();
  2237. expect(propNode?.name).toBe('Name');
  2238. expect(propNode?.visibility).toBe('public');
  2239. });
  2240. });
  2241. describe('Constant extraction', () => {
  2242. it('should extract constants', () => {
  2243. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2244. const result = extractFromSource('Test.pas', code);
  2245. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2246. expect(constants.length).toBe(2);
  2247. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2248. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2249. });
  2250. });
  2251. describe('Type alias extraction', () => {
  2252. it('should extract type aliases', () => {
  2253. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2254. const result = extractFromSource('Test.pas', code);
  2255. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2256. expect(aliasNode).toBeDefined();
  2257. expect(aliasNode?.name).toBe('TUserName');
  2258. });
  2259. });
  2260. describe('Call extraction', () => {
  2261. it('should extract calls from implementation bodies', () => {
  2262. 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.`;
  2263. const result = extractFromSource('Test.pas', code);
  2264. const callRef = result.unresolvedReferences.find(
  2265. (r) => r.referenceKind === 'calls'
  2266. );
  2267. expect(callRef).toBeDefined();
  2268. expect(callRef?.referenceName).toBe('WriteLn');
  2269. });
  2270. });
  2271. describe('Containment edges', () => {
  2272. it('should create contains edges for class members', () => {
  2273. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2274. const result = extractFromSource('Test.pas', code);
  2275. const classNode = result.nodes.find((n) => n.kind === 'class');
  2276. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2277. expect(classNode).toBeDefined();
  2278. expect(methodNode).toBeDefined();
  2279. const containsEdge = result.edges.find(
  2280. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2281. );
  2282. expect(containsEdge).toBeDefined();
  2283. });
  2284. });
  2285. describe('Full fixture: UAuth.pas', () => {
  2286. const code = `unit UAuth;
  2287. interface
  2288. uses
  2289. System.SysUtils,
  2290. System.Classes;
  2291. type
  2292. ITokenValidator = interface
  2293. ['{11111111-1111-1111-1111-111111111111}']
  2294. function Validate(const AToken: string): Boolean;
  2295. end;
  2296. TAuthService = class(TInterfacedObject, ITokenValidator)
  2297. private
  2298. FToken: string;
  2299. FLoginCount: Integer;
  2300. procedure IncLoginCount;
  2301. protected
  2302. function GetToken: string;
  2303. public
  2304. constructor Create;
  2305. destructor Destroy; override;
  2306. function Validate(const AToken: string): Boolean;
  2307. function Login(const AUser, APass: string): string;
  2308. property Token: string read GetToken;
  2309. property LoginCount: Integer read FLoginCount;
  2310. end;
  2311. implementation
  2312. constructor TAuthService.Create;
  2313. begin
  2314. inherited Create;
  2315. FToken := '';
  2316. FLoginCount := 0;
  2317. end;
  2318. destructor TAuthService.Destroy;
  2319. begin
  2320. FToken := '';
  2321. inherited Destroy;
  2322. end;
  2323. procedure TAuthService.IncLoginCount;
  2324. begin
  2325. Inc(FLoginCount);
  2326. end;
  2327. function TAuthService.GetToken: string;
  2328. begin
  2329. Result := FToken;
  2330. end;
  2331. function TAuthService.Validate(const AToken: string): Boolean;
  2332. begin
  2333. Result := AToken <> '';
  2334. end;
  2335. function TAuthService.Login(const AUser, APass: string): string;
  2336. begin
  2337. IncLoginCount;
  2338. if Validate(AUser + ':' + APass) then
  2339. begin
  2340. FToken := AUser;
  2341. Result := 'ok';
  2342. end
  2343. else
  2344. Result := '';
  2345. end;
  2346. end.`;
  2347. it('should extract all expected nodes', () => {
  2348. const result = extractFromSource('UAuth.pas', code);
  2349. expect(result.errors).toHaveLength(0);
  2350. // Module
  2351. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2352. expect(moduleNode?.name).toBe('UAuth');
  2353. // Imports
  2354. const imports = result.nodes.filter((n) => n.kind === 'import');
  2355. expect(imports.length).toBe(2);
  2356. // Interface
  2357. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2358. expect(ifaceNode?.name).toBe('ITokenValidator');
  2359. // Class
  2360. const classNode = result.nodes.find((n) => n.kind === 'class');
  2361. expect(classNode?.name).toBe('TAuthService');
  2362. // Methods
  2363. const methods = result.nodes.filter((n) => n.kind === 'method');
  2364. expect(methods.length).toBeGreaterThanOrEqual(6);
  2365. expect(methods.map((m) => m.name)).toContain('Create');
  2366. expect(methods.map((m) => m.name)).toContain('Destroy');
  2367. expect(methods.map((m) => m.name)).toContain('Login');
  2368. // Fields
  2369. const fields = result.nodes.filter((n) => n.kind === 'field');
  2370. expect(fields.length).toBe(2);
  2371. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2372. // Properties
  2373. const props = result.nodes.filter((n) => n.kind === 'property');
  2374. expect(props.length).toBe(2);
  2375. expect(props.map((p) => p.name)).toContain('Token');
  2376. expect(props.map((p) => p.name)).toContain('LoginCount');
  2377. });
  2378. it('should extract inheritance and interface implementation', () => {
  2379. const result = extractFromSource('UAuth.pas', code);
  2380. const extendsRef = result.unresolvedReferences.find(
  2381. (r) => r.referenceKind === 'extends'
  2382. );
  2383. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2384. const implementsRef = result.unresolvedReferences.find(
  2385. (r) => r.referenceKind === 'implements'
  2386. );
  2387. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2388. });
  2389. it('should extract calls from implementation', () => {
  2390. const result = extractFromSource('UAuth.pas', code);
  2391. const callRefs = result.unresolvedReferences.filter(
  2392. (r) => r.referenceKind === 'calls'
  2393. );
  2394. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2395. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2396. });
  2397. });
  2398. describe('Full fixture: UTypes.pas', () => {
  2399. const code = `unit UTypes;
  2400. interface
  2401. uses
  2402. System.SysUtils;
  2403. const
  2404. C_MAX_RETRIES = 3;
  2405. C_DEFAULT_NAME = 'Guest';
  2406. type
  2407. TUserRole = (urAdmin, urEditor, urViewer);
  2408. TPoint2D = record
  2409. X: Double;
  2410. Y: Double;
  2411. end;
  2412. TUserName = string;
  2413. TUserInfo = class
  2414. public
  2415. type
  2416. TAddress = record
  2417. Street: string;
  2418. City: string;
  2419. Zip: string;
  2420. end;
  2421. private
  2422. FName: TUserName;
  2423. FRole: TUserRole;
  2424. FAddress: TAddress;
  2425. public
  2426. constructor Create(const AName: TUserName; ARole: TUserRole);
  2427. function GetDisplayName: string;
  2428. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2429. property Name: TUserName read FName write FName;
  2430. property Role: TUserRole read FRole;
  2431. property Address: TAddress read FAddress write FAddress;
  2432. end;
  2433. implementation
  2434. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2435. begin
  2436. FName := AName;
  2437. FRole := ARole;
  2438. end;
  2439. function TUserInfo.GetDisplayName: string;
  2440. begin
  2441. if FRole = urAdmin then
  2442. Result := '[Admin] ' + FName
  2443. else
  2444. Result := FName;
  2445. end;
  2446. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2447. begin
  2448. Result := TUserInfo.Create(AName, urAdmin);
  2449. end;
  2450. end.`;
  2451. it('should extract enums with members', () => {
  2452. const result = extractFromSource('UTypes.pas', code);
  2453. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2454. expect(enumNode?.name).toBe('TUserRole');
  2455. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2456. expect(members.length).toBe(3);
  2457. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2458. });
  2459. it('should extract constants', () => {
  2460. const result = extractFromSource('UTypes.pas', code);
  2461. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2462. expect(constants.length).toBe(2);
  2463. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2464. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2465. });
  2466. it('should extract type aliases', () => {
  2467. const result = extractFromSource('UTypes.pas', code);
  2468. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2469. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2470. });
  2471. it('should extract records as classes with fields', () => {
  2472. const result = extractFromSource('UTypes.pas', code);
  2473. const classes = result.nodes.filter((n) => n.kind === 'class');
  2474. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2475. // TPoint2D fields
  2476. const fields = result.nodes.filter((n) => n.kind === 'field');
  2477. expect(fields.map((f) => f.name)).toContain('X');
  2478. expect(fields.map((f) => f.name)).toContain('Y');
  2479. });
  2480. it('should extract static class methods', () => {
  2481. const result = extractFromSource('UTypes.pas', code);
  2482. const methods = result.nodes.filter((n) => n.kind === 'method');
  2483. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2484. expect(staticMethod).toBeDefined();
  2485. expect(staticMethod?.isStatic).toBe(true);
  2486. });
  2487. it('should extract nested types', () => {
  2488. const result = extractFromSource('UTypes.pas', code);
  2489. const classes = result.nodes.filter((n) => n.kind === 'class');
  2490. expect(classes.map((c) => c.name)).toContain('TAddress');
  2491. });
  2492. });
  2493. });
  2494. // =============================================================================
  2495. // DFM/FMX Extraction
  2496. // =============================================================================
  2497. describe('DFM/FMX Extraction', () => {
  2498. it('should extract components from DFM', () => {
  2499. const code = `object Form1: TForm1
  2500. Left = 0
  2501. Top = 0
  2502. Caption = 'My Form'
  2503. object Button1: TButton
  2504. Left = 10
  2505. Top = 10
  2506. Caption = 'Click Me'
  2507. end
  2508. end`;
  2509. const result = extractFromSource('Form1.dfm', code);
  2510. const components = result.nodes.filter((n) => n.kind === 'component');
  2511. expect(components.length).toBe(2);
  2512. expect(components.map((c) => c.name)).toContain('Form1');
  2513. expect(components.map((c) => c.name)).toContain('Button1');
  2514. const button = components.find((c) => c.name === 'Button1');
  2515. expect(button?.signature).toBe('TButton');
  2516. });
  2517. it('should extract nested component hierarchy', () => {
  2518. const code = `object Form1: TForm1
  2519. object Panel1: TPanel
  2520. object Label1: TLabel
  2521. Caption = 'Hello'
  2522. end
  2523. end
  2524. end`;
  2525. const result = extractFromSource('Form1.dfm', code);
  2526. const components = result.nodes.filter((n) => n.kind === 'component');
  2527. expect(components.length).toBe(3);
  2528. // Check nesting: Panel1 contains Label1
  2529. const panel = components.find((c) => c.name === 'Panel1');
  2530. const label = components.find((c) => c.name === 'Label1');
  2531. const containsEdge = result.edges.find(
  2532. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2533. );
  2534. expect(containsEdge).toBeDefined();
  2535. });
  2536. it('should extract event handler references', () => {
  2537. const code = `object Form1: TForm1
  2538. OnCreate = FormCreate
  2539. OnDestroy = FormDestroy
  2540. object Button1: TButton
  2541. OnClick = Button1Click
  2542. end
  2543. end`;
  2544. const result = extractFromSource('Form1.dfm', code);
  2545. const refs = result.unresolvedReferences;
  2546. expect(refs.length).toBe(3);
  2547. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2548. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2549. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2550. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2551. });
  2552. it('should handle multi-line properties', () => {
  2553. const code = `object Form1: TForm1
  2554. SQL.Strings = (
  2555. 'SELECT * FROM users'
  2556. 'WHERE active = 1')
  2557. object Button1: TButton
  2558. OnClick = Button1Click
  2559. end
  2560. end`;
  2561. const result = extractFromSource('Form1.dfm', code);
  2562. const components = result.nodes.filter((n) => n.kind === 'component');
  2563. expect(components.length).toBe(2);
  2564. const refs = result.unresolvedReferences;
  2565. expect(refs.length).toBe(1);
  2566. expect(refs[0]?.referenceName).toBe('Button1Click');
  2567. });
  2568. it('should handle inherited keyword', () => {
  2569. const code = `inherited Form1: TForm1
  2570. Caption = 'Inherited Form'
  2571. object Button1: TButton
  2572. OnClick = Button1Click
  2573. end
  2574. end`;
  2575. const result = extractFromSource('Form1.dfm', code);
  2576. const components = result.nodes.filter((n) => n.kind === 'component');
  2577. expect(components.length).toBe(2);
  2578. expect(components.map((c) => c.name)).toContain('Form1');
  2579. });
  2580. it('should handle item collection properties', () => {
  2581. const code = `object Form1: TForm1
  2582. object StatusBar1: TStatusBar
  2583. Panels = <
  2584. item
  2585. Width = 200
  2586. end
  2587. item
  2588. Width = 200
  2589. end>
  2590. end
  2591. end`;
  2592. const result = extractFromSource('Form1.dfm', code);
  2593. const components = result.nodes.filter((n) => n.kind === 'component');
  2594. expect(components.length).toBe(2);
  2595. });
  2596. describe('Full fixture: MainForm.dfm', () => {
  2597. const code = `object frmMain: TfrmMain
  2598. Left = 0
  2599. Top = 0
  2600. Caption = 'CodeGraph DFM Fixture'
  2601. ClientHeight = 480
  2602. ClientWidth = 640
  2603. OnCreate = FormCreate
  2604. OnDestroy = FormDestroy
  2605. object pnlTop: TPanel
  2606. Left = 0
  2607. Top = 0
  2608. Width = 640
  2609. Height = 50
  2610. object lblTitle: TLabel
  2611. Left = 16
  2612. Top = 16
  2613. Caption = 'Authentication Service'
  2614. end
  2615. object btnLogin: TButton
  2616. Left = 540
  2617. Top = 12
  2618. OnClick = btnLoginClick
  2619. end
  2620. end
  2621. object pnlContent: TPanel
  2622. Left = 0
  2623. Top = 50
  2624. object edtUsername: TEdit
  2625. Left = 16
  2626. Top = 16
  2627. OnChange = edtUsernameChange
  2628. end
  2629. object edtPassword: TEdit
  2630. Left = 16
  2631. Top = 48
  2632. OnKeyPress = edtPasswordKeyPress
  2633. end
  2634. object mmoLog: TMemo
  2635. Left = 16
  2636. Top = 88
  2637. end
  2638. end
  2639. object pnlStatus: TStatusBar
  2640. Left = 0
  2641. Top = 440
  2642. Panels = <
  2643. item
  2644. Width = 200
  2645. end
  2646. item
  2647. Width = 200
  2648. end>
  2649. end
  2650. end`;
  2651. it('should extract all components', () => {
  2652. const result = extractFromSource('MainForm.dfm', code);
  2653. const components = result.nodes.filter((n) => n.kind === 'component');
  2654. expect(components.length).toBe(9);
  2655. expect(components.map((c) => c.name)).toEqual(
  2656. expect.arrayContaining([
  2657. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2658. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2659. ])
  2660. );
  2661. });
  2662. it('should extract all event handlers', () => {
  2663. const result = extractFromSource('MainForm.dfm', code);
  2664. const refs = result.unresolvedReferences;
  2665. expect(refs.length).toBe(5);
  2666. expect(refs.map((r) => r.referenceName)).toEqual(
  2667. expect.arrayContaining([
  2668. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2669. 'edtUsernameChange', 'edtPasswordKeyPress',
  2670. ])
  2671. );
  2672. });
  2673. });
  2674. });
  2675. describe('Kotlin Multiplatform expect/actual', () => {
  2676. let tempDir: string;
  2677. let cg: CodeGraph;
  2678. beforeEach(() => {
  2679. tempDir = createTempDir();
  2680. });
  2681. afterEach(() => {
  2682. if (cg) cg.close();
  2683. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2684. });
  2685. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  2686. const common = path.join(tempDir, 'src', 'commonMain');
  2687. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2688. fs.mkdirSync(common, { recursive: true });
  2689. fs.mkdirSync(jvm, { recursive: true });
  2690. // common source set: expect declarations + a caller that uses them
  2691. fs.writeFileSync(
  2692. path.join(common, 'SystemProps.kt'),
  2693. `package demo.internal
  2694. expect fun systemProp(name: String): String?
  2695. expect class Platform {
  2696. fun describe(): String
  2697. }
  2698. `
  2699. );
  2700. fs.writeFileSync(
  2701. path.join(common, 'Caller.kt'),
  2702. `package demo
  2703. import demo.internal.systemProp
  2704. import demo.internal.Platform
  2705. fun useIt(): String {
  2706. val v = systemProp("os.name")
  2707. return Platform().describe() + v
  2708. }
  2709. `
  2710. );
  2711. // jvm source set: actual implementations
  2712. fs.writeFileSync(
  2713. path.join(jvm, 'SystemProps.kt'),
  2714. `package demo.internal
  2715. actual fun systemProp(name: String): String? = System.getProperty(name)
  2716. actual class Platform {
  2717. actual fun describe(): String = "JVM"
  2718. }
  2719. `
  2720. );
  2721. cg = CodeGraph.initSync(tempDir);
  2722. await cg.indexAll();
  2723. cg.resolveReferences();
  2724. // The expect/actual markers are captured onto the node's decorators.
  2725. const fns = cg.getNodesByKind('function');
  2726. const actualFn = fns.find(
  2727. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  2728. );
  2729. const expectFn = fns.find(
  2730. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  2731. );
  2732. expect(actualFn).toBeDefined();
  2733. expect(expectFn).toBeDefined();
  2734. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  2735. // Editing the JVM actual must surface the common expect AND its caller —
  2736. // before the expect/actual bridge the actual had zero dependents.
  2737. const impact = cg.getImpactRadius(actualFn!.id, 3);
  2738. const impacted = [...impact.nodes.values()].map((n) => n.name);
  2739. expect(impacted).toContain('systemProp'); // the common expect
  2740. expect(impacted).toContain('useIt'); // the caller, reached transitively
  2741. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  2742. const bridge = impact.edges.find(
  2743. (e) =>
  2744. e.target === actualFn!.id &&
  2745. e.provenance === 'heuristic' &&
  2746. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2747. 'kotlin-expect-actual'
  2748. );
  2749. expect(bridge).toBeDefined();
  2750. expect(bridge!.source).toBe(expectFn!.id);
  2751. });
  2752. it('links an expect class to an actual typealias (different node kinds)', async () => {
  2753. const common = path.join(tempDir, 'src', 'commonMain');
  2754. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2755. fs.mkdirSync(common, { recursive: true });
  2756. fs.mkdirSync(jvm, { recursive: true });
  2757. fs.writeFileSync(
  2758. path.join(common, 'Lock.kt'),
  2759. `package demo
  2760. expect class Lock {
  2761. fun acquire()
  2762. }
  2763. `
  2764. );
  2765. fs.writeFileSync(
  2766. path.join(jvm, 'Lock.kt'),
  2767. `package demo
  2768. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  2769. `
  2770. );
  2771. cg = CodeGraph.initSync(tempDir);
  2772. await cg.indexAll();
  2773. cg.resolveReferences();
  2774. const aliasNode = cg
  2775. .getNodesByKind('type_alias')
  2776. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  2777. expect(aliasNode).toBeDefined();
  2778. // The actual typealias is now a cross-file dependency target (linked from
  2779. // the expect class), so it participates in impact rather than being orphaned.
  2780. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  2781. const bridge = impact.edges.find(
  2782. (e) =>
  2783. e.target === aliasNode!.id &&
  2784. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2785. 'kotlin-expect-actual'
  2786. );
  2787. expect(bridge).toBeDefined();
  2788. });
  2789. });
  2790. describe('Scala cross-file dependencies', () => {
  2791. let tempDir: string;
  2792. let cg: CodeGraph;
  2793. beforeEach(() => {
  2794. tempDir = createTempDir();
  2795. });
  2796. afterEach(() => {
  2797. if (cg) cg.close();
  2798. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2799. });
  2800. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  2801. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  2802. fs.mkdirSync(src, { recursive: true });
  2803. fs.writeFileSync(
  2804. path.join(src, 'Semigroup.scala'),
  2805. `package demo
  2806. trait Semigroup[A] {
  2807. def combine(x: A, y: A): A
  2808. }
  2809. `
  2810. );
  2811. fs.writeFileSync(
  2812. path.join(src, 'Monoid.scala'),
  2813. `package demo
  2814. trait Monoid[A] extends Semigroup[A] {
  2815. def empty: A
  2816. }
  2817. `
  2818. );
  2819. fs.writeFileSync(
  2820. path.join(src, 'Instances.scala'),
  2821. `package demo
  2822. object Instances {
  2823. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  2824. def empty: Int = 0
  2825. def combine(x: Int, y: Int): Int = x + y
  2826. }
  2827. }
  2828. `
  2829. );
  2830. fs.writeFileSync(
  2831. path.join(src, 'Folding.scala'),
  2832. `package demo
  2833. object Folding {
  2834. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  2835. xs.foldLeft(M.empty)(M.combine)
  2836. }
  2837. `
  2838. );
  2839. cg = CodeGraph.initSync(tempDir);
  2840. await cg.indexAll();
  2841. cg.resolveReferences();
  2842. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  2843. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  2844. expect(monoid).toBeDefined();
  2845. expect(semigroup).toBeDefined();
  2846. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  2847. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  2848. // the whole point of the fix (the `[A]` used to defeat name matching).
  2849. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  2850. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  2851. // Editing Monoid surfaces the cross-file users: the instance val typed
  2852. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  2853. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  2854. expect(impacted).toContain('intMonoid'); // field type annotation
  2855. expect(impacted).toContain('fold'); // trailing implicit parameter list
  2856. });
  2857. });
  2858. describe('PHP namespace + import resolution', () => {
  2859. let tempDir: string;
  2860. let cg: CodeGraph;
  2861. beforeEach(() => {
  2862. tempDir = createTempDir();
  2863. });
  2864. afterEach(() => {
  2865. if (cg) cg.close();
  2866. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2867. });
  2868. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  2869. const src = path.join(tempDir, 'src');
  2870. // Two interfaces with the SAME simple name in different namespaces — the
  2871. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  2872. // resolve. The namespace qualifies them; the `use` import disambiguates.
  2873. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  2874. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  2875. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  2876. fs.writeFileSync(
  2877. path.join(src, 'Cache', 'Factory.php'),
  2878. `<?php
  2879. namespace Contracts\\Cache;
  2880. interface Factory {
  2881. public function store(): object;
  2882. }
  2883. `
  2884. );
  2885. fs.writeFileSync(
  2886. path.join(src, 'Mail', 'Factory.php'),
  2887. `<?php
  2888. namespace Contracts\\Mail;
  2889. interface Factory {
  2890. public function mailer(): object;
  2891. }
  2892. `
  2893. );
  2894. fs.writeFileSync(
  2895. path.join(src, 'App', 'Service.php'),
  2896. `<?php
  2897. namespace App;
  2898. use Contracts\\Cache\\Factory;
  2899. class Service {
  2900. public function make(): Factory {
  2901. return resolve(Factory::class);
  2902. }
  2903. }
  2904. `
  2905. );
  2906. cg = CodeGraph.initSync(tempDir);
  2907. await cg.indexAll();
  2908. cg.resolveReferences();
  2909. // The PHP namespace is captured into the qualified name, so the two
  2910. // same-named interfaces are distinguishable.
  2911. const cacheFactory = cg
  2912. .getNodesByKind('interface')
  2913. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  2914. const mailFactory = cg
  2915. .getNodesByKind('interface')
  2916. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  2917. expect(cacheFactory).toBeDefined();
  2918. expect(mailFactory).toBeDefined();
  2919. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  2920. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  2921. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  2922. const serviceFile = 'src/App/Service.php';
  2923. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  2924. (n) => (n.filePath ?? '').endsWith(serviceFile)
  2925. );
  2926. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  2927. (n) => (n.filePath ?? '').endsWith(serviceFile)
  2928. );
  2929. expect(cacheReaches).toBe(true);
  2930. expect(mailReaches).toBe(false);
  2931. });
  2932. });
  2933. describe('Ruby mixins (include/extend/prepend)', () => {
  2934. let tempDir: string;
  2935. let cg: CodeGraph;
  2936. beforeEach(() => {
  2937. tempDir = createTempDir();
  2938. });
  2939. afterEach(() => {
  2940. if (cg) cg.close();
  2941. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2942. });
  2943. it('links include/extend/prepend to the mixed-in module across files', async () => {
  2944. const lib = path.join(tempDir, 'lib');
  2945. fs.mkdirSync(lib, { recursive: true });
  2946. fs.writeFileSync(
  2947. path.join(lib, 'concerns.rb'),
  2948. `module Trackable
  2949. def track; end
  2950. end
  2951. module Cacheable
  2952. def cache; end
  2953. end
  2954. module Loggable
  2955. def log; end
  2956. end
  2957. `
  2958. );
  2959. fs.writeFileSync(
  2960. path.join(lib, 'model.rb'),
  2961. `class Model
  2962. include Trackable
  2963. prepend Cacheable
  2964. extend Loggable
  2965. end
  2966. `
  2967. );
  2968. cg = CodeGraph.initSync(tempDir);
  2969. await cg.indexAll();
  2970. cg.resolveReferences();
  2971. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  2972. expect(model).toBeDefined();
  2973. // All three mixin forms create an `implements` edge Model → module, so
  2974. // editing a concern surfaces every class that mixes it in (across files).
  2975. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  2976. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  2977. expect(mod, moduleName).toBeDefined();
  2978. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  2979. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  2980. }
  2981. });
  2982. it('resolves require / require_relative to the required file', async () => {
  2983. const lib = path.join(tempDir, 'lib');
  2984. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  2985. // A leaf file whose class is referenced only dynamically — so without
  2986. // require resolution it would look like nothing depends on it.
  2987. fs.writeFileSync(
  2988. path.join(lib, 'app', 'fetcher.rb'),
  2989. `module App
  2990. class Fetcher
  2991. def fetch; end
  2992. end
  2993. end
  2994. `
  2995. );
  2996. // Pulled in by a load-path `require` …
  2997. fs.writeFileSync(
  2998. path.join(lib, 'app', 'worker.rb'),
  2999. `require "app/fetcher"
  3000. module App
  3001. class Worker; end
  3002. end
  3003. `
  3004. );
  3005. // … and a sibling pulled in by `require_relative`.
  3006. fs.writeFileSync(
  3007. path.join(lib, 'app', 'boot.rb'),
  3008. `require_relative "fetcher"
  3009. `
  3010. );
  3011. cg = CodeGraph.initSync(tempDir);
  3012. await cg.indexAll();
  3013. cg.resolveReferences();
  3014. // The require edges target fetcher.rb's FILE node. Editing it should reach
  3015. // BOTH the load-path requirer (worker.rb) and the require_relative one
  3016. // (boot.rb) — without require resolution its file would have no dependents.
  3017. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  3018. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  3019. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3020. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  3021. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  3022. });
  3023. });
  3024. describe('C++ free-function name extraction', () => {
  3025. let tempDir: string;
  3026. let cg: CodeGraph;
  3027. beforeEach(() => {
  3028. tempDir = createTempDir();
  3029. });
  3030. afterEach(() => {
  3031. if (cg) cg.close();
  3032. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3033. });
  3034. it('names a free function correctly when it has qualified-type params or a trailing return type', async () => {
  3035. const src = path.join(tempDir, 'src');
  3036. fs.mkdirSync(src, { recursive: true });
  3037. // TableFileName has a `const std::string&` parameter; BuildName uses an
  3038. // `auto … -> std::string` trailing return type. Both used to be named
  3039. // `string` (picked up from the parameter / return type), so callers never
  3040. // resolved and the defining file looked like nothing depended on it.
  3041. fs.writeFileSync(
  3042. path.join(src, 'names.cc'),
  3043. `#include <string>
  3044. std::string TableFileName(const std::string& dbname, int number) {
  3045. return dbname;
  3046. }
  3047. auto BuildName(const std::string& a) -> std::string {
  3048. return a;
  3049. }
  3050. `
  3051. );
  3052. fs.writeFileSync(
  3053. path.join(src, 'user.cc'),
  3054. `#include <string>
  3055. std::string use() {
  3056. return TableFileName("db", 1) + BuildName("x");
  3057. }
  3058. `
  3059. );
  3060. cg = CodeGraph.initSync(tempDir);
  3061. await cg.indexAll();
  3062. cg.resolveReferences();
  3063. // The functions are extracted under their real names, not `string`.
  3064. const fns = cg.getNodesByKind('function');
  3065. const tableFn = fns.find((n) => n.name === 'TableFileName');
  3066. const buildFn = fns.find((n) => n.name === 'BuildName');
  3067. expect(tableFn, 'TableFileName extracted (not "string")').toBeDefined();
  3068. expect(buildFn, 'BuildName extracted (not "string")').toBeDefined();
  3069. // And the cross-file calls resolve to them, so editing names.cc surfaces user.cc.
  3070. for (const fn of [tableFn!, buildFn!]) {
  3071. const reached = [...cg.getImpactRadius(fn.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3072. expect(reached.some((p) => p.endsWith('user.cc')), `${fn.name} should be called from user.cc`).toBe(true);
  3073. }
  3074. });
  3075. });
  3076. describe('Dart mixins and type references', () => {
  3077. let tempDir: string;
  3078. let cg: CodeGraph;
  3079. beforeEach(() => {
  3080. tempDir = createTempDir();
  3081. });
  3082. afterEach(() => {
  3083. if (cg) cg.close();
  3084. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3085. });
  3086. it('links `with` mixins and method parameter/return types across files', async () => {
  3087. const lib = path.join(tempDir, 'lib');
  3088. fs.mkdirSync(lib, { recursive: true });
  3089. fs.writeFileSync(
  3090. path.join(lib, 'models.dart'),
  3091. `class User {
  3092. final String name;
  3093. User(this.name);
  3094. }
  3095. mixin Loggable {
  3096. void log() {}
  3097. }
  3098. abstract class Repository {
  3099. User find(int id);
  3100. }
  3101. `
  3102. );
  3103. fs.writeFileSync(
  3104. path.join(lib, 'service.dart'),
  3105. `import 'models.dart';
  3106. class UserService extends Repository with Loggable {
  3107. @override
  3108. User find(int id) => User('x');
  3109. List<User> all() => [];
  3110. }
  3111. `
  3112. );
  3113. cg = CodeGraph.initSync(tempDir);
  3114. await cg.indexAll();
  3115. cg.resolveReferences();
  3116. const inModels = (name: string) =>
  3117. cg.getNodesByKind('class').concat(cg.getNodesByKind('module'))
  3118. .find((n) => n.name === name && n.filePath.endsWith('models.dart'));
  3119. // The `with Loggable` mixin records a dependency — editing the mixin surfaces
  3120. // the class that mixes it in (across files). Loggable is a `mixin`, indexed
  3121. // as a class-like node.
  3122. const loggable = cg.getNodesByKind('class').find((n) => n.name === 'Loggable')
  3123. ?? cg.getNodesByKind('module').find((n) => n.name === 'Loggable');
  3124. expect(loggable, 'Loggable mixin indexed').toBeDefined();
  3125. const mixinUsers = [...cg.getImpactRadius(loggable!.id, 3).nodes.values()].map((n) => n.name);
  3126. expect(mixinUsers).toContain('UserService');
  3127. // `User` is used only as a method parameter/return type in service.dart —
  3128. // editing it must still surface service.dart via the type references.
  3129. const user = inModels('User') ?? cg.getNodesByKind('class').find((n) => n.name === 'User');
  3130. expect(user, 'User indexed').toBeDefined();
  3131. const userDeps = [...cg.getImpactRadius(user!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3132. expect(userDeps.some((p) => p.endsWith('service.dart'))).toBe(true);
  3133. });
  3134. });
  3135. describe('Static-member / value-read references', () => {
  3136. let tempDir: string;
  3137. let cg: CodeGraph;
  3138. beforeEach(() => {
  3139. tempDir = createTempDir();
  3140. });
  3141. afterEach(() => {
  3142. if (cg) cg.close();
  3143. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3144. });
  3145. it('links a type referenced only via a static field / enum value (and ignores lowercase receivers)', async () => {
  3146. fs.writeFileSync(
  3147. path.join(tempDir, 'JsonScope.java'),
  3148. `class JsonScope {
  3149. static final int EMPTY_DOCUMENT = 1;
  3150. }
  3151. `
  3152. );
  3153. fs.writeFileSync(
  3154. path.join(tempDir, 'Reader.java'),
  3155. `class Reader {
  3156. private int helper;
  3157. int peek() {
  3158. return JsonScope.EMPTY_DOCUMENT;
  3159. }
  3160. int noop() {
  3161. return this.helper;
  3162. }
  3163. }
  3164. `
  3165. );
  3166. cg = CodeGraph.initSync(tempDir);
  3167. await cg.indexAll();
  3168. cg.resolveReferences();
  3169. // JsonScope is used ONLY as `JsonScope.EMPTY_DOCUMENT` (a static-field value
  3170. // read — never constructed or called), so before the static-member pass it
  3171. // had no dependents. Editing it now surfaces Reader.java.
  3172. const scope = cg.getNodesByKind('class').find((n) => n.name === 'JsonScope');
  3173. expect(scope, 'JsonScope indexed').toBeDefined();
  3174. const reached = [...cg.getImpactRadius(scope!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3175. expect(reached.some((p) => p.endsWith('Reader.java'))).toBe(true);
  3176. // A lowercase receiver (`this.helper`) must NOT be emitted as a type ref —
  3177. // only Capitalized receivers (types) are. No node named `this`/`helper`
  3178. // should appear as a reference target from peek/noop beyond JsonScope.
  3179. const refTargets = cg
  3180. .getNodesByKind('class')
  3181. .filter((n) => n.name === 'this' || n.name === 'helper');
  3182. expect(refTargets.length).toBe(0);
  3183. });
  3184. it('does not link a static-member read across language families (coincidental name)', async () => {
  3185. // A native (Kotlin) `Build.VERSION` reads the Android system class — it must
  3186. // NOT link to a coincidentally same-named TS class (the cross-language false
  3187. // positive that name-matching produces; `references` edges are language-local).
  3188. fs.writeFileSync(
  3189. path.join(tempDir, 'Build.ts'),
  3190. `export class Build {\n static version = 1;\n}\n`
  3191. );
  3192. fs.writeFileSync(
  3193. path.join(tempDir, 'Device.kt'),
  3194. `package app\nclass Device {\n fun sdk(): Int = Build.VERSION\n}\n`
  3195. );
  3196. cg = CodeGraph.initSync(tempDir);
  3197. await cg.indexAll();
  3198. cg.resolveReferences();
  3199. const tsBuild = cg.getNodesByKind('class').find((n) => n.name === 'Build' && n.filePath.endsWith('Build.ts'));
  3200. expect(tsBuild).toBeDefined();
  3201. // The Kotlin file is `app/Device.kt`; the TS Build must have NO dependent there.
  3202. const deps = [...cg.getImpactRadius(tsBuild!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3203. expect(deps.some((p) => p.endsWith('Device.kt'))).toBe(false);
  3204. });
  3205. });
  3206. describe('Cross-language type/import gate (RN name collisions)', () => {
  3207. let tempDir: string;
  3208. let cg: CodeGraph;
  3209. beforeEach(() => {
  3210. tempDir = createTempDir();
  3211. });
  3212. afterEach(() => {
  3213. if (cg) cg.close();
  3214. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3215. });
  3216. it('a TS PascalCase type ref lands on the TS type, never a same-named native class', async () => {
  3217. // react-native-async-storage's example app has a TS `type TestRunner` AND a
  3218. // Kotlin `class TestRunner`. The React PascalCase resolver name-matched the
  3219. // Kotlin `class` (its COMPONENT_KINDS includes `class`) with no language
  3220. // check at confidence 0.8, outranking the (cross-language-penalized 0.5)
  3221. // TS name-match — so a TS ref to `TestRunner` crossed web→jvm. The ref here
  3222. // is intentionally NOT imported: a clean relative import would mask the bug
  3223. // by resolving via the import map before the framework strategy can win.
  3224. fs.writeFileSync(
  3225. path.join(tempDir, 'package.json'),
  3226. JSON.stringify({ dependencies: { 'react-native': '*' } })
  3227. );
  3228. fs.writeFileSync(
  3229. path.join(tempDir, 'useTests.ts'),
  3230. `export type TestRunner = { run: () => void };\n`
  3231. );
  3232. fs.writeFileSync(
  3233. path.join(tempDir, 'basic.tsx'),
  3234. `export function useBasicTest(r: TestRunner): TestRunner {\n return r;\n}\n`
  3235. );
  3236. fs.writeFileSync(
  3237. path.join(tempDir, 'TestUtils.kt'),
  3238. `package app\nclass TestRunner {\n fun run() {}\n}\n`
  3239. );
  3240. cg = CodeGraph.initSync(tempDir);
  3241. await cg.indexAll();
  3242. cg.resolveReferences();
  3243. const ktRunner = cg
  3244. .getNodesByKind('class')
  3245. .find((n) => n.name === 'TestRunner' && n.filePath.endsWith('TestUtils.kt'));
  3246. expect(ktRunner, 'Kotlin TestRunner class').toBeDefined();
  3247. const ktDeps = [...cg.getImpactRadius(ktRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3248. expect(ktDeps.some((p) => p.endsWith('basic.tsx')), 'Kotlin class has NO TS dependent').toBe(false);
  3249. const tsRunner = cg.getNodesByKind('type_alias').find((n) => n.name === 'TestRunner');
  3250. expect(tsRunner, 'TS TestRunner type_alias').toBeDefined();
  3251. const tsDeps = [...cg.getImpactRadius(tsRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3252. expect(tsDeps.some((p) => p.endsWith('basic.tsx')), 'TS type captured the ref (re-pointed)').toBe(true);
  3253. });
  3254. it('gates a cross-family import name collision but keeps same-family imports', async () => {
  3255. // A TS `import { Widget }` that only matches a Swift `class Widget` must not
  3256. // create a web→apple dependency — but a sibling TS module imported by
  3257. // another TS file (same family) must still resolve (no over-gating).
  3258. fs.writeFileSync(path.join(tempDir, 'Widget.swift'), `class Widget {\n func render() {}\n}\n`);
  3259. fs.writeFileSync(
  3260. path.join(tempDir, 'widget.ts'),
  3261. `import { Widget } from './native';\nexport function mount(w: Widget) {}\n`
  3262. );
  3263. fs.writeFileSync(path.join(tempDir, 'util.ts'), `export class Helper {}\n`);
  3264. fs.writeFileSync(
  3265. path.join(tempDir, 'app.ts'),
  3266. `import { Helper } from './util';\nexport const h = new Helper();\n`
  3267. );
  3268. cg = CodeGraph.initSync(tempDir);
  3269. await cg.indexAll();
  3270. cg.resolveReferences();
  3271. const swiftWidget = cg
  3272. .getNodesByKind('class')
  3273. .find((n) => n.name === 'Widget' && n.filePath.endsWith('.swift'));
  3274. expect(swiftWidget, 'Swift Widget class').toBeDefined();
  3275. const wDeps = [...cg.getImpactRadius(swiftWidget!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3276. expect(wDeps.some((p) => p.endsWith('widget.ts')), 'Swift class has NO TS dependent').toBe(false);
  3277. // Same-family control — the TS Helper must still see its TS dependent.
  3278. const helper = cg.getNodesByKind('class').find((n) => n.name === 'Helper');
  3279. expect(helper, 'TS Helper class').toBeDefined();
  3280. const hDeps = [...cg.getImpactRadius(helper!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3281. expect(hDeps.some((p) => p.endsWith('app.ts')), 'same-family TS import preserved').toBe(true);
  3282. });
  3283. });
  3284. describe('Python absolute module import resolution', () => {
  3285. let tempDir: string;
  3286. let cg: CodeGraph;
  3287. beforeEach(() => {
  3288. tempDir = createTempDir();
  3289. });
  3290. afterEach(() => {
  3291. if (cg) cg.close();
  3292. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3293. });
  3294. it('links a bare `import pkg.module` of an internal module to its file', async () => {
  3295. // `import conduit.apps.signals` (a Django-style side-effect import, and any
  3296. // dotted absolute module import) had no edge to the module file — only
  3297. // `from x import y` was linked — so a module imported by its dotted path
  3298. // looked like nothing depended on it.
  3299. fs.mkdirSync(path.join(tempDir, 'conduit/apps'), { recursive: true });
  3300. fs.writeFileSync(path.join(tempDir, 'conduit/__init__.py'), '');
  3301. fs.writeFileSync(path.join(tempDir, 'conduit/apps/__init__.py'), '');
  3302. fs.writeFileSync(path.join(tempDir, 'conduit/apps/signals.py'), `def handler():\n pass\n`);
  3303. fs.writeFileSync(
  3304. path.join(tempDir, 'conduit/apps/app.py'),
  3305. `import conduit.apps.signals\nimport os\n\nVALUE = 1\n`
  3306. );
  3307. cg = CodeGraph.initSync(tempDir);
  3308. await cg.indexAll();
  3309. cg.resolveReferences();
  3310. const signals = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('conduit/apps/signals.py'));
  3311. expect(signals, 'signals.py indexed').toBeDefined();
  3312. const deps = [...cg.getImpactRadius(signals!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3313. expect(deps.some((p) => p.endsWith('app.py')), 'importer depends on the module').toBe(true);
  3314. // `import os` (stdlib) must NOT fabricate an edge — no os.py file in the repo.
  3315. const osNode = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('/os.py'));
  3316. expect(osNode, 'no stdlib os.py node').toBeUndefined();
  3317. });
  3318. it('Django include() links the root URLconf to the included app urls module', async () => {
  3319. // `url(r'^api/', include('app.urls'))` should record a dependency from the
  3320. // root urlconf onto the included app's `urls.py` — so editing an app's routes
  3321. // surfaces the project urlconf that mounts them.
  3322. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3323. fs.writeFileSync(path.join(tempDir, 'requirements.txt'), `django==4.0\n`);
  3324. fs.writeFileSync(path.join(tempDir, 'app/__init__.py'), '');
  3325. fs.writeFileSync(path.join(tempDir, 'app/views.py'), `def home(request):\n return None\n`);
  3326. fs.writeFileSync(
  3327. path.join(tempDir, 'app/urls.py'),
  3328. `from django.conf.urls import url\nfrom . import views\nurlpatterns = [url(r'^$', views.home)]\n`
  3329. );
  3330. fs.writeFileSync(
  3331. path.join(tempDir, 'urls.py'),
  3332. `from django.conf.urls import include, url\nurlpatterns = [url(r'^app/', include('app.urls'))]\n`
  3333. );
  3334. cg = CodeGraph.initSync(tempDir);
  3335. await cg.indexAll();
  3336. cg.resolveReferences();
  3337. const appUrls = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/urls.py'));
  3338. expect(appUrls, 'app/urls.py indexed').toBeDefined();
  3339. const deps = [...cg.getImpactRadius(appUrls!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3340. expect(deps.some((p) => p.endsWith('urls.py') && !p.endsWith('app/urls.py')), 'root urlconf depends on the included app urls').toBe(true);
  3341. });
  3342. it('resolves `from pkg import submodule` to the submodule under that package, not a same-named one', async () => {
  3343. // FastAPI router-aggregator pattern: `from app.api.routes import authentication`
  3344. // with same-named modules in sibling packages must resolve via the import's
  3345. // SOURCE (the package), not a coincidental same-basename file elsewhere.
  3346. fs.mkdirSync(path.join(tempDir, 'app/api/routes'), { recursive: true });
  3347. fs.mkdirSync(path.join(tempDir, 'app/api/dependencies'), { recursive: true });
  3348. for (const p of ['app/__init__.py', 'app/api/__init__.py', 'app/api/routes/__init__.py', 'app/api/dependencies/__init__.py']) {
  3349. fs.writeFileSync(path.join(tempDir, p), '');
  3350. }
  3351. fs.writeFileSync(path.join(tempDir, 'app/api/routes/authentication.py'), `def login():\n pass\n`);
  3352. fs.writeFileSync(path.join(tempDir, 'app/api/dependencies/authentication.py'), `def get_user():\n pass\n`);
  3353. fs.writeFileSync(
  3354. path.join(tempDir, 'app/api/routes/api.py'),
  3355. `from app.api.routes import authentication\n\nROUTER = authentication\n`
  3356. );
  3357. cg = CodeGraph.initSync(tempDir);
  3358. await cg.indexAll();
  3359. cg.resolveReferences();
  3360. const routesAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('routes/authentication.py'));
  3361. const depsAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('dependencies/authentication.py'));
  3362. expect(routesAuth && depsAuth).toBeTruthy();
  3363. const routesDeps = [...cg.getImpactRadius(routesAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3364. const depsDeps = [...cg.getImpactRadius(depsAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3365. expect(routesDeps.some((p) => p.endsWith('routes/api.py')), 'submodule under the imported package is the dependent').toBe(true);
  3366. expect(depsDeps.some((p) => p.endsWith('routes/api.py')), 'same-named module in a sibling package is NOT').toBe(false);
  3367. });
  3368. });
  3369. describe('Razor / Blazor markup extraction', () => {
  3370. let tempDir: string;
  3371. let cg: CodeGraph;
  3372. beforeEach(() => {
  3373. tempDir = createTempDir();
  3374. });
  3375. afterEach(() => {
  3376. if (cg) cg.close();
  3377. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3378. });
  3379. it('links @model and Blazor component tags to their C# types; ignores HTML elements', async () => {
  3380. fs.mkdirSync(path.join(tempDir, 'Views'), { recursive: true });
  3381. fs.writeFileSync(
  3382. path.join(tempDir, 'LoginViewModel.cs'),
  3383. `namespace App { public class LoginViewModel { public string Email { get; set; } } }`
  3384. );
  3385. fs.writeFileSync(
  3386. path.join(tempDir, 'ToastComponent.cs'),
  3387. `namespace App { public class ToastComponent { } }`
  3388. );
  3389. fs.writeFileSync(
  3390. path.join(tempDir, 'Views/Login.cshtml'),
  3391. `@model LoginViewModel\n<div class="form">\n <input asp-for="Email" />\n</div>\n`
  3392. );
  3393. fs.writeFileSync(
  3394. path.join(tempDir, 'Index.razor'),
  3395. `<div>\n <ToastComponent />\n</div>\n`
  3396. );
  3397. cg = CodeGraph.initSync(tempDir);
  3398. await cg.indexAll();
  3399. cg.resolveReferences();
  3400. // `@model LoginViewModel` → the view-model class.
  3401. const vm = cg.getNodesByKind('class').find((n) => n.name === 'LoginViewModel');
  3402. expect(vm, 'LoginViewModel class').toBeDefined();
  3403. const vmDeps = [...cg.getImpactRadius(vm!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3404. expect(vmDeps.some((p) => p.endsWith('Login.cshtml')), '@model links the view').toBe(true);
  3405. // `<ToastComponent />` → the component class.
  3406. const toast = cg.getNodesByKind('class').find((n) => n.name === 'ToastComponent');
  3407. expect(toast, 'ToastComponent class').toBeDefined();
  3408. const toastDeps = [...cg.getImpactRadius(toast!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3409. expect(toastDeps.some((p) => p.endsWith('Index.razor')), 'Blazor tag links the component').toBe(true);
  3410. // HTML elements (`<div>`, `<input>`) must NOT become component references.
  3411. const htmlNodes = cg.getNodesByKind('class').filter((n) => n.name === 'div' || n.name === 'input');
  3412. expect(htmlNodes.length, 'no node for HTML elements').toBe(0);
  3413. });
  3414. it('C# namespaces qualify type names so same-named types are distinct', async () => {
  3415. fs.writeFileSync(path.join(tempDir, 'entity.cs'), `namespace App.Entities { public class CatalogBrand { } }`);
  3416. fs.writeFileSync(path.join(tempDir, 'dto.cs'), `namespace App.Models { public class CatalogBrand { } }`);
  3417. cg = CodeGraph.initSync(tempDir);
  3418. await cg.indexAll();
  3419. const brands = cg.getNodesByKind('class').filter((n) => n.name === 'CatalogBrand');
  3420. expect(brands.length, 'both CatalogBrand classes indexed').toBe(2);
  3421. const qns = brands.map((b) => b.qualifiedName).sort();
  3422. expect(qns[0]).not.toBe(qns[1]); // distinct qualified names (namespace-scoped)
  3423. expect(qns.some((q) => q.includes('Entities') && q.endsWith('CatalogBrand'))).toBe(true);
  3424. expect(qns.some((q) => q.includes('Models') && q.endsWith('CatalogBrand'))).toBe(true);
  3425. });
  3426. it('disambiguates a Razor type ref via @using (incl. folder _Imports.razor)', async () => {
  3427. // `CatalogBrand` exists as both a domain entity and a DTO; the component
  3428. // `@using`s the DTO's namespace (here via the folder _Imports.razor), so the
  3429. // ref must resolve to the DTO, not the same-named entity.
  3430. fs.mkdirSync(path.join(tempDir, 'Models'), { recursive: true });
  3431. fs.mkdirSync(path.join(tempDir, 'Entities'), { recursive: true });
  3432. fs.mkdirSync(path.join(tempDir, 'Pages'), { recursive: true });
  3433. fs.writeFileSync(path.join(tempDir, 'Models/CatalogBrand.cs'), `namespace App.Models { public class CatalogBrand { public int Id { get; set; } } }`);
  3434. fs.writeFileSync(path.join(tempDir, 'Entities/CatalogBrand.cs'), `namespace App.Entities { public class CatalogBrand { public int Id { get; set; } } }`);
  3435. fs.writeFileSync(path.join(tempDir, 'Pages/_Imports.razor'), `@using App.Models\n`);
  3436. fs.writeFileSync(
  3437. path.join(tempDir, 'Pages/List.razor'),
  3438. `<h1>List</h1>\n@code {\n private CatalogBrand _b = new CatalogBrand();\n}\n`
  3439. );
  3440. cg = CodeGraph.initSync(tempDir);
  3441. await cg.indexAll();
  3442. cg.resolveReferences();
  3443. const dto = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Models::CatalogBrand');
  3444. const entity = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Entities::CatalogBrand');
  3445. expect(dto && entity, 'both CatalogBrand classes').toBeTruthy();
  3446. const dtoDeps = [...cg.getImpactRadius(dto!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3447. const entityDeps = [...cg.getImpactRadius(entity!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3448. expect(dtoDeps.some((p) => p.endsWith('List.razor')), 'resolves to the @using\'d DTO').toBe(true);
  3449. expect(entityDeps.some((p) => p.endsWith('List.razor')), 'NOT the same-named entity').toBe(false);
  3450. });
  3451. it('delegates Blazor @code block C# to cover types used in component logic', async () => {
  3452. fs.writeFileSync(
  3453. path.join(tempDir, 'CatalogService.cs'),
  3454. `namespace App { public class CatalogService { public void Load() { } } }`
  3455. );
  3456. fs.writeFileSync(
  3457. path.join(tempDir, 'List.razor'),
  3458. `<h1>Catalog</h1>\n\n@code {\n private CatalogService _svc = new CatalogService();\n void Refresh() { _svc.Load(); }\n}\n`
  3459. );
  3460. cg = CodeGraph.initSync(tempDir);
  3461. await cg.indexAll();
  3462. cg.resolveReferences();
  3463. const svc = cg.getNodesByKind('class').find((n) => n.name === 'CatalogService');
  3464. expect(svc, 'CatalogService class').toBeDefined();
  3465. const deps = [...cg.getImpactRadius(svc!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3466. expect(deps.some((p) => p.endsWith('List.razor')), '@code usage links the component to the service').toBe(true);
  3467. });
  3468. });
  3469. describe('Default import resolution (renamed default export)', () => {
  3470. let tempDir: string;
  3471. let cg: CodeGraph;
  3472. beforeEach(() => {
  3473. tempDir = createTempDir();
  3474. });
  3475. afterEach(() => {
  3476. if (cg) cg.close();
  3477. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3478. });
  3479. it('links a renamed default import to the module file', async () => {
  3480. // Express route aggregator: `import articlesController from './controller'`
  3481. // where the module does `export default router`. The renamed local can't be
  3482. // found as a symbol, so the controller file had no dependent — the dependency
  3483. // is on the module file regardless of the default export's name.
  3484. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  3485. fs.writeFileSync(path.join(tempDir, 'app/controller.ts'), `const router = { get() {} };\nexport default router;\n`);
  3486. fs.writeFileSync(path.join(tempDir, 'app/routes.ts'), `import myController from './controller';\nexport const api = myController;\n`);
  3487. cg = CodeGraph.initSync(tempDir);
  3488. await cg.indexAll();
  3489. cg.resolveReferences();
  3490. const controller = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/controller.ts'));
  3491. expect(controller, 'controller.ts indexed').toBeDefined();
  3492. const deps = [...cg.getImpactRadius(controller!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3493. expect(deps.some((p) => p.endsWith('routes.ts')), 'importer depends on the default-exporting module').toBe(true);
  3494. });
  3495. });
  3496. describe('Chained method-call resolution (C# extension methods)', () => {
  3497. let tempDir: string;
  3498. let cg: CodeGraph;
  3499. beforeEach(() => {
  3500. tempDir = createTempDir();
  3501. });
  3502. afterEach(() => {
  3503. if (cg) cg.close();
  3504. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3505. });
  3506. it('resolves a chained extension-method call (a.b.Method()) to its definition', async () => {
  3507. // ASP.NET DI registration: `builder.Services.AddCoreServices(...)` calls a
  3508. // static extension method elsewhere. A multi-dot receiver chain matched no
  3509. // method-call pattern before, so the extension method had no caller.
  3510. fs.mkdirSync(path.join(tempDir, 'cfg'), { recursive: true });
  3511. fs.writeFileSync(
  3512. path.join(tempDir, 'cfg/Ext.cs'),
  3513. `namespace App {\n public static class Ext {\n public static object AddCoreServices(this object services, int x) { return services; }\n }\n}\n`
  3514. );
  3515. fs.writeFileSync(
  3516. path.join(tempDir, 'Program.cs'),
  3517. `namespace App {\n public class Program {\n public void Run(object builder) {\n builder.Services.AddCoreServices(1);\n }\n }\n}\n`
  3518. );
  3519. cg = CodeGraph.initSync(tempDir);
  3520. await cg.indexAll();
  3521. cg.resolveReferences();
  3522. const ext = cg
  3523. .getNodesByKind('method')
  3524. .find((n) => n.name === 'AddCoreServices')
  3525. ?? cg.getNodesByKind('function').find((n) => n.name === 'AddCoreServices');
  3526. expect(ext, 'AddCoreServices defined').toBeDefined();
  3527. const callers = [...cg.getImpactRadius(ext!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3528. expect(callers.some((p) => p.endsWith('Program.cs')), 'chained extension call resolves to its definition').toBe(true);
  3529. });
  3530. });
  3531. describe('Same-directory include + KMP import resolution', () => {
  3532. let tempDir: string;
  3533. let cg: CodeGraph;
  3534. beforeEach(() => {
  3535. tempDir = createTempDir();
  3536. });
  3537. afterEach(() => {
  3538. if (cg) cg.close();
  3539. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3540. });
  3541. it('a C/C++ #include resolves to the same-directory header, not a same-named one elsewhere', async () => {
  3542. // A multi-platform native module has a header of the same basename per
  3543. // platform. `windows/Provider.cpp`'s `#include "Storage.h"` means its OWN
  3544. // sibling header — not `apple/Storage.h` (which sorts first and so was
  3545. // picked arbitrarily before, leaving the real local header with 0 deps).
  3546. fs.mkdirSync(path.join(tempDir, 'apple'), { recursive: true });
  3547. fs.mkdirSync(path.join(tempDir, 'windows'), { recursive: true });
  3548. fs.writeFileSync(path.join(tempDir, 'apple', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3549. fs.writeFileSync(path.join(tempDir, 'windows', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  3550. fs.writeFileSync(
  3551. path.join(tempDir, 'windows', 'Provider.cpp'),
  3552. `#include "Storage.h"\nint use() { Storage s; return s.n; }\n`
  3553. );
  3554. cg = CodeGraph.initSync(tempDir);
  3555. await cg.indexAll();
  3556. cg.resolveReferences();
  3557. const winHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('windows/Storage.h'));
  3558. const appleHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('apple/Storage.h'));
  3559. expect(winHeader, 'windows/Storage.h indexed').toBeDefined();
  3560. expect(appleHeader, 'apple/Storage.h indexed').toBeDefined();
  3561. const winDeps = [...cg.getImpactRadius(winHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3562. const appleDeps = [...cg.getImpactRadius(appleHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3563. expect(winDeps.some((p) => p.endsWith('Provider.cpp')), 'same-dir header gets the includer').toBe(true);
  3564. expect(appleDeps.some((p) => p.endsWith('Provider.cpp')), 'other-platform header does NOT').toBe(false);
  3565. });
  3566. it('a Kotlin Multiplatform commonMain import resolves to the expect, not a platform actual', async () => {
  3567. const common = path.join(tempDir, 'src/commonMain/kotlin/app');
  3568. const android = path.join(tempDir, 'src/androidMain/kotlin/app');
  3569. fs.mkdirSync(common, { recursive: true });
  3570. fs.mkdirSync(android, { recursive: true });
  3571. fs.writeFileSync(path.join(common, 'Platform.kt'), `package app\nexpect class PlatformContext\n`);
  3572. fs.writeFileSync(path.join(android, 'Platform.android.kt'), `package app\nactual class PlatformContext\n`);
  3573. fs.writeFileSync(
  3574. path.join(common, 'Db.kt'),
  3575. `package app\nimport app.PlatformContext\nclass Db {\n fun open(ctx: PlatformContext) {}\n}\n`
  3576. );
  3577. cg = CodeGraph.initSync(tempDir);
  3578. await cg.indexAll();
  3579. cg.resolveReferences();
  3580. const expectCtx = cg
  3581. .getNodesByKind('class')
  3582. .find((n) => n.name === 'PlatformContext' && n.filePath.endsWith('commonMain/kotlin/app/Platform.kt'));
  3583. expect(expectCtx, 'commonMain expect PlatformContext').toBeDefined();
  3584. const deps = [...cg.getImpactRadius(expectCtx!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3585. expect(deps.some((p) => p.endsWith('Db.kt')), 'commonMain import lands on the expect, not the actual').toBe(true);
  3586. });
  3587. });
  3588. describe('Delphi form code-behind pairing', () => {
  3589. let tempDir: string;
  3590. let cg: CodeGraph;
  3591. beforeEach(() => {
  3592. tempDir = createTempDir();
  3593. });
  3594. afterEach(() => {
  3595. if (cg) cg.close();
  3596. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3597. });
  3598. it('links a `.dfm` form to its sibling `.pas` code-behind unit', async () => {
  3599. // A Delphi form unit owns its visual form definition via `{$R *.dfm}`, not a
  3600. // `uses` clause — so a `.dfm` used only as a form definition looked orphaned.
  3601. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.dfm'),
  3602. `object FRMAbout: TFRMAbout\n Caption = 'About'\nend\n`);
  3603. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.pas'),
  3604. `unit UFRMAbout;\ninterface\nuses Forms;\ntype\n TFRMAbout = class(TForm)\n end;\nimplementation\n{$R *.dfm}\nend.\n`);
  3605. cg = CodeGraph.initSync(tempDir);
  3606. await cg.indexAll();
  3607. cg.resolveReferences();
  3608. const dfm = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('UFRMAbout.dfm'));
  3609. expect(dfm, 'UFRMAbout.dfm file node').toBeDefined();
  3610. const deps = cg.getFileDependents(dfm!.filePath);
  3611. expect(deps.some((p) => p.endsWith('UFRMAbout.pas')), 'the .pas unit links its .dfm form').toBe(true);
  3612. });
  3613. });
  3614. describe('Liquid Shopify JSON template section resolution', () => {
  3615. let tempDir: string;
  3616. let cg: CodeGraph;
  3617. beforeEach(() => {
  3618. tempDir = createTempDir();
  3619. });
  3620. afterEach(() => {
  3621. if (cg) cg.close();
  3622. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3623. });
  3624. it('links a Shopify JSON template section `type` to its sections/<type>.liquid', async () => {
  3625. // Shopify OS 2.0 templates are JSON, referencing sections by `type` — not
  3626. // a `{% section %}` Liquid tag — so a section used only from a JSON template
  3627. // looked unused. The JSON is now indexed and its `type`s linked.
  3628. fs.mkdirSync(path.join(tempDir, 'sections'), { recursive: true });
  3629. fs.mkdirSync(path.join(tempDir, 'templates/customers'), { recursive: true });
  3630. fs.writeFileSync(path.join(tempDir, 'sections/main-product.liquid'), `<div>{{ product.title }}</div>\n`);
  3631. fs.writeFileSync(path.join(tempDir, 'sections/main-login.liquid'), `<form>{{ 'customer.login' | t }}</form>\n`);
  3632. fs.writeFileSync(path.join(tempDir, 'templates/product.json'), JSON.stringify({ sections: { main: { type: 'main-product' } }, order: ['main'] }));
  3633. // Nested template dir (templates/customers/login.json) must resolve too.
  3634. fs.writeFileSync(path.join(tempDir, 'templates/customers/login.json'), JSON.stringify({ sections: { main: { type: 'main-login' } }, order: ['main'] }));
  3635. cg = CodeGraph.initSync(tempDir);
  3636. await cg.indexAll();
  3637. cg.resolveReferences();
  3638. const product = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-product.liquid'));
  3639. const login = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-login.liquid'));
  3640. expect(product, 'main-product section').toBeDefined();
  3641. expect(login, 'main-login section').toBeDefined();
  3642. expect(cg.getFileDependents(product!.filePath).some((p) => p.endsWith('templates/product.json')), 'top-level JSON template links its section').toBe(true);
  3643. expect(cg.getFileDependents(login!.filePath).some((p) => p.endsWith('customers/login.json')), 'nested JSON template links its section').toBe(true);
  3644. });
  3645. });
  3646. describe('Lua/Luau require resolution', () => {
  3647. let tempDir: string;
  3648. let cg: CodeGraph;
  3649. beforeEach(() => {
  3650. tempDir = createTempDir();
  3651. });
  3652. afterEach(() => {
  3653. if (cg) cg.close();
  3654. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3655. });
  3656. it('resolves a dotted Lua require and an instance-path Luau require to their module files', async () => {
  3657. // The require is the ONLY link (no method call), so coverage here proves the
  3658. // require resolver specifically, not method-call name-matching.
  3659. // Lua dotted module path: require("myapp.config") → lua/myapp/config.lua.
  3660. fs.mkdirSync(path.join(tempDir, 'lua/myapp'), { recursive: true });
  3661. fs.writeFileSync(path.join(tempDir, 'lua/myapp/config.lua'), `local M = {}\nfunction M.setup() end\nreturn M\n`);
  3662. fs.writeFileSync(path.join(tempDir, 'lua/myapp/init.lua'), `local config = require("myapp.config")\nreturn config\n`);
  3663. // Luau Roblox instance-path require (only the leaf survives extraction):
  3664. // require(script.Util.helper) → src/Util/helper.luau.
  3665. fs.mkdirSync(path.join(tempDir, 'src/Util'), { recursive: true });
  3666. fs.writeFileSync(path.join(tempDir, 'src/Util/helper.luau'), `local H = {}\nfunction H.go() end\nreturn H\n`);
  3667. fs.writeFileSync(path.join(tempDir, 'src/init.luau'), `local helper = require(script.Util.helper)\nreturn helper\n`);
  3668. cg = CodeGraph.initSync(tempDir);
  3669. await cg.indexAll();
  3670. cg.resolveReferences();
  3671. const config = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('myapp/config.lua'));
  3672. const helper = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('Util/helper.luau'));
  3673. expect(config, 'config.lua file node').toBeDefined();
  3674. expect(helper, 'helper.luau file node').toBeDefined();
  3675. const cfgDeps = cg.getFileDependents(config!.filePath);
  3676. const helpDeps = cg.getFileDependents(helper!.filePath);
  3677. expect(cfgDeps.some((p) => p.endsWith('myapp/init.lua')), 'dotted Lua require resolves to the module').toBe(true);
  3678. expect(helpDeps.some((p) => p.endsWith('src/init.luau')), 'instance-path Luau require resolves to the module').toBe(true);
  3679. });
  3680. });
  3681. describe('Rust module-path call resolution', () => {
  3682. let tempDir: string;
  3683. let cg: CodeGraph;
  3684. beforeEach(() => {
  3685. tempDir = createTempDir();
  3686. });
  3687. afterEach(() => {
  3688. if (cg) cg.close();
  3689. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3690. });
  3691. it('a bare submodule call (`users::router()`) resolves self-relative to the submodule fn', async () => {
  3692. // The canonical Axum router-assembly pattern: a parent module calls each
  3693. // submodule's `router()`. `users::` / `profiles::` are SELF-relative
  3694. // submodule prefixes (2018 edition) — `mod users;` makes `users` a child of
  3695. // the CURRENT module, NOT `crate::users`. Before the fix the bare prefix was
  3696. // resolved crate-relative only (looking for `src/users.rs`), so it found
  3697. // nothing and the handler modules looked dependent-less.
  3698. const http = path.join(tempDir, 'src/http');
  3699. fs.mkdirSync(http, { recursive: true });
  3700. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod http;\n`);
  3701. fs.writeFileSync(
  3702. path.join(http, 'mod.rs'),
  3703. `mod users;\nmod profiles;\npub fn api_router() {\n users::router();\n profiles::router();\n}\n`
  3704. );
  3705. fs.writeFileSync(path.join(http, 'users.rs'), `pub fn router() -> i32 { 1 }\n`);
  3706. fs.writeFileSync(path.join(http, 'profiles.rs'), `pub fn router() -> i32 { 2 }\n`);
  3707. cg = CodeGraph.initSync(tempDir);
  3708. await cg.indexAll();
  3709. cg.resolveReferences();
  3710. // Each submodule's same-named `router` fn must get mod.rs as a dependent —
  3711. // proving the bare prefix resolved self-relative AND disambiguated the
  3712. // colliding `router` name to the correct file (not an arbitrary one).
  3713. const routers = cg.getNodesByKind('function').filter((n) => n.name === 'router');
  3714. const usersRouter = routers.find((n) => n.filePath.endsWith('http/users.rs'));
  3715. const profilesRouter = routers.find((n) => n.filePath.endsWith('http/profiles.rs'));
  3716. expect(usersRouter, 'users.rs router fn').toBeDefined();
  3717. expect(profilesRouter, 'profiles.rs router fn').toBeDefined();
  3718. const usersDeps = [...cg.getImpactRadius(usersRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3719. const profilesDeps = [...cg.getImpactRadius(profilesRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3720. expect(usersDeps.some((p) => p.endsWith('http/mod.rs')), 'users::router() lands on users.rs').toBe(true);
  3721. expect(profilesDeps.some((p) => p.endsWith('http/mod.rs')), 'profiles::router() lands on profiles.rs').toBe(true);
  3722. });
  3723. it('a 3-segment module-path call (`database::profiles::find()`) resolves to the leaf fn', async () => {
  3724. // A 2-level module path — the common `db.run(move |c| database::profiles::find(c))`
  3725. // / `crate::a::b::func()` shape. The reference-resolver pre-filter used to drop any
  3726. // `a::b::c` whose leaf it never checked (it tested only the first segment and the
  3727. // `b::c` remainder, neither of which names a symbol), so the call never reached the
  3728. // Rust path resolver and the leaf module looked dependent-less.
  3729. const routes = path.join(tempDir, 'src/routes');
  3730. const database = path.join(tempDir, 'src/database');
  3731. fs.mkdirSync(routes, { recursive: true });
  3732. fs.mkdirSync(database, { recursive: true });
  3733. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod routes;\npub mod database;\n`);
  3734. fs.writeFileSync(path.join(database, 'mod.rs'), `pub mod profiles;\n`);
  3735. fs.writeFileSync(path.join(database, 'profiles.rs'), `pub fn find(id: i32) -> i32 { id }\n`);
  3736. fs.writeFileSync(
  3737. path.join(routes, 'mod.rs'),
  3738. `use crate::database;\npub fn get_profile(id: i32) -> i32 {\n database::profiles::find(id)\n}\n`
  3739. );
  3740. cg = CodeGraph.initSync(tempDir);
  3741. await cg.indexAll();
  3742. cg.resolveReferences();
  3743. const find = cg
  3744. .getNodesByKind('function')
  3745. .find((n) => n.name === 'find' && n.filePath.endsWith('database/profiles.rs'));
  3746. expect(find, 'database/profiles.rs find fn').toBeDefined();
  3747. const deps = [...cg.getImpactRadius(find!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3748. expect(deps.some((p) => p.endsWith('routes/mod.rs')), 'database::profiles::find() resolves to the leaf fn').toBe(true);
  3749. });
  3750. it('Rocket `routes![…]` / `catchers![…]` macros link the mount to the handler fns', async () => {
  3751. // Tree-sitter leaves the macro body as a raw token tree, so the handler
  3752. // paths inside `routes![a::b::handler, …]` are invisible to the call walker
  3753. // and the handlers — mounted by Rocket at runtime, not called in-repo — look
  3754. // like they have no caller. The route-macro extractor reconstructs each path
  3755. // and emits a reference, which the Rust path resolver links to the handler.
  3756. const routes = path.join(tempDir, 'src/routes');
  3757. fs.mkdirSync(routes, { recursive: true });
  3758. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'),
  3759. `mod routes;\nfn not_found() {}\npub fn rocket() {\n` +
  3760. ` rocket::build()\n` +
  3761. ` .mount("/api", routes![routes::users::post_users, routes::users::get_user])\n` +
  3762. ` .register("/", catchers![not_found]);\n}\n`);
  3763. fs.writeFileSync(path.join(routes, 'mod.rs'), `pub mod users;\n`);
  3764. fs.writeFileSync(path.join(routes, 'users.rs'), `pub fn post_users() {}\npub fn get_user() {}\n`);
  3765. cg = CodeGraph.initSync(tempDir);
  3766. await cg.indexAll();
  3767. cg.resolveReferences();
  3768. const handlers = cg.getNodesByKind('function').filter((n) => n.filePath.endsWith('routes/users.rs'));
  3769. expect(handlers.length, 'both handler fns indexed').toBe(2);
  3770. for (const h of handlers) {
  3771. const deps = [...cg.getImpactRadius(h.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3772. expect(deps.some((p) => p.endsWith('lib.rs')), `routes![] links ${h.name} to its mount in lib.rs`).toBe(true);
  3773. }
  3774. });
  3775. });
  3776. describe('SvelteKit load → page synthesizer', () => {
  3777. let tempDir: string;
  3778. let cg: CodeGraph;
  3779. beforeEach(() => {
  3780. tempDir = createTempDir();
  3781. });
  3782. afterEach(() => {
  3783. if (cg) cg.close();
  3784. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3785. });
  3786. it('links a +page.svelte to its OWN directory\'s +page.server.js load, not another route\'s', async () => {
  3787. // SvelteKit wires +page.server.js's `load` to +page.svelte's `data` BY FILE
  3788. // PATH — there is no static import — so editing a loader showed no impact on
  3789. // the page it feeds. The synthesizer links each page component to the `load`
  3790. // in its OWN directory (path-deterministic, so it never crosses routes).
  3791. const login = path.join(tempDir, 'src/routes/login');
  3792. const register = path.join(tempDir, 'src/routes/register');
  3793. fs.mkdirSync(login, { recursive: true });
  3794. fs.mkdirSync(register, { recursive: true });
  3795. fs.writeFileSync(path.join(login, '+page.svelte'), `<script>export let data;</script>\n<h1>Login {data.x}</h1>\n`);
  3796. fs.writeFileSync(path.join(login, '+page.server.js'), `export function load() { return { x: 1 }; }\n`);
  3797. fs.writeFileSync(path.join(register, '+page.svelte'), `<script>export let data;</script>\n<h1>Register</h1>\n`);
  3798. fs.writeFileSync(path.join(register, '+page.server.js'), `export function load() { return { y: 2 }; }\n`);
  3799. cg = CodeGraph.initSync(tempDir);
  3800. await cg.indexAll();
  3801. cg.resolveReferences();
  3802. const loginLoad = cg
  3803. .getNodesByKind('function')
  3804. .find((n) => n.name === 'load' && n.filePath.endsWith('login/+page.server.js'));
  3805. expect(loginLoad, 'login load fn').toBeDefined();
  3806. const impacted = [...cg.getImpactRadius(loginLoad!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3807. // editing login's load surfaces login's page (the framework-wired data flow)…
  3808. expect(impacted.some((p) => p.endsWith('login/+page.svelte')), 'load links to its own page').toBe(true);
  3809. // …but never register's page (same-directory only).
  3810. expect(impacted.some((p) => p.endsWith('register/+page.svelte')), 'does not cross routes').toBe(false);
  3811. });
  3812. });
  3813. describe('Nuxt nested auto-imported component resolution', () => {
  3814. let tempDir: string;
  3815. let cg: CodeGraph;
  3816. beforeEach(() => {
  3817. tempDir = createTempDir();
  3818. });
  3819. afterEach(() => {
  3820. if (cg) cg.close();
  3821. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3822. });
  3823. it('links a `<MediaCard/>` usage to components/media/Card.vue (Nuxt dir-prefixed auto-import)', async () => {
  3824. // Nuxt auto-imports a nested component by a DIRECTORY-PREFIXED name —
  3825. // components/media/Card.vue is used as <MediaCard/>, not <Card/> — but the
  3826. // component node is named by basename (`Card`), so the PascalCase usage
  3827. // didn't resolve and the nested component looked unused.
  3828. const media = path.join(tempDir, 'components/media');
  3829. fs.mkdirSync(media, { recursive: true });
  3830. fs.writeFileSync(path.join(media, 'Card.vue'), `<template><div>card</div></template>\n<script setup>defineProps(['item'])</script>\n`);
  3831. fs.writeFileSync(
  3832. path.join(tempDir, 'components/Grid.vue'),
  3833. `<template>\n <div><MediaCard :item="i" /></div>\n</template>\n<script setup>const i = {}</script>\n`
  3834. );
  3835. cg = CodeGraph.initSync(tempDir);
  3836. await cg.indexAll();
  3837. cg.resolveReferences();
  3838. const card = cg.getNodesByKind('component').find((n) => n.filePath.endsWith('media/Card.vue'));
  3839. expect(card, 'media/Card.vue component').toBeDefined();
  3840. const deps = [...cg.getImpactRadius(card!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3841. expect(deps.some((p) => p.endsWith('components/Grid.vue')), '<MediaCard> links Grid to media/Card.vue').toBe(true);
  3842. });
  3843. });
  3844. describe('Swift property-wrapper attribute type references', () => {
  3845. let tempDir: string;
  3846. let cg: CodeGraph;
  3847. beforeEach(() => {
  3848. tempDir = createTempDir();
  3849. });
  3850. afterEach(() => {
  3851. if (cg) cg.close();
  3852. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3853. });
  3854. it('a Fluent `@Siblings(through: Pivot.self)` links the model to the pivot type', async () => {
  3855. // A many-to-many pivot/join model is referenced ONLY through the relationship
  3856. // property wrapper's metatype argument (`Pivot.self`), never by a controller
  3857. // query. The wrapper type was captured but the argument expression wasn't
  3858. // walked, so the pivot model looked like nothing depended on it.
  3859. fs.writeFileSync(path.join(tempDir, 'Pivot.swift'),
  3860. `import Fluent\nfinal class AcronymCategoryPivot: Model {\n static let schema = "acronym-category"\n}\n`);
  3861. fs.writeFileSync(path.join(tempDir, 'Acronym.swift'),
  3862. `import Fluent\nfinal class Acronym: Model {\n` +
  3863. ` @Siblings(through: AcronymCategoryPivot.self, from: \\.$acronym, to: \\.$category)\n` +
  3864. ` var categories: [Category]\n}\n`);
  3865. cg = CodeGraph.initSync(tempDir);
  3866. await cg.indexAll();
  3867. cg.resolveReferences();
  3868. const pivot = cg.getNodesByKind('class').find((n) => n.name === 'AcronymCategoryPivot');
  3869. expect(pivot, 'pivot model class').toBeDefined();
  3870. const deps = [...cg.getImpactRadius(pivot!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3871. expect(deps.some((p) => p.endsWith('Acronym.swift')), '@Siblings metatype arg links Acronym to the pivot').toBe(true);
  3872. });
  3873. });
  3874. describe('Objective-C messages, class receivers, and #import', () => {
  3875. let tempDir: string;
  3876. let cg: CodeGraph;
  3877. beforeEach(() => {
  3878. tempDir = createTempDir();
  3879. });
  3880. afterEach(() => {
  3881. if (cg) cg.close();
  3882. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3883. });
  3884. it('resolves single-arg selectors, class-message receivers, and #import headers', async () => {
  3885. fs.writeFileSync(
  3886. path.join(tempDir, 'SDImageCache.h'),
  3887. `#import <Foundation/Foundation.h>
  3888. @interface SDImageCache : NSObject
  3889. + (instancetype)sharedCache;
  3890. + (void)storeImage:(NSString *)key;
  3891. @end
  3892. `
  3893. );
  3894. fs.writeFileSync(
  3895. path.join(tempDir, 'SDImageCache.m'),
  3896. `#import "SDImageCache.h"
  3897. @implementation SDImageCache
  3898. + (instancetype)sharedCache { return nil; }
  3899. + (void)storeImage:(NSString *)key { }
  3900. @end
  3901. `
  3902. );
  3903. fs.writeFileSync(
  3904. path.join(tempDir, 'SDManager.m'),
  3905. `#import "SDImageCache.h"
  3906. @interface SDManager : NSObject
  3907. @end
  3908. @implementation SDManager
  3909. - (void)run {
  3910. [SDImageCache sharedCache];
  3911. [SDImageCache storeImage:@"k"];
  3912. }
  3913. @end
  3914. `
  3915. );
  3916. cg = CodeGraph.initSync(tempDir);
  3917. await cg.indexAll();
  3918. cg.resolveReferences();
  3919. // 1. The single-argument selector `[SDImageCache storeImage:@"k"]` resolves
  3920. // to the `storeImage:` method — named WITH its colon both at the call site
  3921. // and the definition (before the fix the call site dropped the colon).
  3922. const storeImage = cg.getNodesByKind('method').find((n) => n.name === 'storeImage:');
  3923. expect(storeImage, 'storeImage: method').toBeDefined();
  3924. const storeCallers = [...cg.getImpactRadius(storeImage!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3925. expect(storeCallers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3926. // 2. The class-message receiver `[SDImageCache sharedCache]` references the
  3927. // SDImageCache class (whose @interface lives in the header).
  3928. const cache = cg.getNodesByKind('class').find((n) => n.name === 'SDImageCache');
  3929. expect(cache, 'SDImageCache class').toBeDefined();
  3930. const classDeps = [...cg.getImpactRadius(cache!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3931. expect(classDeps.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3932. // 3. `#import "SDImageCache.h"` resolves to the header FILE — editing it
  3933. // surfaces both importers.
  3934. const header = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('SDImageCache.h'));
  3935. expect(header, 'SDImageCache.h indexed').toBeDefined();
  3936. const importers = [...cg.getImpactRadius(header!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3937. expect(importers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  3938. });
  3939. });
  3940. describe('Full Indexing', () => {
  3941. let tempDir: string;
  3942. beforeEach(() => {
  3943. tempDir = createTempDir();
  3944. });
  3945. afterEach(() => {
  3946. cleanupTempDir(tempDir);
  3947. });
  3948. it('should index a TypeScript file', async () => {
  3949. // Create test file
  3950. const srcDir = path.join(tempDir, 'src');
  3951. fs.mkdirSync(srcDir);
  3952. fs.writeFileSync(
  3953. path.join(srcDir, 'utils.ts'),
  3954. `
  3955. export function add(a: number, b: number): number {
  3956. return a + b;
  3957. }
  3958. export function multiply(a: number, b: number): number {
  3959. return a * b;
  3960. }
  3961. `
  3962. );
  3963. // Initialize and index
  3964. const cg = CodeGraph.initSync(tempDir);
  3965. const result = await cg.indexAll();
  3966. expect(result.success).toBe(true);
  3967. expect(result.filesIndexed).toBe(1);
  3968. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  3969. // Check nodes were stored
  3970. const nodes = cg.getNodesInFile('src/utils.ts');
  3971. expect(nodes.length).toBeGreaterThanOrEqual(2);
  3972. const addFunc = nodes.find((n) => n.name === 'add');
  3973. expect(addFunc).toBeDefined();
  3974. expect(addFunc?.kind).toBe('function');
  3975. cg.close();
  3976. });
  3977. it('should index multiple files', async () => {
  3978. // Create test files
  3979. const srcDir = path.join(tempDir, 'src');
  3980. fs.mkdirSync(srcDir);
  3981. fs.writeFileSync(
  3982. path.join(srcDir, 'math.ts'),
  3983. `export function add(a: number, b: number) { return a + b; }`
  3984. );
  3985. fs.writeFileSync(
  3986. path.join(srcDir, 'string.ts'),
  3987. `export function capitalize(s: string) { return s.toUpperCase(); }`
  3988. );
  3989. // Initialize and index
  3990. const cg = CodeGraph.initSync(tempDir);
  3991. const result = await cg.indexAll();
  3992. expect(result.success).toBe(true);
  3993. expect(result.filesIndexed).toBe(2);
  3994. const files = cg.getFiles();
  3995. expect(files.length).toBe(2);
  3996. cg.close();
  3997. });
  3998. it('should track file hashes for incremental updates', async () => {
  3999. // Create initial file
  4000. const srcDir = path.join(tempDir, 'src');
  4001. fs.mkdirSync(srcDir);
  4002. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  4003. // Initialize and index
  4004. const cg = CodeGraph.initSync(tempDir);
  4005. await cg.indexAll();
  4006. // Check file is tracked
  4007. const file = cg.getFile('src/main.ts');
  4008. expect(file).toBeDefined();
  4009. expect(file?.contentHash).toBeDefined();
  4010. // Modify file
  4011. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  4012. // Check for changes
  4013. const changes = cg.getChangedFiles();
  4014. expect(changes.modified).toContain('src/main.ts');
  4015. cg.close();
  4016. });
  4017. it('should sync and detect changes', async () => {
  4018. // Create initial file
  4019. const srcDir = path.join(tempDir, 'src');
  4020. fs.mkdirSync(srcDir);
  4021. fs.writeFileSync(
  4022. path.join(srcDir, 'main.ts'),
  4023. `export function original() { return 1; }`
  4024. );
  4025. // Initialize and index
  4026. const cg = CodeGraph.initSync(tempDir);
  4027. await cg.indexAll();
  4028. const initialNodes = cg.getNodesInFile('src/main.ts');
  4029. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  4030. // Modify file
  4031. fs.writeFileSync(
  4032. path.join(srcDir, 'main.ts'),
  4033. `export function updated() { return 2; }`
  4034. );
  4035. // Sync
  4036. const syncResult = await cg.sync();
  4037. expect(syncResult.filesModified).toBe(1);
  4038. // Check nodes were updated
  4039. const updatedNodes = cg.getNodesInFile('src/main.ts');
  4040. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  4041. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  4042. cg.close();
  4043. });
  4044. it('should count file-level tracked YAML files as indexed', async () => {
  4045. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4046. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  4047. const cg = CodeGraph.initSync(tempDir);
  4048. const result = await cg.indexAll();
  4049. expect(result.success).toBe(true);
  4050. expect(result.filesIndexed).toBe(2);
  4051. expect(result.filesSkipped).toBe(0);
  4052. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  4053. cg.close();
  4054. });
  4055. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  4056. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4057. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4058. const cg = CodeGraph.initSync(tempDir);
  4059. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  4060. expect(result.success).toBe(true);
  4061. expect(result.filesIndexed).toBe(2);
  4062. expect(result.filesSkipped).toBe(0);
  4063. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4064. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  4065. cg.close();
  4066. });
  4067. it('should count file-level tracked .properties files as indexed', async () => {
  4068. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4069. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  4070. const cg = CodeGraph.initSync(tempDir);
  4071. const result = await cg.indexAll();
  4072. expect(result.success).toBe(true);
  4073. expect(result.filesIndexed).toBe(2);
  4074. expect(result.filesSkipped).toBe(0);
  4075. cg.close();
  4076. });
  4077. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  4078. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4079. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4080. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4081. const cg = CodeGraph.initSync(tempDir);
  4082. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  4083. expect(result.success).toBe(true);
  4084. expect(result.filesIndexed).toBe(3);
  4085. expect(result.filesSkipped).toBe(0);
  4086. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4087. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  4088. cg.close();
  4089. });
  4090. });
  4091. describe('Path Normalization', () => {
  4092. it('should convert backslashes to forward slashes', () => {
  4093. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  4094. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  4095. });
  4096. it('should leave forward-slash paths unchanged', () => {
  4097. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  4098. });
  4099. it('should handle empty string', () => {
  4100. expect(normalizePath('')).toBe('');
  4101. });
  4102. });
  4103. describe('Directory Exclusion', () => {
  4104. let tempDir: string;
  4105. beforeEach(() => {
  4106. tempDir = createTempDir();
  4107. });
  4108. afterEach(() => {
  4109. cleanupTempDir(tempDir);
  4110. });
  4111. it('should exclude directories listed in .gitignore', () => {
  4112. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  4113. const srcDir = path.join(tempDir, 'src');
  4114. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  4115. fs.mkdirSync(srcDir, { recursive: true });
  4116. fs.mkdirSync(nmDir, { recursive: true });
  4117. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4118. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4119. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4120. const files = scanDirectory(tempDir);
  4121. expect(files).toContain('src/index.ts');
  4122. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4123. });
  4124. it('should exclude nested node_modules via a root .gitignore', () => {
  4125. // A trailing-slash pattern with no leading slash matches at any depth.
  4126. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  4127. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  4128. fs.mkdirSync(srcDir, { recursive: true });
  4129. fs.mkdirSync(nmDir, { recursive: true });
  4130. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4131. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4132. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4133. const files = scanDirectory(tempDir);
  4134. expect(files).toContain('packages/app/src/index.ts');
  4135. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4136. });
  4137. it('should apply a nested .gitignore only to its own subtree', () => {
  4138. const appSrc = path.join(tempDir, 'app', 'src');
  4139. fs.mkdirSync(appSrc, { recursive: true });
  4140. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  4141. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  4142. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  4143. // A sibling with the same name outside app/ must NOT be ignored.
  4144. const otherDir = path.join(tempDir, 'other', 'src');
  4145. fs.mkdirSync(otherDir, { recursive: true });
  4146. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  4147. const files = scanDirectory(tempDir);
  4148. expect(files).toContain('app/src/keep.ts');
  4149. expect(files).not.toContain('app/src/skip.ts');
  4150. expect(files).toContain('other/src/skip.ts');
  4151. });
  4152. it('should always skip .git directories', () => {
  4153. const srcDir = path.join(tempDir, 'src');
  4154. const gitDir = path.join(tempDir, '.git', 'objects');
  4155. fs.mkdirSync(srcDir, { recursive: true });
  4156. fs.mkdirSync(gitDir, { recursive: true });
  4157. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4158. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  4159. const files = scanDirectory(tempDir);
  4160. expect(files).toContain('src/index.ts');
  4161. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  4162. });
  4163. it('should return forward-slash paths on all platforms', () => {
  4164. const srcDir = path.join(tempDir, 'src', 'components');
  4165. fs.mkdirSync(srcDir, { recursive: true });
  4166. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  4167. const files = scanDirectory(tempDir);
  4168. expect(files.length).toBe(1);
  4169. expect(files[0]).toBe('src/components/Button.tsx');
  4170. expect(files[0]).not.toContain('\\');
  4171. });
  4172. });
  4173. describe('Git Submodules', () => {
  4174. let tempDir: string;
  4175. beforeEach(() => {
  4176. tempDir = createTempDir();
  4177. });
  4178. afterEach(() => {
  4179. cleanupTempDir(tempDir);
  4180. });
  4181. it('should index files inside git submodules (issue #147)', async () => {
  4182. const { execFileSync } = await import('child_process');
  4183. const git = (cwd: string, ...args: string[]) =>
  4184. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4185. // Build a separate "library" repo to use as a submodule source.
  4186. const libDir = path.join(tempDir, '_lib');
  4187. fs.mkdirSync(libDir, { recursive: true });
  4188. git(libDir, 'init', '-q');
  4189. git(libDir, 'config', 'user.email', 'test@test.com');
  4190. git(libDir, 'config', 'user.name', 'Test');
  4191. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  4192. git(libDir, 'add', '-A');
  4193. git(libDir, 'commit', '-q', '-m', 'lib init');
  4194. // Build the main repo and add the lib repo as a submodule.
  4195. const mainDir = path.join(tempDir, 'main');
  4196. fs.mkdirSync(mainDir, { recursive: true });
  4197. git(mainDir, 'init', '-q');
  4198. git(mainDir, 'config', 'user.email', 'test@test.com');
  4199. git(mainDir, 'config', 'user.name', 'Test');
  4200. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  4201. git(mainDir, 'add', '-A');
  4202. git(mainDir, 'commit', '-q', '-m', 'app init');
  4203. // protocol.file.allow=always is required to add a local-path submodule on
  4204. // recent git versions (CVE-2022-39253 mitigation).
  4205. execFileSync(
  4206. 'git',
  4207. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  4208. { cwd: mainDir, stdio: 'pipe' }
  4209. );
  4210. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  4211. const files = scanDirectory(mainDir);
  4212. expect(files).toContain('app.ts');
  4213. expect(files).toContain('libs/lib/lib.ts');
  4214. });
  4215. });
  4216. describe('Nested non-submodule git repos', () => {
  4217. let tempDir: string;
  4218. beforeEach(() => {
  4219. tempDir = createTempDir();
  4220. });
  4221. afterEach(() => {
  4222. cleanupTempDir(tempDir);
  4223. });
  4224. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  4225. const { execFileSync } = await import('child_process');
  4226. const git = (cwd: string, ...args: string[]) =>
  4227. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4228. // Top-level workspace is itself a git repo, holding no source directly —
  4229. // the CMake "super-repo" layout from the issue.
  4230. const root = path.join(tempDir, 'root');
  4231. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  4232. git(root, 'init', '-q');
  4233. git(root, 'config', 'user.email', 'test@test.com');
  4234. git(root, 'config', 'user.name', 'Test');
  4235. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  4236. // Two independent clones living inside the workspace (NOT submodules):
  4237. // one with committed source, one with only untracked source.
  4238. const sub1 = path.join(root, 'sub_repo1', 'src');
  4239. fs.mkdirSync(sub1, { recursive: true });
  4240. git(path.join(root, 'sub_repo1'), 'init', '-q');
  4241. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  4242. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  4243. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  4244. git(path.join(root, 'sub_repo1'), 'add', '-A');
  4245. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  4246. const sub2 = path.join(root, 'sub_repo2', 'src');
  4247. fs.mkdirSync(sub2, { recursive: true });
  4248. git(path.join(root, 'sub_repo2'), 'init', '-q');
  4249. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  4250. const files = scanDirectory(root);
  4251. // Both committed and untracked source from the nested repos must be found.
  4252. expect(files).toContain('sub_repo1/src/one.ts');
  4253. expect(files).toContain('sub_repo2/src/two.ts');
  4254. });
  4255. it('should respect each embedded repo\'s own .gitignore', async () => {
  4256. const { execFileSync } = await import('child_process');
  4257. const git = (cwd: string, ...args: string[]) =>
  4258. execFileSync('git', args, { cwd, stdio: 'pipe' });
  4259. const root = path.join(tempDir, 'root');
  4260. fs.mkdirSync(root, { recursive: true });
  4261. git(root, 'init', '-q');
  4262. const sub = path.join(root, 'sub_repo', 'src');
  4263. fs.mkdirSync(sub, { recursive: true });
  4264. git(path.join(root, 'sub_repo'), 'init', '-q');
  4265. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  4266. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  4267. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  4268. const files = scanDirectory(root);
  4269. expect(files).toContain('sub_repo/src/real.ts');
  4270. expect(files).not.toContain('sub_repo/src/generated.ts');
  4271. });
  4272. });
  4273. // =============================================================================
  4274. // Scala
  4275. // =============================================================================
  4276. describe('Scala Extraction', () => {
  4277. describe('Language detection', () => {
  4278. it('should detect Scala files', () => {
  4279. expect(detectLanguage('Main.scala')).toBe('scala');
  4280. expect(detectLanguage('script.sc')).toBe('scala');
  4281. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  4282. });
  4283. it('should report Scala as supported', () => {
  4284. expect(isLanguageSupported('scala')).toBe(true);
  4285. expect(getSupportedLanguages()).toContain('scala');
  4286. });
  4287. });
  4288. describe('Class extraction', () => {
  4289. it('should extract class definitions', () => {
  4290. const code = `
  4291. class UserService(private val repo: UserRepository) {
  4292. def findUser(id: String): Option[String] = Some(id)
  4293. }
  4294. `;
  4295. const result = extractFromSource('UserService.scala', code);
  4296. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  4297. expect(cls).toBeDefined();
  4298. expect(cls?.language).toBe('scala');
  4299. });
  4300. it('should extract object definitions as class kind', () => {
  4301. const code = `
  4302. object DatabaseConfig {
  4303. val url = "jdbc:postgresql://localhost/mydb"
  4304. }
  4305. `;
  4306. const result = extractFromSource('Config.scala', code);
  4307. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  4308. expect(obj).toBeDefined();
  4309. });
  4310. it('should extract trait definitions as trait kind', () => {
  4311. const code = `
  4312. trait Repository[A] {
  4313. def findById(id: String): Option[A]
  4314. def save(entity: A): Unit
  4315. }
  4316. `;
  4317. const result = extractFromSource('Repository.scala', code);
  4318. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  4319. expect(trait_).toBeDefined();
  4320. });
  4321. });
  4322. describe('Method and function extraction', () => {
  4323. it('should extract method definitions inside a class', () => {
  4324. const code = `
  4325. class Calculator {
  4326. def add(a: Int, b: Int): Int = a + b
  4327. def divide(a: Double, b: Double): Double = a / b
  4328. }
  4329. `;
  4330. const result = extractFromSource('Calculator.scala', code);
  4331. const methods = result.nodes.filter((n) => n.kind === 'method');
  4332. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  4333. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  4334. });
  4335. it('should extract method signatures', () => {
  4336. const code = `
  4337. class Greeter {
  4338. def greet(name: String): String = s"Hello, \${name}!"
  4339. }
  4340. `;
  4341. const result = extractFromSource('Greeter.scala', code);
  4342. const method = result.nodes.find((n) => n.name === 'greet');
  4343. expect(method?.signature).toContain('name: String');
  4344. expect(method?.signature).toContain('String');
  4345. });
  4346. it('should extract top-level function definitions as functions', () => {
  4347. const code = `
  4348. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  4349. def greet(name: String): String = s"Hello, \${name}!"
  4350. `;
  4351. const result = extractFromSource('utils.scala', code);
  4352. const fns = result.nodes.filter((n) => n.kind === 'function');
  4353. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  4354. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  4355. });
  4356. });
  4357. describe('Val and var extraction', () => {
  4358. it('should extract val inside a class as field', () => {
  4359. const code = `
  4360. class Config {
  4361. val timeout: Int = 30
  4362. val host: String = "localhost"
  4363. }
  4364. `;
  4365. const result = extractFromSource('Config.scala', code);
  4366. const fields = result.nodes.filter((n) => n.kind === 'field');
  4367. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  4368. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  4369. });
  4370. it('should extract var inside a class as field', () => {
  4371. const code = `
  4372. class Counter {
  4373. var count: Int = 0
  4374. }
  4375. `;
  4376. const result = extractFromSource('Counter.scala', code);
  4377. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  4378. expect(field).toBeDefined();
  4379. });
  4380. it('should extract top-level val as constant', () => {
  4381. const code = `
  4382. val MaxConnections: Int = 100
  4383. val DefaultTimeout = 30
  4384. `;
  4385. const result = extractFromSource('constants.scala', code);
  4386. const consts = result.nodes.filter((n) => n.kind === 'constant');
  4387. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  4388. });
  4389. it('should extract top-level var as variable', () => {
  4390. const code = `
  4391. var retries: Int = 3
  4392. `;
  4393. const result = extractFromSource('state.scala', code);
  4394. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  4395. expect(v).toBeDefined();
  4396. });
  4397. it('should include type in val/var signature', () => {
  4398. const code = `
  4399. class Service {
  4400. val timeout: Int = 30
  4401. }
  4402. `;
  4403. const result = extractFromSource('Service.scala', code);
  4404. const field = result.nodes.find((n) => n.name === 'timeout');
  4405. expect(field?.signature).toContain('timeout');
  4406. expect(field?.signature).toContain('Int');
  4407. });
  4408. });
  4409. describe('Enum extraction', () => {
  4410. it('should extract enum definitions', () => {
  4411. const code = `
  4412. enum Color:
  4413. case Red
  4414. case Green
  4415. case Blue
  4416. `;
  4417. const result = extractFromSource('Color.scala', code);
  4418. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  4419. expect(enumNode).toBeDefined();
  4420. });
  4421. it('should extract enum cases as enum_member', () => {
  4422. const code = `
  4423. enum Direction:
  4424. case North
  4425. case South
  4426. case East
  4427. case West
  4428. `;
  4429. const result = extractFromSource('Direction.scala', code);
  4430. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  4431. expect(members.find((m) => m.name === 'North')).toBeDefined();
  4432. expect(members.find((m) => m.name === 'South')).toBeDefined();
  4433. expect(members.length).toBeGreaterThanOrEqual(4);
  4434. });
  4435. });
  4436. describe('Type alias extraction', () => {
  4437. it('should extract type aliases', () => {
  4438. const code = `
  4439. type UserId = String
  4440. type UserMap = Map[String, String]
  4441. `;
  4442. const result = extractFromSource('types.scala', code);
  4443. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  4444. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  4445. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  4446. });
  4447. });
  4448. describe('Import extraction', () => {
  4449. it('should extract import declarations', () => {
  4450. const code = `
  4451. import scala.collection.mutable.ListBuffer
  4452. import scala.concurrent.Future
  4453. `;
  4454. const result = extractFromSource('imports.scala', code);
  4455. const imports = result.nodes.filter((n) => n.kind === 'import');
  4456. expect(imports.length).toBeGreaterThanOrEqual(2);
  4457. });
  4458. });
  4459. describe('Visibility modifiers', () => {
  4460. it('should extract private visibility', () => {
  4461. const code = `
  4462. class Service {
  4463. private val secret: String = "abc"
  4464. private def helper(): Unit = {}
  4465. }
  4466. `;
  4467. const result = extractFromSource('Service.scala', code);
  4468. const secretField = result.nodes.find((n) => n.name === 'secret');
  4469. expect(secretField?.visibility).toBe('private');
  4470. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  4471. expect(helperMethod?.visibility).toBe('private');
  4472. });
  4473. it('should extract protected visibility', () => {
  4474. const code = `
  4475. class Base {
  4476. protected def helperMethod(): Unit = {}
  4477. }
  4478. `;
  4479. const result = extractFromSource('Base.scala', code);
  4480. const method = result.nodes.find((n) => n.name === 'helperMethod');
  4481. expect(method?.visibility).toBe('protected');
  4482. });
  4483. it('should default to public visibility', () => {
  4484. const code = `
  4485. class Greeter {
  4486. def hello(): Unit = {}
  4487. }
  4488. `;
  4489. const result = extractFromSource('Greeter.scala', code);
  4490. const method = result.nodes.find((n) => n.name === 'hello');
  4491. expect(method?.visibility).toBe('public');
  4492. });
  4493. });
  4494. describe('Inheritance', () => {
  4495. it('should extract extends relationships', () => {
  4496. const code = `
  4497. class AdminUser extends User {
  4498. def adminAction(): Unit = {}
  4499. }
  4500. `;
  4501. const result = extractFromSource('AdminUser.scala', code);
  4502. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  4503. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  4504. });
  4505. });
  4506. describe('Call extraction', () => {
  4507. it('should extract function call expressions', () => {
  4508. const code = `
  4509. def processData(): Unit = {
  4510. val result = computeResult()
  4511. println(result)
  4512. }
  4513. `;
  4514. const result = extractFromSource('processor.scala', code);
  4515. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  4516. expect(calls.length).toBeGreaterThan(0);
  4517. });
  4518. });
  4519. });
  4520. describe('Vue Extraction', () => {
  4521. it('should detect Vue files', () => {
  4522. expect(detectLanguage('App.vue')).toBe('vue');
  4523. expect(detectLanguage('components/Button.vue')).toBe('vue');
  4524. expect(isLanguageSupported('vue')).toBe(true);
  4525. });
  4526. it('should extract component node from a Vue SFC', () => {
  4527. const code = `<template>
  4528. <div>{{ message }}</div>
  4529. </template>
  4530. <script>
  4531. export default {
  4532. data() {
  4533. return { message: 'Hello' };
  4534. }
  4535. }
  4536. </script>
  4537. `;
  4538. const result = extractFromSource('HelloWorld.vue', code);
  4539. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4540. expect(componentNode).toBeDefined();
  4541. expect(componentNode?.name).toBe('HelloWorld');
  4542. expect(componentNode?.language).toBe('vue');
  4543. expect(componentNode?.isExported).toBe(true);
  4544. });
  4545. it('should extract functions from <script> block', () => {
  4546. const code = `<template>
  4547. <button @click="handleClick">Click</button>
  4548. </template>
  4549. <script>
  4550. function handleClick() {
  4551. console.log('clicked');
  4552. }
  4553. const count = 0;
  4554. </script>
  4555. `;
  4556. const result = extractFromSource('Button.vue', code);
  4557. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4558. expect(componentNode).toBeDefined();
  4559. expect(componentNode?.name).toBe('Button');
  4560. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  4561. expect(funcNode).toBeDefined();
  4562. expect(funcNode?.language).toBe('vue');
  4563. });
  4564. it('should extract from <script setup lang="ts"> block', () => {
  4565. const code = `<template>
  4566. <div>{{ count }}</div>
  4567. </template>
  4568. <script setup lang="ts">
  4569. import { ref } from 'vue';
  4570. const count = ref(0);
  4571. function increment(): void {
  4572. count.value++;
  4573. }
  4574. </script>
  4575. `;
  4576. const result = extractFromSource('Counter.vue', code);
  4577. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4578. expect(componentNode).toBeDefined();
  4579. expect(componentNode?.name).toBe('Counter');
  4580. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  4581. expect(funcNode).toBeDefined();
  4582. expect(funcNode?.language).toBe('vue');
  4583. // All nodes should be marked as vue language
  4584. for (const node of result.nodes) {
  4585. expect(node.language).toBe('vue');
  4586. }
  4587. });
  4588. it('should extract calls from top-level <script setup> initializers', () => {
  4589. const code = `<template>
  4590. <div>{{ token }}</div>
  4591. </template>
  4592. <script setup lang="ts">
  4593. import { getTokenMp } from './api/upload';
  4594. const token = getTokenMp();
  4595. </script>
  4596. `;
  4597. const result = extractFromSource('Issue425Setup.vue', code);
  4598. const call = result.unresolvedReferences.find(
  4599. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  4600. );
  4601. expect(call).toBeDefined();
  4602. });
  4603. it('should extract calls from Vue Options API object methods', () => {
  4604. const code = `<template>
  4605. <button @click="save">Save</button>
  4606. </template>
  4607. <script>
  4608. import { getTokenMp } from './api/upload';
  4609. export default {
  4610. methods: {
  4611. save() {
  4612. return getTokenMp();
  4613. }
  4614. },
  4615. setup() {
  4616. return getTokenMp();
  4617. }
  4618. }
  4619. </script>
  4620. `;
  4621. const result = extractFromSource('Issue425Options.vue', code);
  4622. const calls = result.unresolvedReferences.filter(
  4623. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  4624. );
  4625. expect(calls).toHaveLength(2);
  4626. });
  4627. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  4628. const code = `<template>
  4629. <div class="wrap">
  4630. <UserCard :user="u" />
  4631. <my-button>Click</my-button>
  4632. <Transition><span>x</span></Transition>
  4633. </div>
  4634. </template>
  4635. <script setup lang="ts">
  4636. import UserCard from './UserCard.vue';
  4637. import MyButton from './MyButton.vue';
  4638. </script>
  4639. `;
  4640. const result = extractFromSource('Host.vue', code);
  4641. const refs = result.unresolvedReferences
  4642. .filter((r) => r.referenceKind === 'references')
  4643. .map((r) => r.referenceName);
  4644. expect(refs).toContain('UserCard'); // PascalCase tag
  4645. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  4646. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  4647. expect(refs).not.toContain('Div'); // native HTML element skipped
  4648. expect(refs).not.toContain('Span');
  4649. });
  4650. it('should extract from both <script> and <script setup> blocks', () => {
  4651. const code = `<template>
  4652. <div>{{ msg }}</div>
  4653. </template>
  4654. <script>
  4655. export default {
  4656. name: 'DualScript'
  4657. }
  4658. </script>
  4659. <script setup>
  4660. const msg = 'hello';
  4661. function greet() {
  4662. return msg;
  4663. }
  4664. </script>
  4665. `;
  4666. const result = extractFromSource('DualScript.vue', code);
  4667. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4668. expect(componentNode).toBeDefined();
  4669. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  4670. expect(greetFunc).toBeDefined();
  4671. });
  4672. it('should create component node for template-only Vue file', () => {
  4673. const code = `<template>
  4674. <div>Static content</div>
  4675. </template>
  4676. `;
  4677. const result = extractFromSource('Static.vue', code);
  4678. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4679. expect(componentNode).toBeDefined();
  4680. expect(componentNode?.name).toBe('Static');
  4681. expect(componentNode?.language).toBe('vue');
  4682. // Only the component node should exist (no script nodes)
  4683. expect(result.nodes.length).toBe(1);
  4684. });
  4685. it('should create containment edges from component to script nodes', () => {
  4686. const code = `<template>
  4687. <div>{{ value }}</div>
  4688. </template>
  4689. <script setup lang="ts">
  4690. const value = 42;
  4691. </script>
  4692. `;
  4693. const result = extractFromSource('Contained.vue', code);
  4694. const componentNode = result.nodes.find((n) => n.kind === 'component');
  4695. expect(componentNode).toBeDefined();
  4696. // Should have containment edges from component to child nodes
  4697. const containEdges = result.edges.filter(
  4698. (e) => e.source === componentNode!.id && e.kind === 'contains'
  4699. );
  4700. expect(containEdges.length).toBeGreaterThan(0);
  4701. });
  4702. });
  4703. describe('Instantiates + Decorates edge extraction', () => {
  4704. it('emits an instantiates ref for `new Foo()`', () => {
  4705. const code = `
  4706. class Foo {}
  4707. function bootstrap() { return new Foo(); }
  4708. `;
  4709. const result = extractFromSource('app.ts', code);
  4710. const ref = result.unresolvedReferences.find(
  4711. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  4712. );
  4713. expect(ref).toBeDefined();
  4714. });
  4715. it('strips type-argument suffix from generic constructors', () => {
  4716. const code = `
  4717. class Container<T> { constructor(_: T) {} }
  4718. function go() { return new Container<string>('x'); }
  4719. `;
  4720. const result = extractFromSource('app.ts', code);
  4721. const ref = result.unresolvedReferences.find(
  4722. (r) => r.referenceKind === 'instantiates'
  4723. );
  4724. expect(ref).toBeDefined();
  4725. // Container<string> must be normalised to "Container" — otherwise
  4726. // resolution can never match the class node.
  4727. expect(ref!.referenceName).toBe('Container');
  4728. });
  4729. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  4730. const code = `
  4731. const ns = { Foo: class {} };
  4732. function go() { return new ns.Foo(); }
  4733. `;
  4734. const result = extractFromSource('app.ts', code);
  4735. const ref = result.unresolvedReferences.find(
  4736. (r) => r.referenceKind === 'instantiates'
  4737. );
  4738. // We can't always resolve which Foo, but the name should be the
  4739. // simple identifier so name-matching has a chance.
  4740. expect(ref?.referenceName).toBe('Foo');
  4741. });
  4742. it('emits a decorates ref for `@Foo class X {}`', () => {
  4743. const code = `
  4744. function Foo(_arg: string) { return (cls: any) => cls; }
  4745. @Foo('x')
  4746. class X {}
  4747. `;
  4748. const result = extractFromSource('app.ts', code);
  4749. const decorClass = result.unresolvedReferences.find(
  4750. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  4751. );
  4752. expect(decorClass).toBeDefined();
  4753. });
  4754. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  4755. // Regression: the sibling-walk must stop at the first non-
  4756. // decorator separator. `@A class Foo {} @B class Bar {}` must
  4757. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  4758. // `decorates(Bar, A)`.
  4759. const code = `
  4760. function A(cls: any) { return cls; }
  4761. function B(cls: any) { return cls; }
  4762. @A
  4763. class Foo {}
  4764. @B
  4765. class Bar {}
  4766. `;
  4767. const result = extractFromSource('app.ts', code);
  4768. const decoratesEdges = result.unresolvedReferences.filter(
  4769. (r) => r.referenceKind === 'decorates'
  4770. );
  4771. // Exactly one decorates ref per decorated class, no cross-attribution.
  4772. const fromBar = decoratesEdges.filter((r) =>
  4773. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  4774. );
  4775. expect(fromBar.length).toBe(1);
  4776. expect(fromBar[0]!.referenceName).toBe('B');
  4777. });
  4778. it('emits a decorates ref for `@Foo method() {}`', () => {
  4779. const code = `
  4780. function Get(p: string) { return (t: any, k: string) => t; }
  4781. class Svc {
  4782. @Get('/x') method() { return 1; }
  4783. }
  4784. `;
  4785. const result = extractFromSource('app.ts', code);
  4786. const decorMethod = result.unresolvedReferences.find(
  4787. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  4788. );
  4789. expect(decorMethod).toBeDefined();
  4790. // The decorated symbol must be `method`, not the constructor or class.
  4791. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  4792. expect(decoratedNode?.name).toBe('method');
  4793. });
  4794. });
  4795. // =============================================================================
  4796. // Lua
  4797. // =============================================================================
  4798. describe('Lua Extraction', () => {
  4799. describe('Language detection', () => {
  4800. it('should detect Lua files', () => {
  4801. expect(detectLanguage('init.lua')).toBe('lua');
  4802. expect(detectLanguage('src/util.lua')).toBe('lua');
  4803. });
  4804. it('should report Lua as supported', () => {
  4805. expect(isLanguageSupported('lua')).toBe(true);
  4806. expect(getSupportedLanguages()).toContain('lua');
  4807. });
  4808. });
  4809. describe('Function extraction', () => {
  4810. it('should extract global and local functions', () => {
  4811. const code = `
  4812. function configure(opts) return opts end
  4813. local function helper(x) return x * 2 end
  4814. `;
  4815. const result = extractFromSource('init.lua', code);
  4816. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  4817. expect(funcs).toContain('configure');
  4818. expect(funcs).toContain('helper');
  4819. const configure = result.nodes.find((n) => n.name === 'configure');
  4820. expect(configure?.language).toBe('lua');
  4821. expect(configure?.signature).toBe('(opts)');
  4822. });
  4823. it('should split table/method functions into a receiver and method name', () => {
  4824. const code = `
  4825. function M.connect(host, port) return host end
  4826. function M:send(data) return self end
  4827. `;
  4828. const result = extractFromSource('init.lua', code);
  4829. const methods = result.nodes.filter((n) => n.kind === 'method');
  4830. const connect = methods.find((m) => m.name === 'connect');
  4831. expect(connect?.qualifiedName).toBe('M::connect');
  4832. const send = methods.find((m) => m.name === 'send');
  4833. expect(send?.qualifiedName).toBe('M::send');
  4834. });
  4835. });
  4836. describe('Variable extraction', () => {
  4837. it('should extract local variable declarations', () => {
  4838. const code = `
  4839. local M = {}
  4840. local count = 0
  4841. `;
  4842. const result = extractFromSource('mod.lua', code);
  4843. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  4844. expect(vars).toContain('M');
  4845. expect(vars).toContain('count');
  4846. });
  4847. });
  4848. describe('Import extraction (require)', () => {
  4849. it('should extract require() in local declarations and bare calls', () => {
  4850. const code = `
  4851. local socket = require("socket")
  4852. local http = require "resty.http"
  4853. require("side.effect")
  4854. `;
  4855. const result = extractFromSource('net.lua', code);
  4856. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4857. expect(imports).toContain('socket');
  4858. expect(imports).toContain('resty.http');
  4859. expect(imports).toContain('side.effect');
  4860. const ref = result.unresolvedReferences.find(
  4861. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  4862. );
  4863. expect(ref).toBeDefined();
  4864. });
  4865. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  4866. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  4867. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  4868. // by extracting several sources in sequence and asserting the LAST still works.
  4869. it('should keep extracting require across many sequential parses', () => {
  4870. let last;
  4871. for (let i = 0; i < 8; i++) {
  4872. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  4873. }
  4874. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4875. expect(imports).toContain('module.7');
  4876. });
  4877. });
  4878. describe('Call extraction', () => {
  4879. it('should record intra-file calls as resolvable references', () => {
  4880. const code = `
  4881. local function helper(x) return x end
  4882. local function run(y) return helper(y) end
  4883. `;
  4884. const result = extractFromSource('calls.lua', code);
  4885. const call = result.unresolvedReferences.find(
  4886. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  4887. );
  4888. expect(call).toBeDefined();
  4889. });
  4890. });
  4891. });
  4892. // =============================================================================
  4893. // Luau (typed superset of Lua — https://luau.org)
  4894. // =============================================================================
  4895. describe('Luau Extraction', () => {
  4896. describe('Language detection', () => {
  4897. it('should detect Luau files', () => {
  4898. expect(detectLanguage('init.luau')).toBe('luau');
  4899. expect(detectLanguage('src/Client.luau')).toBe('luau');
  4900. });
  4901. it('should report Luau as supported', () => {
  4902. expect(isLanguageSupported('luau')).toBe(true);
  4903. expect(getSupportedLanguages()).toContain('luau');
  4904. });
  4905. });
  4906. describe('Type aliases', () => {
  4907. it('should extract `type` and `export type` definitions', () => {
  4908. const code = `
  4909. export type Vector = { x: number, y: number }
  4910. type Handler = (msg: string) -> boolean
  4911. `;
  4912. const result = extractFromSource('types.luau', code);
  4913. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  4914. const vector = aliases.find((a) => a.name === 'Vector');
  4915. expect(vector).toBeDefined();
  4916. expect(vector?.isExported).toBe(true);
  4917. const handler = aliases.find((a) => a.name === 'Handler');
  4918. expect(handler).toBeDefined();
  4919. expect(handler?.isExported).toBe(false);
  4920. });
  4921. });
  4922. describe('Typed functions and methods', () => {
  4923. it('should capture typed signatures and split methods by receiver', () => {
  4924. const code = `
  4925. function configure(opts: { debug: boolean }): boolean
  4926. return opts.debug
  4927. end
  4928. function Client:fetch(path: string): Response
  4929. return path
  4930. end
  4931. `;
  4932. const result = extractFromSource('client.luau', code);
  4933. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  4934. expect(configure?.language).toBe('luau');
  4935. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  4936. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  4937. expect(fetch?.qualifiedName).toBe('Client::fetch');
  4938. });
  4939. });
  4940. describe('Imports and variables', () => {
  4941. it('should extract string and Roblox instance-path require imports', () => {
  4942. const code = `
  4943. local http = require("http")
  4944. local Signal = require(script.Parent.Signal)
  4945. local count = 0
  4946. `;
  4947. const result = extractFromSource('mod.luau', code);
  4948. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4949. expect(imports).toContain('http'); // string require
  4950. expect(imports).toContain('Signal'); // Roblox instance-path require
  4951. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  4952. expect(vars).toContain('count');
  4953. });
  4954. });
  4955. });
  4956. // =============================================================================
  4957. // Objective-C
  4958. // =============================================================================
  4959. describe('Objective-C Extraction', () => {
  4960. const sample = `
  4961. #import <Foundation/Foundation.h>
  4962. #import "MyClass.h"
  4963. @interface MyClass : NSObject <NSCopying>
  4964. @property (nonatomic, copy) NSString *name;
  4965. - (void)greet;
  4966. - (void)doThing:(id)x with:(id)y;
  4967. + (instancetype)shared;
  4968. @end
  4969. @implementation MyClass
  4970. - (void)greet {
  4971. NSLog(@"Hello");
  4972. [self doWork];
  4973. }
  4974. - (void)doThing:(id)x with:(id)y {
  4975. [self notify:x];
  4976. }
  4977. + (instancetype)shared {
  4978. return [[MyClass alloc] init];
  4979. }
  4980. @end
  4981. void helperFunction(int count) {
  4982. MyClass *obj = [MyClass shared];
  4983. [obj greet];
  4984. }
  4985. `;
  4986. it('should extract classes, methods, functions, and imports', () => {
  4987. const result = extractFromSource('App.m', sample);
  4988. const classes = result.nodes.filter((n) => n.kind === 'class');
  4989. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  4990. const methods = result.nodes.filter((n) => n.kind === 'method');
  4991. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  4992. const shared = methods.find((m) => m.name === 'shared');
  4993. expect(shared?.isStatic).toBe(true);
  4994. const properties = result.nodes.filter((n) => n.kind === 'property');
  4995. expect(properties.some((p) => p.name === 'name')).toBe(true);
  4996. const functions = result.nodes.filter((n) => n.kind === 'function');
  4997. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  4998. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4999. expect(imports).toContain('Foundation/Foundation.h');
  5000. expect(imports).toContain('MyClass.h');
  5001. });
  5002. it('should record inheritance and protocol conformance', () => {
  5003. const result = extractFromSource('App.m', sample);
  5004. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  5005. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  5006. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  5007. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  5008. });
  5009. it('should record message sends and C calls', () => {
  5010. const result = extractFromSource('App.m', sample);
  5011. const calls = result.unresolvedReferences
  5012. .filter((r) => r.referenceKind === 'calls')
  5013. .map((r) => r.referenceName);
  5014. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  5015. });
  5016. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  5017. // Regression for the gap discovered post-#165: message_expression's
  5018. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  5019. // so calls never resolved to multi-part method definitions like
  5020. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  5021. // must match the method-definition name with full keywords + trailing colons.
  5022. const code = `
  5023. @implementation Caller
  5024. - (void)demo {
  5025. NSMutableDictionary *d = [NSMutableDictionary new];
  5026. [d setObject:@"v" forKey:@"k"];
  5027. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  5028. [self touchesBegan:nil withEvent:nil];
  5029. }
  5030. @end
  5031. `;
  5032. const result = extractFromSource('Caller.m', code);
  5033. const calls = result.unresolvedReferences
  5034. .filter((r) => r.referenceKind === 'calls')
  5035. .map((r) => r.referenceName);
  5036. expect(calls).toEqual(
  5037. expect.arrayContaining([
  5038. 'd.setObject:forKey:',
  5039. 'd.setObject:forKey:withRetry:',
  5040. 'touchesBegan:withEvent:',
  5041. ])
  5042. );
  5043. });
  5044. it('should not classify pure C headers with @end in comments as objc', () => {
  5045. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  5046. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  5047. });
  5048. it('should extract protocol declarations', () => {
  5049. const code = `
  5050. @protocol DataSource <NSObject>
  5051. - (NSInteger)numberOfItems;
  5052. @end
  5053. `;
  5054. const result = extractFromSource('DataSource.h', code);
  5055. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  5056. expect(protocol).toBeDefined();
  5057. });
  5058. it('should report Objective-C as supported', () => {
  5059. expect(isLanguageSupported('objc')).toBe(true);
  5060. expect(getSupportedLanguages()).toContain('objc');
  5061. });
  5062. });
  5063. describe('Regression: issue-specific extraction fixes', () => {
  5064. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  5065. const code = `
  5066. define(['dep'], function (dep) {
  5067. function innerHelper(x) { return x + 1; }
  5068. function compute(y) { return innerHelper(y); }
  5069. return { compute: compute };
  5070. });
  5071. `;
  5072. const result = extractFromSource('amd-module.js', code);
  5073. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  5074. expect(fns).toContain('innerHelper');
  5075. expect(fns).toContain('compute');
  5076. });
  5077. it('attaches Go methods on generic receivers to their type (#583)', () => {
  5078. const code = `
  5079. package main
  5080. type Stack[T any] struct { items []T }
  5081. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  5082. func (s Stack[T]) Len() int { return len(s.items) }
  5083. `;
  5084. const result = extractFromSource('stack.go', code);
  5085. const methods = result.nodes.filter((n) => n.kind === 'method');
  5086. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  5087. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  5088. });
  5089. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  5090. expect(isSourceFile('mod.mts')).toBe(true);
  5091. expect(isSourceFile('mod.cts')).toBe(true);
  5092. expect(isSourceFile('service.xsjs')).toBe(true);
  5093. expect(isSourceFile('lib.xsjslib')).toBe(true);
  5094. expect(detectLanguage('mod.mts')).toBe('typescript');
  5095. expect(detectLanguage('service.xsjs')).toBe('javascript');
  5096. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  5097. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  5098. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  5099. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  5100. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  5101. });
  5102. });
  5103. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  5104. // An import IS a dependency, but extraction only emits references for calls,
  5105. // instantiations, type annotations, and inheritance — so a symbol imported and
  5106. // then merely re-exported, placed in a registry array, passed as an argument,
  5107. // or used in JSX produced no cross-file edge, leaving the providing file with a
  5108. // false "0 dependents". These tests pin the import/re-export binding linking.
  5109. it('emits an imports reference per named, aliased, and default import binding', () => {
  5110. const code = `
  5111. import { widget, helper as h } from './foo';
  5112. import Thing from './thing';
  5113. import * as NS from './ns';
  5114. export const registry = [widget];
  5115. `;
  5116. const result = extractFromSource('bar.ts', code);
  5117. const names = result.unresolvedReferences
  5118. .filter((r) => r.referenceKind === 'imports')
  5119. .map((r) => r.referenceName);
  5120. expect(names).toContain('widget'); // named import → local name
  5121. expect(names).toContain('h'); // aliased import → local alias
  5122. expect(names).toContain('Thing'); // default import
  5123. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  5124. });
  5125. it('emits an imports reference per re-exported binding', () => {
  5126. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  5127. const names = result.unresolvedReferences
  5128. .filter((r) => r.referenceKind === 'imports')
  5129. .map((r) => r.referenceName);
  5130. // Re-export links the SOURCE-side name, not the local alias.
  5131. expect(names).toContain('alpha');
  5132. expect(names).toContain('beta');
  5133. });
  5134. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  5135. const dir = createTempDir();
  5136. try {
  5137. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5138. fs.writeFileSync(
  5139. path.join(dir, 'src', 'foo.ts'),
  5140. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  5141. );
  5142. // bar uses widget ONLY in an array and re-exports helper — neither is
  5143. // called/typed, so before import-linking bar had no edge to foo at all.
  5144. fs.writeFileSync(
  5145. path.join(dir, 'src', 'bar.ts'),
  5146. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  5147. );
  5148. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  5149. await cg.indexAll();
  5150. cg.resolveReferences();
  5151. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  5152. cg.destroy();
  5153. } finally {
  5154. cleanupTempDir(dir);
  5155. }
  5156. });
  5157. it('a namespace import touched only via a value-member read still links the module file', async () => {
  5158. const dir = createTempDir();
  5159. try {
  5160. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5161. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  5162. // `foo` is imported as a namespace and used ONLY via a value-member read
  5163. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  5164. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  5165. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  5166. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  5167. await cg.indexAll();
  5168. cg.resolveReferences();
  5169. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  5170. cg.destroy();
  5171. } finally {
  5172. cleanupTempDir(dir);
  5173. }
  5174. });
  5175. });
  5176. describe('Python import dependency linking (blast-radius recall)', () => {
  5177. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  5178. // name brought in with `from module import X` and then merely stored, used as
  5179. // a decorator/argument, or re-exported through an `__init__.py` produced no
  5180. // cross-file edge — the providing module showed a false "0 dependents".
  5181. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  5182. const code = [
  5183. 'from foo import helper, widget',
  5184. 'from foo import Thing as T',
  5185. 'from . import sibling',
  5186. 'from bar import *',
  5187. ].join('\n');
  5188. const names = extractFromSource('mod.py', code)
  5189. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  5190. .map((r) => r.referenceName);
  5191. expect(names).toContain('helper');
  5192. expect(names).toContain('widget'); // value import
  5193. expect(names).toContain('T'); // aliased import → local name
  5194. expect(names).toContain('sibling'); // `from . import <name>`
  5195. expect(names).not.toContain('*'); // wildcard import has no names
  5196. });
  5197. it('a Python value imported but never called still makes the importer a dependent', async () => {
  5198. const dir = createTempDir();
  5199. try {
  5200. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5201. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  5202. // bar imports widget+helper but only stores widget in a list — nothing is
  5203. // called, so before import-linking bar had no edge to foo.
  5204. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  5205. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5206. await cg.indexAll();
  5207. cg.resolveReferences();
  5208. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  5209. cg.destroy();
  5210. } finally {
  5211. cleanupTempDir(dir);
  5212. }
  5213. });
  5214. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  5215. const dir = createTempDir();
  5216. try {
  5217. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5218. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  5219. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  5220. // certs is an imported MODULE (a file), and certs.where() is a qualified
  5221. // call through it — the receiver isn't a symbol, so plain name-matching
  5222. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  5223. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  5224. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5225. await cg.indexAll();
  5226. cg.resolveReferences();
  5227. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  5228. cg.destroy();
  5229. } finally {
  5230. cleanupTempDir(dir);
  5231. }
  5232. });
  5233. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  5234. const dir = createTempDir();
  5235. try {
  5236. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  5237. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  5238. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  5239. // member resolution can't find it — the module-import backstop must still
  5240. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  5241. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  5242. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  5243. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  5244. await cg.indexAll();
  5245. cg.resolveReferences();
  5246. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  5247. cg.destroy();
  5248. } finally {
  5249. cleanupTempDir(dir);
  5250. }
  5251. });
  5252. });
  5253. describe('Go cross-package composite literals (blast-radius recall)', () => {
  5254. // Go function calls and type references across packages already resolved, but
  5255. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  5256. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  5257. // (gin's render/binding implementations) showed 0 dependents.
  5258. it('links a cross-package struct composite literal to the defining package', async () => {
  5259. const dir = createTempDir();
  5260. try {
  5261. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5262. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  5263. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  5264. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  5265. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5266. await cg.indexAll();
  5267. cg.resolveReferences();
  5268. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  5269. cg.destroy();
  5270. } finally {
  5271. cleanupTempDir(dir);
  5272. }
  5273. });
  5274. it('links a composite literal in a package-level var registry', async () => {
  5275. const dir = createTempDir();
  5276. try {
  5277. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5278. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  5279. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  5280. // The implementation is registered only in a top-level `var registry = {...}`
  5281. // map literal — the body walker doesn't cover top-level declarations, so this
  5282. // exercises the var-initializer walking added for Go.
  5283. 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`);
  5284. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5285. await cg.indexAll();
  5286. cg.resolveReferences();
  5287. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  5288. cg.destroy();
  5289. } finally {
  5290. cleanupTempDir(dir);
  5291. }
  5292. });
  5293. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  5294. const dir = createTempDir();
  5295. try {
  5296. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5297. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  5298. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  5299. // `(*Wrapped)` — without normalization it dropped on the floor.
  5300. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  5301. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5302. await cg.indexAll();
  5303. cg.resolveReferences();
  5304. expect(cg.getFileDependents('types.go')).toContain('use.go');
  5305. cg.destroy();
  5306. } finally {
  5307. cleanupTempDir(dir);
  5308. }
  5309. });
  5310. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  5311. const dir = createTempDir();
  5312. try {
  5313. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  5314. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  5315. 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`);
  5316. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  5317. // reached ONLY through the interface (API.Marshal). Without implicit
  5318. // interface satisfaction + dispatch, json.go shows 0 dependents.
  5319. 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`);
  5320. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  5321. await cg.indexAll();
  5322. cg.resolveReferences();
  5323. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  5324. cg.destroy();
  5325. } finally {
  5326. cleanupTempDir(dir);
  5327. }
  5328. });
  5329. });
  5330. describe('C# records (blast-radius recall)', () => {
  5331. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  5332. // but `record` / `record struct` declarations weren't extracted as types — so
  5333. // every reference, generic-type-argument, and `new` of a record dropped on the
  5334. // floor and the defining file showed 0 dependents. (#237)
  5335. it('extracts a record as a graph node (record class + record struct)', () => {
  5336. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  5337. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  5338. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  5339. });
  5340. it('resolves references / instantiations of a record across files', async () => {
  5341. const dir = createTempDir();
  5342. try {
  5343. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  5344. // Box is used as a generic type argument and instantiated — both require
  5345. // Box to be a node to resolve.
  5346. fs.writeFileSync(
  5347. path.join(dir, 'use.cs'),
  5348. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  5349. );
  5350. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  5351. await cg.indexAll();
  5352. cg.resolveReferences();
  5353. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  5354. cg.destroy();
  5355. } finally {
  5356. cleanupTempDir(dir);
  5357. }
  5358. });
  5359. });
  5360. describe('Rust cross-module recall', () => {
  5361. function rustProject(files: Record<string, string>): string {
  5362. const dir = createTempDir();
  5363. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  5364. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  5365. for (const [rel, content] of Object.entries(files)) {
  5366. const full = path.join(dir, 'src', rel);
  5367. fs.mkdirSync(path.dirname(full), { recursive: true });
  5368. fs.writeFileSync(full, content);
  5369. }
  5370. return dir;
  5371. }
  5372. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  5373. const dir = rustProject({
  5374. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  5375. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  5376. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  5377. });
  5378. try {
  5379. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5380. await cg.indexAll();
  5381. cg.resolveReferences();
  5382. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  5383. cg.destroy();
  5384. } finally { cleanupTempDir(dir); }
  5385. });
  5386. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  5387. const dir = rustProject({
  5388. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  5389. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  5390. // Mine implements Render structurally; reached via &dyn Render dispatch.
  5391. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  5392. });
  5393. try {
  5394. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5395. await cg.indexAll();
  5396. cg.resolveReferences();
  5397. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  5398. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  5399. cg.destroy();
  5400. } finally { cleanupTempDir(dir); }
  5401. });
  5402. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  5403. const dir = rustProject({
  5404. 'lib.rs': 'pub mod api;\n',
  5405. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  5406. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  5407. });
  5408. try {
  5409. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5410. await cg.indexAll();
  5411. cg.resolveReferences();
  5412. // The re-export hub depends on the module it re-exports from.
  5413. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  5414. cg.destroy();
  5415. } finally { cleanupTempDir(dir); }
  5416. });
  5417. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  5418. const dir = rustProject({
  5419. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  5420. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  5421. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  5422. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  5423. // send this re-export to fast.rs specifically, not name-match either.
  5424. 'hub.rs': 'pub use crate::fast::read;\n',
  5425. });
  5426. try {
  5427. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  5428. await cg.indexAll();
  5429. cg.resolveReferences();
  5430. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  5431. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  5432. cg.destroy();
  5433. } finally { cleanupTempDir(dir); }
  5434. });
  5435. });
  5436. describe('Java annotations (blast-radius recall)', () => {
  5437. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  5438. const dir = createTempDir();
  5439. try {
  5440. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  5441. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  5442. // live inside a `modifiers` node on the class/field/method) must extract.
  5443. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  5444. fs.writeFileSync(
  5445. path.join(dir, 'p', 'User.java'),
  5446. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  5447. );
  5448. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  5449. await cg.indexAll();
  5450. cg.resolveReferences();
  5451. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  5452. cg.destroy();
  5453. } finally { cleanupTempDir(dir); }
  5454. });
  5455. });
  5456. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  5457. it('links a @propertyWrapper usage to the wrapper type', async () => {
  5458. const dir = createTempDir();
  5459. try {
  5460. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  5461. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  5462. // `@Argument` is a Swift attribute on a stored property — it lives in the
  5463. // property's `modifiers` and Swift doesn't extract instance properties as
  5464. // their own nodes, so without the fix the wrapper type has no users.
  5465. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  5466. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  5467. await cg.indexAll();
  5468. cg.resolveReferences();
  5469. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  5470. cg.destroy();
  5471. } finally { cleanupTempDir(dir); }
  5472. });
  5473. });