extraction.test.ts 255 KB

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