extraction.test.ts 236 KB

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