extraction.test.ts 277 KB

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