1
0

extraction.test.ts 298 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020
  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, blankCppInlineMacros, blankMetalAttributes, recoverMangledCppName } 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 detect Metal shader files as C++ (#1121)', () => {
  86. expect(detectLanguage('Shaders.metal')).toBe('cpp');
  87. expect(isSourceFile('Renderer/Shaders.metal')).toBe(true);
  88. });
  89. it('should return unknown for unsupported extensions', () => {
  90. expect(detectLanguage('styles.css')).toBe('unknown');
  91. expect(detectLanguage('data.json')).toBe('unknown');
  92. });
  93. });
  94. describe('Language Support', () => {
  95. it('should report supported languages', () => {
  96. expect(isLanguageSupported('typescript')).toBe(true);
  97. expect(isLanguageSupported('python')).toBe(true);
  98. expect(isLanguageSupported('go')).toBe(true);
  99. expect(isLanguageSupported('unknown')).toBe(false);
  100. });
  101. it('should list all supported languages', () => {
  102. const languages = getSupportedLanguages();
  103. expect(languages).toContain('typescript');
  104. expect(languages).toContain('javascript');
  105. expect(languages).toContain('python');
  106. expect(languages).toContain('go');
  107. expect(languages).toContain('rust');
  108. expect(languages).toContain('java');
  109. expect(languages).toContain('csharp');
  110. expect(languages).toContain('php');
  111. expect(languages).toContain('ruby');
  112. expect(languages).toContain('swift');
  113. expect(languages).toContain('kotlin');
  114. expect(languages).toContain('dart');
  115. });
  116. });
  117. describe('TypeScript Extraction', () => {
  118. it('should extract function declarations', () => {
  119. const code = `
  120. export function processPayment(amount: number): Promise<Receipt> {
  121. return stripe.charge(amount);
  122. }
  123. `;
  124. const result = extractFromSource('payment.ts', code);
  125. // File node + function node
  126. const fileNode = result.nodes.find((n) => n.kind === 'file');
  127. expect(fileNode).toBeDefined();
  128. expect(fileNode?.name).toBe('payment.ts');
  129. const funcNode = result.nodes.find((n) => n.kind === 'function');
  130. expect(funcNode).toMatchObject({
  131. kind: 'function',
  132. name: 'processPayment',
  133. language: 'typescript',
  134. isExported: true,
  135. });
  136. expect(funcNode?.signature).toContain('amount: number');
  137. });
  138. it('should extract class declarations', () => {
  139. const code = `
  140. export class PaymentService {
  141. private stripe: StripeClient;
  142. constructor(apiKey: string) {
  143. this.stripe = new StripeClient(apiKey);
  144. }
  145. async charge(amount: number): Promise<Receipt> {
  146. return this.stripe.charge(amount);
  147. }
  148. }
  149. `;
  150. const result = extractFromSource('service.ts', code);
  151. const classNode = result.nodes.find((n) => n.kind === 'class');
  152. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  153. expect(classNode).toBeDefined();
  154. expect(classNode?.name).toBe('PaymentService');
  155. expect(classNode?.isExported).toBe(true);
  156. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  157. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  158. expect(chargeMethod).toBeDefined();
  159. });
  160. it('captures docstrings for export- and const-wrapped declarations (#780)', () => {
  161. const code = `
  162. // plain class control
  163. class Ledger {}
  164. // exported class
  165. export class Invoice {}
  166. // export default
  167. export default function settle() { return true; }
  168. // exported arrow const
  169. export const refund = (amount: number) => amount;
  170. // non-export arrow const
  171. const audit = (amount: number) => amount;
  172. `;
  173. const byName = new Map(extractFromSource('doc.ts', code).nodes.map((n) => [n.name, n]));
  174. expect(byName.get('Ledger')?.docstring).toBe('plain class control'); // control still works
  175. expect(byName.get('Invoice')?.docstring).toBe('exported class');
  176. expect(byName.get('settle')?.docstring).toBe('export default');
  177. expect(byName.get('refund')?.docstring).toBe('exported arrow const');
  178. expect(byName.get('audit')?.docstring).toBe('non-export arrow const');
  179. });
  180. it('does not mis-attribute a class comment to an uncommented member (#780)', () => {
  181. const code = `
  182. // Comment for Box
  183. export class Box {
  184. noComment() {}
  185. // own comment
  186. withComment() {}
  187. }
  188. `;
  189. const byName = new Map(extractFromSource('box.ts', code).nodes.map((n) => [n.name, n]));
  190. expect(byName.get('Box')?.docstring).toBe('Comment for Box');
  191. expect(byName.get('noComment')?.docstring ?? null).toBeNull(); // no over-walk
  192. expect(byName.get('withComment')?.docstring).toBe('own comment');
  193. });
  194. it('captures docstrings for decorated Python declarations, stripping `#` (#780)', () => {
  195. const code = [
  196. '# decorated function',
  197. '@app.route("/x")',
  198. 'def py_handler():',
  199. ' return 1',
  200. '',
  201. '',
  202. '# plain function control',
  203. 'def py_plain():',
  204. ' return 1',
  205. '',
  206. '',
  207. '# decorated class',
  208. '@dataclass',
  209. 'class PyModel:',
  210. ' pass',
  211. '',
  212. ].join('\n');
  213. const byName = new Map(extractFromSource('mod.py', code).nodes.map((n) => [n.name, n]));
  214. expect(byName.get('py_handler')?.docstring).toBe('decorated function');
  215. expect(byName.get('py_plain')?.docstring).toBe('plain function control'); // `#` stripped
  216. expect(byName.get('PyModel')?.docstring).toBe('decorated class');
  217. });
  218. it('cleans comment markers across language styles (#780)', () => {
  219. const doc = (file: string, code: string, name: string) =>
  220. new Map(extractFromSource(file, code).nodes.map((n) => [n.name, n])).get(name)?.docstring;
  221. // Rust doc lines (`///`, `//!`) — the trailing slash used to leak through.
  222. expect(doc('m.rs', '/// rust doc line\nfn rs_fn() {}', 'rs_fn')).toBe('rust doc line');
  223. // Lua line + long-bracket comments.
  224. expect(doc('m.lua', '-- lua line\nfunction lua_fn() end', 'lua_fn')).toBe('lua line');
  225. expect(doc('b.lua', '--[[ lua block ]]\nfunction lua_b() end', 'lua_b')).toBe('lua block');
  226. // Pascal brace and paren-star comments.
  227. const pasUnit = (c: string) =>
  228. `unit U;\ninterface\n${c}\nprocedure P;\nimplementation\nprocedure P;\nbegin\nend;\nend.\n`;
  229. expect(doc('a.pas', pasUnit('{ pascal brace }'), 'P')).toBe('pascal brace');
  230. expect(doc('c.pas', pasUnit('(* pascal paren *)'), 'P')).toBe('pascal paren');
  231. // C block comment still clean (no regression).
  232. expect(doc('m.c', '/* c block */\nvoid c_fn(void) {}', 'c_fn')).toBe('c block');
  233. });
  234. it('should extract interfaces', () => {
  235. const code = `
  236. export interface User {
  237. id: string;
  238. name: string;
  239. email: string;
  240. }
  241. `;
  242. const result = extractFromSource('types.ts', code);
  243. const fileNode = result.nodes.find((n) => n.kind === 'file');
  244. expect(fileNode).toBeDefined();
  245. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  246. expect(ifaceNode).toMatchObject({
  247. kind: 'interface',
  248. name: 'User',
  249. isExported: true,
  250. });
  251. });
  252. it('should extract type references from interface property signatures', () => {
  253. const code = `
  254. import type { IPage } from '../PromoterList';
  255. import type { IOrderField } from '../types';
  256. interface Hprops {
  257. value?: Partial<IPage> & Partial<IOrderField>;
  258. }
  259. `;
  260. const result = extractFromSource('HeaderFilter.ts', code);
  261. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  262. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  263. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  264. });
  265. it('should extract type references from interface method signatures', () => {
  266. const code = `
  267. import type { IPage } from '../PromoterList';
  268. import type { IOrderField } from '../types';
  269. interface MethodForm {
  270. fetchPage(arg: IPage): IOrderField;
  271. }
  272. `;
  273. const result = extractFromSource('MethodForm.ts', code);
  274. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  275. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  276. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  277. });
  278. it('extracts type references from in-body local variable annotations', () => {
  279. // A function that uses a type ONLY in its body — `const items: Foo[] = []` —
  280. // still depends on Foo. The body walker used to capture calls but never type
  281. // annotations, so impact / `affected` missed the dependency. Must cover
  282. // function, class-method, and object-literal-method bodies — and must NOT
  283. // turn the locals themselves into graph nodes (that would explode the graph).
  284. const code = `
  285. import { Foo } from './types';
  286. export function build(): void {
  287. const items: Foo[] = [];
  288. void items;
  289. }
  290. export class K {
  291. run(): void {
  292. const a: Foo = { x: 1 };
  293. void a;
  294. }
  295. }
  296. export const handler = {
  297. handle(): void {
  298. const b: Foo = { x: 1 };
  299. void b;
  300. },
  301. };
  302. `;
  303. const result = extractFromSource('inbody.ts', code);
  304. const fooRefs = result.unresolvedReferences.filter(
  305. (r) => r.referenceKind === 'references' && r.referenceName === 'Foo'
  306. );
  307. // One per body scope: build(), K.run(), handler.handle().
  308. expect(fooRefs.length).toBeGreaterThanOrEqual(3);
  309. // Each reference is attributed to its enclosing function/method node — never
  310. // to a local-variable node, because locals are intentionally not extracted.
  311. const byId = new Map(result.nodes.map((n) => [n.id, n]));
  312. for (const ref of fooRefs) {
  313. const owner = byId.get(ref.fromNodeId);
  314. expect(owner).toBeDefined();
  315. expect(['function', 'method']).toContain(owner!.kind);
  316. }
  317. // The locals (items/a/b) must not leak in as symbols.
  318. expect(result.nodes.some((n) => ['items', 'a', 'b'].includes(n.name))).toBe(false);
  319. });
  320. it('should track function calls', () => {
  321. const code = `
  322. function main() {
  323. const result = processData();
  324. console.log(result);
  325. }
  326. `;
  327. const result = extractFromSource('main.ts', code);
  328. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  329. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  330. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  331. });
  332. });
  333. describe('Arrow Function Export Extraction', () => {
  334. it('should extract exported arrow functions assigned to const', () => {
  335. const code = `
  336. export const useAuth = (): AuthContextValue => {
  337. return useContext(AuthContext);
  338. };
  339. `;
  340. const result = extractFromSource('hooks.ts', code);
  341. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  342. expect(funcNode).toBeDefined();
  343. expect(funcNode).toMatchObject({
  344. kind: 'function',
  345. name: 'useAuth',
  346. isExported: true,
  347. });
  348. });
  349. it('should extract exported function expressions assigned to const', () => {
  350. const code = `
  351. export const processData = function(input: string): string {
  352. return input.trim();
  353. };
  354. `;
  355. const result = extractFromSource('utils.ts', code);
  356. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  357. expect(funcNode).toBeDefined();
  358. expect(funcNode).toMatchObject({
  359. kind: 'function',
  360. name: 'processData',
  361. isExported: true,
  362. });
  363. });
  364. it('should not extract non-exported arrow functions as exported', () => {
  365. const code = `
  366. const internalHelper = () => {
  367. return 42;
  368. };
  369. `;
  370. const result = extractFromSource('internal.ts', code);
  371. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  372. expect(helperNode).toBeDefined();
  373. expect(helperNode?.isExported).toBeFalsy();
  374. });
  375. it('should still skip truly anonymous arrow functions', () => {
  376. const code = `
  377. const items = [1, 2, 3].map((x) => x * 2);
  378. `;
  379. const result = extractFromSource('anon.ts', code);
  380. // The inline arrow function passed to .map() has no variable_declarator parent
  381. // and should remain anonymous (skipped)
  382. const anonFunctions = result.nodes.filter(
  383. (n) => n.kind === 'function' && n.name === '<anonymous>'
  384. );
  385. expect(anonFunctions).toHaveLength(0);
  386. });
  387. it('should extract multiple exported arrow functions from the same file', () => {
  388. const code = `
  389. export const add = (a: number, b: number): number => a + b;
  390. export const subtract = (a: number, b: number): number => a - b;
  391. const internal = () => 'not exported';
  392. `;
  393. const result = extractFromSource('math.ts', code);
  394. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  395. expect(exported).toHaveLength(2);
  396. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  397. const internalNode = result.nodes.find((n) => n.name === 'internal');
  398. expect(internalNode).toBeDefined();
  399. expect(internalNode?.isExported).toBeFalsy();
  400. });
  401. it('should extract arrow functions in JavaScript files', () => {
  402. const code = `
  403. export const fetchData = async () => {
  404. const response = await fetch('/api/data');
  405. return response.json();
  406. };
  407. `;
  408. const result = extractFromSource('api.js', code);
  409. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  410. expect(funcNode).toBeDefined();
  411. expect(funcNode).toMatchObject({
  412. kind: 'function',
  413. name: 'fetchData',
  414. isExported: true,
  415. });
  416. });
  417. });
  418. describe('Type Alias Extraction', () => {
  419. it('should extract exported type aliases in TypeScript', () => {
  420. const code = `
  421. export type AuthContextValue = {
  422. user: User | null;
  423. login: () => void;
  424. logout: () => void;
  425. };
  426. `;
  427. const result = extractFromSource('types.ts', code);
  428. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  429. expect(typeNode).toMatchObject({
  430. kind: 'type_alias',
  431. name: 'AuthContextValue',
  432. isExported: true,
  433. });
  434. });
  435. it('should extract non-exported type aliases', () => {
  436. const code = `
  437. type InternalState = {
  438. loading: boolean;
  439. error: string | null;
  440. };
  441. `;
  442. const result = extractFromSource('internal.ts', code);
  443. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  444. expect(typeNode).toMatchObject({
  445. kind: 'type_alias',
  446. name: 'InternalState',
  447. isExported: false,
  448. });
  449. });
  450. it('should extract multiple type aliases from the same file', () => {
  451. const code = `
  452. export type UnitSystem = 'metric' | 'imperial';
  453. export type DateFormat = 'ISO' | 'US' | 'EU';
  454. type Internal = string;
  455. `;
  456. const result = extractFromSource('config.ts', code);
  457. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  458. expect(typeAliases).toHaveLength(3);
  459. const exported = typeAliases.filter((n) => n.isExported);
  460. expect(exported).toHaveLength(2);
  461. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  462. });
  463. // A service/contract registry written as a tuple of generic instantiations —
  464. // the names are string-literal type arguments, not declarations, so static
  465. // extraction otherwise never indexes them (issue #634).
  466. it('extracts string-literal contract names from a generic tuple type alias (#634)', () => {
  467. const code = `
  468. interface Service<Name extends string, Req, Resp> { name: Name; }
  469. export type MyServiceList = [
  470. Service<'query_apply_record', { pageNo: number }, { ok: boolean }>,
  471. Service<'apply_confirm', { code: string }, { ok: boolean }>
  472. ];
  473. `;
  474. const result = extractFromSource('services/api.ts', code);
  475. const names = result.nodes.filter(
  476. (n) => n.kind === 'method' && n.qualifiedName.startsWith('MyServiceList::')
  477. );
  478. expect(names.map((n) => n.name).sort()).toEqual(['apply_confirm', 'query_apply_record']);
  479. const queryNode = names.find((n) => n.name === 'query_apply_record');
  480. expect(queryNode?.qualifiedName).toBe('MyServiceList::query_apply_record');
  481. // Signature carries the full contract entry so search results show context.
  482. expect(queryNode?.signature).toContain("Service<'query_apply_record'");
  483. // The string-literal name is contained by the type alias.
  484. const alias = result.nodes.find((n) => n.kind === 'type_alias' && n.name === 'MyServiceList');
  485. const containsEdge = result.edges.find(
  486. (e) => e.kind === 'contains' && e.source === alias?.id && e.target === queryNode?.id
  487. );
  488. expect(containsEdge).toBeDefined();
  489. });
  490. it('does not extract string literals from utility types or nested generics (#634)', () => {
  491. const code = `
  492. interface User { id: string; name: string; }
  493. interface Service<Name extends string, Req, Resp> { name: Name; }
  494. export type Picked = Pick<User, 'id' | 'name'>;
  495. export type Rec = Record<'foo' | 'bar', number>;
  496. // Tuple entry, but the name is a non-identifier route path; the nested Pick's
  497. // 'id' must also stay out (only DIRECT literal args of a tuple's generic count).
  498. export type Routes = [Service<'/api/users', Pick<User, 'id'>, {}>];
  499. // Bare string-literal tuple — not generic type arguments.
  500. export type Names = ['alpha', 'beta'];
  501. `;
  502. const result = extractFromSource('noise.ts', code);
  503. const leaked = result.nodes.filter(
  504. (n) =>
  505. (n.kind === 'method' || n.kind === 'property') &&
  506. ['id', 'name', 'foo', 'bar', 'alpha', 'beta'].includes(n.name)
  507. );
  508. expect(leaked).toEqual([]);
  509. });
  510. });
  511. describe('Exported Variable Extraction', () => {
  512. it('should extract exported const with call expression (Zustand store)', () => {
  513. const code = `
  514. export const useUIStore = create<UIState>((set) => ({
  515. isOpen: false,
  516. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  517. }));
  518. `;
  519. const result = extractFromSource('store.ts', code);
  520. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  521. expect(varNode).toBeDefined();
  522. expect(varNode?.isExported).toBe(true);
  523. });
  524. it('should extract exported const with object literal', () => {
  525. const code = `
  526. export const config = {
  527. apiUrl: 'https://api.example.com',
  528. timeout: 5000,
  529. };
  530. `;
  531. const result = extractFromSource('config.ts', code);
  532. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  533. expect(varNode).toBeDefined();
  534. expect(varNode?.isExported).toBe(true);
  535. });
  536. it('should extract exported const with array literal', () => {
  537. const code = `
  538. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  539. `;
  540. const result = extractFromSource('constants.ts', code);
  541. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  542. expect(varNode).toBeDefined();
  543. expect(varNode?.isExported).toBe(true);
  544. });
  545. it('should extract exported const with primitive value', () => {
  546. const code = `
  547. export const MAX_RETRIES = 3;
  548. export const API_VERSION = "v2";
  549. `;
  550. const result = extractFromSource('constants.ts', code);
  551. const variables = result.nodes.filter((n) => n.kind === 'constant');
  552. expect(variables).toHaveLength(2);
  553. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  554. });
  555. it('should NOT duplicate arrow functions as both function and variable', () => {
  556. const code = `
  557. export const useAuth = () => {
  558. return useContext(AuthContext);
  559. };
  560. `;
  561. const result = extractFromSource('hooks.ts', code);
  562. // Should be extracted as function (from arrow function handler), NOT as variable
  563. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  564. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  565. expect(funcNodes).toHaveLength(1);
  566. expect(varNodes).toHaveLength(0);
  567. });
  568. it('should extract non-exported const as non-exported variable', () => {
  569. const code = `
  570. const internalConfig = {
  571. debug: true,
  572. };
  573. `;
  574. const result = extractFromSource('internal.ts', code);
  575. // Non-exported const at file level should be extracted as a constant (not exported)
  576. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  577. expect(varNodes).toHaveLength(1);
  578. expect(varNodes[0]?.isExported).toBeFalsy();
  579. });
  580. it('should extract Zod schema exports', () => {
  581. const code = `
  582. export const userSchema = z.object({
  583. id: z.string(),
  584. name: z.string(),
  585. email: z.string().email(),
  586. });
  587. `;
  588. const result = extractFromSource('schemas.ts', code);
  589. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  590. expect(varNode).toBeDefined();
  591. expect(varNode?.isExported).toBe(true);
  592. });
  593. it('should extract XState machine exports', () => {
  594. const code = `
  595. export const authMachine = createMachine({
  596. id: "auth",
  597. initial: "idle",
  598. states: {
  599. idle: {},
  600. authenticated: {},
  601. },
  602. });
  603. `;
  604. const result = extractFromSource('machine.ts', code);
  605. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  606. expect(varNode).toBeDefined();
  607. expect(varNode?.isExported).toBe(true);
  608. });
  609. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  610. const code = `
  611. import { getTokenMp } from './api/upload';
  612. const token = getTokenMp();
  613. `;
  614. const result = extractFromSource('app.ts', code);
  615. const call = result.unresolvedReferences.find(
  616. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  617. );
  618. expect(call).toBeDefined();
  619. });
  620. });
  621. describe('File Node Extraction', () => {
  622. it('should create a file-kind node for each parsed file', () => {
  623. const code = `
  624. export function greet(name: string): string {
  625. return "Hello " + name;
  626. }
  627. `;
  628. const result = extractFromSource('greeter.ts', code);
  629. const fileNode = result.nodes.find((n) => n.kind === 'file');
  630. expect(fileNode).toBeDefined();
  631. expect(fileNode?.name).toBe('greeter.ts');
  632. expect(fileNode?.filePath).toBe('greeter.ts');
  633. expect(fileNode?.language).toBe('typescript');
  634. expect(fileNode?.startLine).toBe(1);
  635. });
  636. it('should create file nodes for Python files', () => {
  637. const code = `
  638. def main():
  639. pass
  640. `;
  641. const result = extractFromSource('main.py', code);
  642. const fileNode = result.nodes.find((n) => n.kind === 'file');
  643. expect(fileNode).toBeDefined();
  644. expect(fileNode?.name).toBe('main.py');
  645. expect(fileNode?.language).toBe('python');
  646. });
  647. it('should create containment edges from file node to top-level declarations', () => {
  648. const code = `
  649. export function foo() {}
  650. export function bar() {}
  651. `;
  652. const result = extractFromSource('fns.ts', code);
  653. const fileNode = result.nodes.find((n) => n.kind === 'file');
  654. expect(fileNode).toBeDefined();
  655. // There should be contains edges from the file node to each function
  656. const containsEdges = result.edges.filter(
  657. (e) => e.source === fileNode?.id && e.kind === 'contains'
  658. );
  659. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  660. });
  661. });
  662. describe('Python Extraction', () => {
  663. it('should extract function definitions', () => {
  664. const code = `
  665. def calculate_total(items: list, tax_rate: float) -> float:
  666. """Calculate total with tax."""
  667. subtotal = sum(item.price for item in items)
  668. return subtotal * (1 + tax_rate)
  669. `;
  670. const result = extractFromSource('calc.py', code);
  671. const fileNode = result.nodes.find((n) => n.kind === 'file');
  672. expect(fileNode).toBeDefined();
  673. const funcNode = result.nodes.find((n) => n.kind === 'function');
  674. expect(funcNode).toMatchObject({
  675. kind: 'function',
  676. name: 'calculate_total',
  677. language: 'python',
  678. });
  679. });
  680. it('should extract class definitions', () => {
  681. const code = `
  682. class UserService:
  683. """Service for managing users."""
  684. def __init__(self, db):
  685. self.db = db
  686. def get_user(self, user_id: str) -> User:
  687. return self.db.find_user(user_id)
  688. `;
  689. const result = extractFromSource('service.py', code);
  690. const classNode = result.nodes.find((n) => n.kind === 'class');
  691. expect(classNode).toBeDefined();
  692. expect(classNode?.name).toBe('UserService');
  693. });
  694. });
  695. describe('Go Extraction', () => {
  696. it('should extract function declarations', () => {
  697. const code = `
  698. package main
  699. func ProcessOrder(order Order) (Receipt, error) {
  700. // Process the order
  701. return Receipt{}, nil
  702. }
  703. `;
  704. const result = extractFromSource('main.go', code);
  705. const funcNode = result.nodes.find((n) => n.kind === 'function');
  706. expect(funcNode).toBeDefined();
  707. expect(funcNode?.name).toBe('ProcessOrder');
  708. });
  709. it('should extract method declarations', () => {
  710. const code = `
  711. package main
  712. type Service struct {
  713. db *Database
  714. }
  715. func (s *Service) GetUser(id string) (*User, error) {
  716. return s.db.FindUser(id)
  717. }
  718. `;
  719. const result = extractFromSource('service.go', code);
  720. const methodNode = result.nodes.find((n) => n.kind === 'method');
  721. expect(methodNode).toBeDefined();
  722. expect(methodNode?.name).toBe('GetUser');
  723. });
  724. });
  725. describe('Rust Extraction', () => {
  726. it('should extract function declarations', () => {
  727. const code = `
  728. pub fn process_data(input: &str) -> Result<Output, Error> {
  729. // Process data
  730. Ok(Output::new())
  731. }
  732. `;
  733. const result = extractFromSource('lib.rs', code);
  734. const funcNode = result.nodes.find((n) => n.kind === 'function');
  735. expect(funcNode).toBeDefined();
  736. expect(funcNode?.name).toBe('process_data');
  737. expect(funcNode?.visibility).toBe('public');
  738. });
  739. it('should extract struct declarations', () => {
  740. const code = `
  741. pub struct User {
  742. pub id: String,
  743. pub name: String,
  744. email: String,
  745. }
  746. `;
  747. const result = extractFromSource('models.rs', code);
  748. const structNode = result.nodes.find((n) => n.kind === 'struct');
  749. expect(structNode).toBeDefined();
  750. expect(structNode?.name).toBe('User');
  751. });
  752. it('should extract trait declarations', () => {
  753. const code = `
  754. pub trait Repository {
  755. fn find(&self, id: &str) -> Option<Entity>;
  756. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  757. }
  758. `;
  759. const result = extractFromSource('traits.rs', code);
  760. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  761. expect(traitNode).toBeDefined();
  762. expect(traitNode?.name).toBe('Repository');
  763. });
  764. it('should extract impl Trait for Type as implements edges', () => {
  765. const code = `
  766. pub struct MyCache {}
  767. pub trait Cache {
  768. fn get(&self, key: &str) -> Option<String>;
  769. }
  770. impl Cache for MyCache {
  771. fn get(&self, key: &str) -> Option<String> {
  772. None
  773. }
  774. }
  775. `;
  776. const result = extractFromSource('cache.rs', code);
  777. // Should have an unresolved reference for implements
  778. const implRef = result.unresolvedReferences.find(
  779. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  780. );
  781. expect(implRef).toBeDefined();
  782. // The struct MyCache should be the source
  783. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  784. expect(myCacheNode).toBeDefined();
  785. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  786. });
  787. it('should extract trait supertraits as extends references', () => {
  788. const code = `
  789. pub trait Display {}
  790. pub trait Error: Display {
  791. fn description(&self) -> &str;
  792. }
  793. `;
  794. const result = extractFromSource('error.rs', code);
  795. const extendsRef = result.unresolvedReferences.find(
  796. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  797. );
  798. expect(extendsRef).toBeDefined();
  799. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  800. expect(errorTrait).toBeDefined();
  801. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  802. });
  803. it('should not create implements edges for plain impl blocks', () => {
  804. const code = `
  805. pub struct Counter {
  806. count: u32,
  807. }
  808. impl Counter {
  809. pub fn new() -> Counter {
  810. Counter { count: 0 }
  811. }
  812. pub fn increment(&mut self) {
  813. self.count += 1;
  814. }
  815. }
  816. `;
  817. const result = extractFromSource('counter.rs', code);
  818. // Should have no implements references (no trait involved)
  819. const implRefs = result.unresolvedReferences.filter(
  820. (r) => r.referenceKind === 'implements'
  821. );
  822. expect(implRefs).toHaveLength(0);
  823. });
  824. });
  825. describe('Java Extraction', () => {
  826. it('should extract class declarations', () => {
  827. const code = `
  828. public class UserService {
  829. private final UserRepository repository;
  830. public UserService(UserRepository repository) {
  831. this.repository = repository;
  832. }
  833. public User getUser(String id) {
  834. return repository.findById(id);
  835. }
  836. }
  837. `;
  838. const result = extractFromSource('UserService.java', code);
  839. const classNode = result.nodes.find((n) => n.kind === 'class');
  840. expect(classNode).toBeDefined();
  841. expect(classNode?.name).toBe('UserService');
  842. expect(classNode?.visibility).toBe('public');
  843. });
  844. it('should extract method declarations', () => {
  845. const code = `
  846. public class Calculator {
  847. public static int add(int a, int b) {
  848. return a + b;
  849. }
  850. }
  851. `;
  852. const result = extractFromSource('Calculator.java', code);
  853. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  854. expect(methodNode).toBeDefined();
  855. expect(methodNode?.isStatic).toBe(true);
  856. });
  857. it('wraps top-level declarations in a namespace from package_declaration', () => {
  858. const code = `
  859. package com.example.foo;
  860. public class Bar {
  861. public String greet() { return "hi"; }
  862. }
  863. `;
  864. const result = extractFromSource('Bar.java', code);
  865. const ns = result.nodes.find((n) => n.kind === 'namespace');
  866. expect(ns?.name).toBe('com.example.foo');
  867. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  868. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  869. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  870. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  871. });
  872. it('does not wrap when no package is declared', () => {
  873. const code = `
  874. public class Bar {
  875. public String greet() { return "hi"; }
  876. }
  877. `;
  878. const result = extractFromSource('Bar.java', code);
  879. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  880. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  881. expect(cls?.qualifiedName).toBe('Bar');
  882. });
  883. it('extracts anonymous-class overrides from `new T() { ... }`', () => {
  884. // The pattern that breaks the trace through `strategy.foo()` in
  885. // libraries like guava's Splitter: the lambda-returned anonymous
  886. // class overrides abstract methods on the base, but without
  887. // extracting those overrides the interface→impl synthesizer has
  888. // nothing to bridge.
  889. const code = `
  890. package com.example;
  891. abstract class Base {
  892. abstract int compute(int x);
  893. }
  894. public class Factory {
  895. public Base make() {
  896. return new Base() {
  897. @Override
  898. int compute(int x) { return x + 1; }
  899. };
  900. }
  901. }
  902. `;
  903. const result = extractFromSource('Factory.java', code);
  904. const anon = result.nodes.find((n) => n.kind === 'class' && /Base\$anon@/.test(n.name));
  905. expect(anon, 'anonymous Base subclass should be extracted as a class').toBeDefined();
  906. const compute = result.nodes.find(
  907. (n) => n.kind === 'method' && n.name === 'compute' && n.qualifiedName.includes('$anon@')
  908. );
  909. expect(compute, 'override method should be a method on the anon class').toBeDefined();
  910. expect(compute!.qualifiedName).toContain('Factory::make::<Base$anon@');
  911. expect(compute!.qualifiedName.endsWith('::compute')).toBe(true);
  912. // Anon class must extend Base so Phase 5.5 (interface-impl) can bridge.
  913. const extendsRef = result.unresolvedReferences.find(
  914. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base' && r.fromNodeId === anon!.id
  915. );
  916. expect(extendsRef, 'anon class should carry an `extends Base` reference').toBeDefined();
  917. // The enclosing `make` method still emits an instantiates edge to Base —
  918. // anon extraction must not swallow that signal.
  919. const instantiatesRef = result.unresolvedReferences.find(
  920. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Base'
  921. );
  922. expect(instantiatesRef, 'enclosing method should still instantiate Base').toBeDefined();
  923. });
  924. it('extracts anonymous-class overrides inside a lambda body', () => {
  925. // The exact guava pattern: a lambda is passed to a constructor, and the
  926. // lambda body returns `new T() { @Override ... }`. The anon class must
  927. // still surface even though it sits inside a lambda_expression node.
  928. const code = `
  929. package com.example;
  930. interface Strategy {
  931. java.util.Iterator<String> iterator(String s);
  932. }
  933. abstract class BaseIter implements java.util.Iterator<String> {
  934. abstract int separatorStart(int start);
  935. }
  936. public class Splitter {
  937. private final Strategy strategy;
  938. public Splitter(Strategy s) { this.strategy = s; }
  939. public static Splitter on(char c) {
  940. return new Splitter((seq) ->
  941. new BaseIter() {
  942. @Override
  943. int separatorStart(int start) { return start + 1; }
  944. @Override public boolean hasNext() { return false; }
  945. @Override public String next() { return null; }
  946. });
  947. }
  948. }
  949. `;
  950. const result = extractFromSource('Splitter.java', code);
  951. const anon = result.nodes.find((n) => n.kind === 'class' && /BaseIter\$anon@/.test(n.name));
  952. expect(anon, 'anon BaseIter inside the lambda body should be extracted').toBeDefined();
  953. const sepStart = result.nodes.find(
  954. (n) =>
  955. n.kind === 'method' &&
  956. n.name === 'separatorStart' &&
  957. n.qualifiedName.includes('$anon@')
  958. );
  959. expect(sepStart, 'override inside the lambda-returned anon class should be a method node').toBeDefined();
  960. });
  961. });
  962. describe('C# Extraction', () => {
  963. it('should extract class declarations', () => {
  964. const code = `
  965. public class OrderService
  966. {
  967. private readonly IOrderRepository _repository;
  968. public OrderService(IOrderRepository repository)
  969. {
  970. _repository = repository;
  971. }
  972. public async Task<Order> GetOrderAsync(string id)
  973. {
  974. return await _repository.FindByIdAsync(id);
  975. }
  976. }
  977. `;
  978. const result = extractFromSource('OrderService.cs', code);
  979. const classNode = result.nodes.find((n) => n.kind === 'class');
  980. expect(classNode).toBeDefined();
  981. expect(classNode?.name).toBe('OrderService');
  982. expect(classNode?.visibility).toBe('public');
  983. });
  984. it('indexes every record form with the right kind (#831)', () => {
  985. // The grammar parses ALL record forms as record_declaration — there is no
  986. // record_struct_declaration node — so the value-type forms are told apart
  987. // by their `struct` keyword child. Positional one-liners have no body
  988. // block and must still index (the no-body gate is for C/C++ forward
  989. // declarations, not records).
  990. const code = `
  991. namespace Fixture;
  992. public record SimplePositional(int A);
  993. public record WithBody(int A) { public int DoubleIt() => A * 2; }
  994. public record class ExplicitClassRec(string Name);
  995. public record struct ValueRec(int X);
  996. public readonly record struct ReadonlyRec(int X, int Y);
  997. public record DerivedRec(int A, string B) : SimplePositional(A);
  998. public record GenericRec<T>(T Value);
  999. public partial record PartialRec(int A);
  1000. `;
  1001. const result = extractFromSource('Records.cs', code);
  1002. const kindOf = (name: string) => result.nodes.find((n) => n.name === name)?.kind;
  1003. expect(kindOf('SimplePositional')).toBe('class');
  1004. expect(kindOf('WithBody')).toBe('class');
  1005. expect(kindOf('ExplicitClassRec')).toBe('class');
  1006. expect(kindOf('DerivedRec')).toBe('class');
  1007. expect(kindOf('GenericRec')).toBe('class');
  1008. expect(kindOf('PartialRec')).toBe('class');
  1009. // Value-type records are structs, not classes.
  1010. expect(kindOf('ValueRec')).toBe('struct');
  1011. expect(kindOf('ReadonlyRec')).toBe('struct');
  1012. // Members of a bodied record still extract.
  1013. expect(kindOf('DoubleIt')).toBe('method');
  1014. });
  1015. it('indexes primary-constructor classes, including keyed-DI attribute params (#237)', () => {
  1016. // C# 12 primary constructors (`class Foo(IDep dep) { … }`) are parsed
  1017. // natively by the vendored tree-sitter-c-sharp 0.23.x grammar. The worst
  1018. // shape under the previous (older) grammar — an attribute-with-args on a
  1019. // ctor param (`[FromKeyedServices("primary")] …`, the ASP.NET keyed-DI
  1020. // pattern) — used to parse as an ERROR that swallowed the whole class, so
  1021. // the class and all its methods vanished. They now index in every case.
  1022. const code = `
  1023. public class DataService(IMemoryCache cache)
  1024. {
  1025. public void Warm() { }
  1026. }
  1027. public class InstanceService(InstanceManager m, ProfileManager p)
  1028. {
  1029. public void DeployAndLaunchAsync() { }
  1030. public void Deploy() { }
  1031. }
  1032. public partial class UpdateService(int x) : ILifetimeService
  1033. {
  1034. public void Run() { }
  1035. }
  1036. public class K1KeyedDi([FromKeyedServices("primary")] IMemoryCache cache)
  1037. {
  1038. public void Warm() { }
  1039. }
  1040. public record CatalogBrand(int Id, string Name);
  1041. `;
  1042. const result = extractFromSource('Services.cs', code);
  1043. const classNames = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  1044. expect(classNames).toContain('DataService');
  1045. expect(classNames).toContain('InstanceService');
  1046. expect(classNames).toContain('UpdateService'); // partial + base list
  1047. expect(classNames).toContain('K1KeyedDi'); // attribute-arg ctor param — used to vanish entirely
  1048. expect(classNames).toContain('CatalogBrand'); // record
  1049. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  1050. expect(methods).toContain('DeployAndLaunchAsync');
  1051. expect(methods).toContain('Deploy');
  1052. expect(methods).toContain('Run');
  1053. });
  1054. it('keeps a class indexable when a nested enum has #if-guarded members (#237)', () => {
  1055. // A `#if` directive inside an enum member list (the multi-targeting pattern
  1056. // in libraries like Newtonsoft.Json) makes the grammar emit an ERROR that,
  1057. // for a nested enum, detaches the enclosing class's member list — dropping
  1058. // most of the class's methods. A pre-parse pass blanks the directive lines
  1059. // (keeping both branches), so the class and all its methods still index.
  1060. const code = `
  1061. public class Reader
  1062. {
  1063. private enum ReadType
  1064. {
  1065. #if HAVE_DATE_TIME_OFFSET
  1066. ReadAsDateTimeOffset,
  1067. #endif
  1068. ReadAsDouble,
  1069. ReadAsString,
  1070. }
  1071. public void Open() { }
  1072. public void Close() { }
  1073. public int ReadInt() { return 0; }
  1074. }
  1075. `;
  1076. const result = extractFromSource('Reader.cs', code);
  1077. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  1078. // All three methods after the #if-bearing enum must survive.
  1079. expect(methods).toContain('Open');
  1080. expect(methods).toContain('Close');
  1081. expect(methods).toContain('ReadInt');
  1082. // Both enum branches are kept.
  1083. const enumMembers = result.nodes.filter((n) => n.kind === 'enum_member').map((n) => n.name);
  1084. expect(enumMembers).toContain('ReadAsDateTimeOffset');
  1085. expect(enumMembers).toContain('ReadAsDouble');
  1086. });
  1087. });
  1088. describe('PHP Extraction', () => {
  1089. it('should extract class declarations', () => {
  1090. const code = `<?php
  1091. class UserController
  1092. {
  1093. private UserService $userService;
  1094. public function __construct(UserService $userService)
  1095. {
  1096. $this->userService = $userService;
  1097. }
  1098. public function show(string $id): User
  1099. {
  1100. return $this->userService->find($id);
  1101. }
  1102. }
  1103. `;
  1104. const result = extractFromSource('UserController.php', code);
  1105. const classNode = result.nodes.find((n) => n.kind === 'class');
  1106. expect(classNode).toBeDefined();
  1107. expect(classNode?.name).toBe('UserController');
  1108. });
  1109. it('should extract class inheritance (extends) and interface implementation', () => {
  1110. const code = `<?php
  1111. class ChildController extends BaseController implements Serializable, JsonSerializable
  1112. {
  1113. public function serialize(): string
  1114. {
  1115. return json_encode($this);
  1116. }
  1117. }
  1118. `;
  1119. const result = extractFromSource('ChildController.php', code);
  1120. const classNode = result.nodes.find((n) => n.kind === 'class');
  1121. expect(classNode).toBeDefined();
  1122. expect(classNode?.name).toBe('ChildController');
  1123. const extendsRef = result.unresolvedReferences.find(
  1124. (r) => r.referenceKind === 'extends'
  1125. );
  1126. expect(extendsRef).toBeDefined();
  1127. expect(extendsRef?.referenceName).toBe('BaseController');
  1128. const implementsRefs = result.unresolvedReferences.filter(
  1129. (r) => r.referenceKind === 'implements'
  1130. );
  1131. expect(implementsRefs.length).toBe(2);
  1132. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  1133. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  1134. });
  1135. });
  1136. describe('Swift Extraction', () => {
  1137. it('should extract class declarations', () => {
  1138. const code = `
  1139. public class NetworkManager {
  1140. private let session: URLSession
  1141. public init(session: URLSession = .shared) {
  1142. self.session = session
  1143. }
  1144. public func fetchData(from url: URL) async throws -> Data {
  1145. let (data, _) = try await session.data(from: url)
  1146. return data
  1147. }
  1148. }
  1149. `;
  1150. const result = extractFromSource('NetworkManager.swift', code);
  1151. const classNode = result.nodes.find((n) => n.kind === 'class');
  1152. expect(classNode).toBeDefined();
  1153. expect(classNode?.name).toBe('NetworkManager');
  1154. });
  1155. it('should extract function declarations', () => {
  1156. const code = `
  1157. func calculateSum(_ numbers: [Int]) -> Int {
  1158. return numbers.reduce(0, +)
  1159. }
  1160. public func formatCurrency(amount: Double) -> String {
  1161. return String(format: "$%.2f", amount)
  1162. }
  1163. `;
  1164. const result = extractFromSource('utils.swift', code);
  1165. const functions = result.nodes.filter((n) => n.kind === 'function');
  1166. expect(functions.length).toBeGreaterThanOrEqual(1);
  1167. });
  1168. it('should extract struct declarations', () => {
  1169. const code = `
  1170. public struct User {
  1171. let id: UUID
  1172. var name: String
  1173. var email: String
  1174. func displayName() -> String {
  1175. return name
  1176. }
  1177. }
  1178. `;
  1179. const result = extractFromSource('User.swift', code);
  1180. const structNode = result.nodes.find((n) => n.kind === 'struct');
  1181. expect(structNode).toBeDefined();
  1182. expect(structNode?.name).toBe('User');
  1183. });
  1184. it('should extract protocol declarations', () => {
  1185. const code = `
  1186. public protocol Repository {
  1187. associatedtype Entity
  1188. func find(id: String) async throws -> Entity?
  1189. func save(_ entity: Entity) async throws
  1190. }
  1191. `;
  1192. const result = extractFromSource('Repository.swift', code);
  1193. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  1194. expect(protocolNode).toBeDefined();
  1195. expect(protocolNode?.name).toBe('Repository');
  1196. });
  1197. it('should extract class inheritance and protocol conformance', () => {
  1198. const code = `
  1199. class DataRequest: Request {
  1200. func validate() {}
  1201. }
  1202. class UploadRequest: DataRequest, Sendable {
  1203. func upload() {}
  1204. }
  1205. enum AFError: Error {
  1206. case invalidURL
  1207. }
  1208. struct HTTPMethod: RawRepresentable {
  1209. let rawValue: String
  1210. }
  1211. protocol UploadConvertible: URLRequestConvertible {
  1212. func asURLRequest() throws -> URLRequest
  1213. }
  1214. `;
  1215. const result = extractFromSource('Inheritance.swift', code);
  1216. const extendsRefs = result.unresolvedReferences.filter(
  1217. (r) => r.referenceKind === 'extends'
  1218. );
  1219. // DataRequest extends Request
  1220. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  1221. // UploadRequest extends DataRequest and Sendable
  1222. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  1223. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  1224. // AFError extends Error
  1225. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  1226. // HTTPMethod extends RawRepresentable
  1227. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  1228. // UploadConvertible extends URLRequestConvertible
  1229. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  1230. });
  1231. it('indexes Swift properties so they are findable: computed → property, stored → field, static → constant/variable (#1020)', () => {
  1232. const code = `
  1233. struct ReproConfig {
  1234. let reproStoredValue: Int
  1235. var reproComputedFlag: Bool {
  1236. reproStoredValue > 0
  1237. }
  1238. static let sharedLimit = 10
  1239. static var sharedCount = 0
  1240. func reproControlMethod() -> Bool {
  1241. reproComputedFlag
  1242. }
  1243. }
  1244. final class ReproService {
  1245. private let reproClassStored: String = "x"
  1246. var reproClassComputed: Int { reproClassStored.count }
  1247. }
  1248. `;
  1249. const result = extractFromSource('Repro.swift', code);
  1250. const byName = (name: string) => result.nodes.find((n) => n.name === name);
  1251. // Computed properties are the regression this fix targets: before #1020 they
  1252. // were dropped entirely, so search/explore returned nothing for them.
  1253. expect(byName('reproComputedFlag')?.kind).toBe('property');
  1254. expect(byName('reproClassComputed')?.kind).toBe('property');
  1255. // Stored instance properties stay `field` (fixed earlier in #708 — guard it).
  1256. expect(byName('reproStoredValue')?.kind).toBe('field');
  1257. expect(byName('reproClassStored')?.kind).toBe('field');
  1258. // `static let`/`static var` members remain shared constant/variable nodes.
  1259. expect(byName('sharedLimit')?.kind).toBe('constant');
  1260. expect(byName('sharedCount')?.kind).toBe('variable');
  1261. // The control method is unaffected.
  1262. expect(byName('reproControlMethod')?.kind).toBe('method');
  1263. });
  1264. it("attributes a computed property's getter calls to the property, not the type (SwiftUI body flow) (#1020)", () => {
  1265. const code = `
  1266. struct GreetingView {
  1267. let name: String
  1268. var body: some View {
  1269. let prefix = "Hi"
  1270. return VStack {
  1271. Text(greeting(prefix))
  1272. }
  1273. }
  1274. func greeting(_ p: String) -> String { p }
  1275. }
  1276. `;
  1277. const result = extractFromSource('View.swift', code);
  1278. const body = result.nodes.find((n) => n.kind === 'property' && n.name === 'body');
  1279. expect(body).toBeDefined();
  1280. // The getter's call to greeting() must originate from `body` (so a SwiftUI
  1281. // view's render flow is reachable through the property), not flatten onto the
  1282. // enclosing struct.
  1283. const callsFromBody = result.unresolvedReferences.filter(
  1284. (r) => r.fromNodeId === body!.id && r.referenceKind === 'calls'
  1285. );
  1286. expect(callsFromBody.some((r) => r.referenceName === 'greeting')).toBe(true);
  1287. // The getter is walked as a body, so a local declared inside it is NOT
  1288. // node-ified (locals are the data-flow frontier we leave uncovered). Before
  1289. // this fix the generic walker treated such a local as a struct `field`.
  1290. expect(result.nodes.find((n) => n.name === 'prefix')).toBeUndefined();
  1291. });
  1292. it('indexes a Swift protocol property requirement as a findable property (#1020)', () => {
  1293. const code = `
  1294. protocol Themable {
  1295. var accentColor: Color { get }
  1296. var title: String { get set }
  1297. }
  1298. `;
  1299. const result = extractFromSource('Themable.swift', code);
  1300. expect(result.nodes.find((n) => n.name === 'accentColor')?.kind).toBe('property');
  1301. expect(result.nodes.find((n) => n.name === 'title')?.kind).toBe('property');
  1302. });
  1303. });
  1304. describe('Kotlin Extraction', () => {
  1305. it('should extract class declarations', () => {
  1306. const code = `
  1307. class UserRepository(private val database: Database) {
  1308. fun findById(id: String): User? {
  1309. return database.query("SELECT * FROM users WHERE id = ?", id)
  1310. }
  1311. suspend fun save(user: User) {
  1312. database.insert(user)
  1313. }
  1314. }
  1315. `;
  1316. const result = extractFromSource('UserRepository.kt', code);
  1317. const classNode = result.nodes.find((n) => n.kind === 'class');
  1318. expect(classNode).toBeDefined();
  1319. expect(classNode?.name).toBe('UserRepository');
  1320. });
  1321. it('should extract function declarations', () => {
  1322. const code = `
  1323. fun calculateTotal(items: List<Item>): Double {
  1324. return items.sumOf { it.price }
  1325. }
  1326. suspend fun fetchUserData(userId: String): User {
  1327. return api.getUser(userId)
  1328. }
  1329. `;
  1330. const result = extractFromSource('utils.kt', code);
  1331. const functions = result.nodes.filter((n) => n.kind === 'function');
  1332. expect(functions.length).toBeGreaterThanOrEqual(1);
  1333. });
  1334. it('should detect suspend functions as async', () => {
  1335. const code = `
  1336. suspend fun loadData(): List<String> {
  1337. delay(1000)
  1338. return listOf("a", "b", "c")
  1339. }
  1340. `;
  1341. const result = extractFromSource('loader.kt', code);
  1342. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1343. expect(funcNode).toBeDefined();
  1344. expect(funcNode?.isAsync).toBe(true);
  1345. });
  1346. it('should extract fun interface declarations', () => {
  1347. const code = `
  1348. fun interface OnObjectRetainedListener {
  1349. fun onObjectRetained()
  1350. }
  1351. `;
  1352. const result = extractFromSource('listener.kt', code);
  1353. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1354. expect(ifaceNode).toBeDefined();
  1355. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  1356. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1357. expect(methodNode).toBeDefined();
  1358. expect(methodNode?.name).toBe('onObjectRetained');
  1359. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  1360. });
  1361. it('should extract complex fun interface with nested classes', () => {
  1362. const code = `
  1363. fun interface EventListener {
  1364. fun onEvent(event: Event)
  1365. sealed class Event {
  1366. class DumpingHeap : Event()
  1367. }
  1368. }
  1369. `;
  1370. const result = extractFromSource('events.kt', code);
  1371. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1372. expect(ifaceNode).toBeDefined();
  1373. expect(ifaceNode?.name).toBe('EventListener');
  1374. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  1375. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  1376. expect(eventClass).toBeDefined();
  1377. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  1378. expect(dumpingHeap).toBeDefined();
  1379. });
  1380. it('should not affect regular function declarations', () => {
  1381. const code = `
  1382. fun interface MyCallback {
  1383. fun invoke(value: Int)
  1384. }
  1385. fun regularFunction(): String {
  1386. return "hello"
  1387. }
  1388. `;
  1389. const result = extractFromSource('mixed.kt', code);
  1390. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1391. expect(ifaceNode).toBeDefined();
  1392. expect(ifaceNode?.name).toBe('MyCallback');
  1393. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1394. expect(funcNode).toBeDefined();
  1395. expect(funcNode?.name).toBe('regularFunction');
  1396. });
  1397. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  1398. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  1399. // misparse: function_declaration > ERROR("interface Name {") instead of
  1400. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  1401. const code = `
  1402. import java.io.IOException
  1403. fun interface Interceptor {
  1404. @Throws(IOException::class)
  1405. fun intercept(chain: Chain): Response
  1406. }
  1407. `;
  1408. const result = extractFromSource('interceptor.kt', code);
  1409. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1410. expect(ifaceNode).toBeDefined();
  1411. expect(ifaceNode?.name).toBe('Interceptor');
  1412. });
  1413. it('should extract methods from interface with nested fun interface', () => {
  1414. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  1415. // the parent body as ERROR. Methods inside should still be extracted.
  1416. const code = `
  1417. interface WebSocket {
  1418. fun request(): Request
  1419. fun send(text: String): Boolean
  1420. fun cancel()
  1421. fun interface Factory {
  1422. fun newWebSocket(request: Request): WebSocket
  1423. }
  1424. }
  1425. `;
  1426. const result = extractFromSource('websocket.kt', code);
  1427. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  1428. expect(wsIface).toBeDefined();
  1429. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  1430. const methodNames = methods.map((m) => m.name);
  1431. expect(methodNames).toContain('request');
  1432. expect(methodNames).toContain('send');
  1433. expect(methodNames).toContain('cancel');
  1434. });
  1435. it('wraps top-level declarations in a namespace from package_header', () => {
  1436. const code = `
  1437. package com.example.foo
  1438. class Bar {
  1439. fun greet(): String = "hi"
  1440. }
  1441. fun util(): Int = 42
  1442. `;
  1443. const result = extractFromSource('Bar.kt', code);
  1444. const ns = result.nodes.find((n) => n.kind === 'namespace');
  1445. expect(ns?.name).toBe('com.example.foo');
  1446. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1447. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  1448. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  1449. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  1450. const util = result.nodes.find((n) => n.kind === 'function' && n.name === 'util');
  1451. expect(util?.qualifiedName).toBe('com.example.foo::util');
  1452. });
  1453. it('handles a single-segment package', () => {
  1454. const code = `
  1455. package foo
  1456. class Bar
  1457. `;
  1458. const result = extractFromSource('Bar.kt', code);
  1459. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1460. expect(cls?.qualifiedName).toBe('foo::Bar');
  1461. });
  1462. it('does not wrap when no package is declared', () => {
  1463. const code = `
  1464. class Bar {
  1465. fun greet() = "hi"
  1466. }
  1467. `;
  1468. const result = extractFromSource('Bar.kt', code);
  1469. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  1470. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1471. expect(cls?.qualifiedName).toBe('Bar');
  1472. });
  1473. });
  1474. describe('Dart Extraction', () => {
  1475. it('should extract class declarations', () => {
  1476. const code = `
  1477. class UserService {
  1478. final Database _db;
  1479. Future<User> findById(String id) async {
  1480. return await _db.query(id);
  1481. }
  1482. void _privateMethod() {}
  1483. }
  1484. `;
  1485. const result = extractFromSource('service.dart', code);
  1486. const classNode = result.nodes.find((n) => n.kind === 'class');
  1487. expect(classNode).toBeDefined();
  1488. expect(classNode?.name).toBe('UserService');
  1489. expect(classNode?.visibility).toBe('public');
  1490. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1491. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1492. const findById = methodNodes.find((m) => m.name === 'findById');
  1493. expect(findById).toBeDefined();
  1494. expect(findById?.isAsync).toBe(true);
  1495. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1496. expect(privateMethod).toBeDefined();
  1497. expect(privateMethod?.visibility).toBe('private');
  1498. // Dart models a method body as a SIBLING of the signature, so the method
  1499. // node must be extended to span its body (not just the signature line) —
  1500. // required for body-level analysis (callees, the callback synthesizer).
  1501. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1502. });
  1503. it('should extract top-level function declarations', () => {
  1504. const code = `
  1505. void topLevelFunction(String name) {
  1506. print(name);
  1507. }
  1508. `;
  1509. const result = extractFromSource('utils.dart', code);
  1510. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1511. expect(funcNode).toBeDefined();
  1512. expect(funcNode?.name).toBe('topLevelFunction');
  1513. expect(funcNode?.language).toBe('dart');
  1514. });
  1515. it('should extract enum declarations', () => {
  1516. const code = `
  1517. enum Status { active, inactive, pending }
  1518. `;
  1519. const result = extractFromSource('models.dart', code);
  1520. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1521. expect(enumNode).toBeDefined();
  1522. expect(enumNode?.name).toBe('Status');
  1523. });
  1524. it('should extract mixin declarations', () => {
  1525. const code = `
  1526. mixin LoggerMixin {
  1527. void log(String message) {}
  1528. }
  1529. `;
  1530. const result = extractFromSource('mixins.dart', code);
  1531. const classNode = result.nodes.find((n) => n.kind === 'class');
  1532. expect(classNode).toBeDefined();
  1533. expect(classNode?.name).toBe('LoggerMixin');
  1534. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1535. expect(methodNode).toBeDefined();
  1536. expect(methodNode?.name).toBe('log');
  1537. });
  1538. it('should extract extension declarations', () => {
  1539. const code = `
  1540. extension StringExt on String {
  1541. bool get isBlank => trim().isEmpty;
  1542. }
  1543. `;
  1544. const result = extractFromSource('extensions.dart', code);
  1545. const classNode = result.nodes.find((n) => n.kind === 'class');
  1546. expect(classNode).toBeDefined();
  1547. expect(classNode?.name).toBe('StringExt');
  1548. });
  1549. it('should detect static methods', () => {
  1550. const code = `
  1551. class Utils {
  1552. static void doWork() {}
  1553. }
  1554. `;
  1555. const result = extractFromSource('utils.dart', code);
  1556. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1557. expect(methodNode).toBeDefined();
  1558. expect(methodNode?.name).toBe('doWork');
  1559. expect(methodNode?.isStatic).toBe(true);
  1560. });
  1561. it('should detect async functions', () => {
  1562. const code = `
  1563. Future<String> fetchData() async {
  1564. return await http.get('/data');
  1565. }
  1566. `;
  1567. const result = extractFromSource('api.dart', code);
  1568. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1569. expect(funcNode).toBeDefined();
  1570. expect(funcNode?.name).toBe('fetchData');
  1571. expect(funcNode?.isAsync).toBe(true);
  1572. });
  1573. it('should detect private visibility via underscore convention', () => {
  1574. const code = `
  1575. void _privateHelper() {}
  1576. void publicFunction() {}
  1577. `;
  1578. const result = extractFromSource('helpers.dart', code);
  1579. const functions = result.nodes.filter((n) => n.kind === 'function');
  1580. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1581. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1582. expect(privateFunc?.visibility).toBe('private');
  1583. expect(publicFunc?.visibility).toBe('public');
  1584. });
  1585. });
  1586. describe('Import Extraction', () => {
  1587. describe('TypeScript/JavaScript imports', () => {
  1588. it('should extract default imports', () => {
  1589. const code = `import React from 'react';`;
  1590. const result = extractFromSource('app.tsx', code);
  1591. const importNode = result.nodes.find((n) => n.kind === 'import');
  1592. expect(importNode).toBeDefined();
  1593. expect(importNode?.name).toBe('react');
  1594. expect(importNode?.signature).toBe("import React from 'react';");
  1595. });
  1596. it('should extract named imports', () => {
  1597. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1598. const result = extractFromSource('icons.tsx', code);
  1599. const importNode = result.nodes.find((n) => n.kind === 'import');
  1600. expect(importNode).toBeDefined();
  1601. expect(importNode?.name).toBe('@phosphor-icons/react');
  1602. expect(importNode?.signature).toContain('Bug');
  1603. expect(importNode?.signature).toContain('Database');
  1604. });
  1605. it('should extract namespace imports', () => {
  1606. const code = `import * as Icons from '@phosphor-icons/react';`;
  1607. const result = extractFromSource('icons.tsx', code);
  1608. const importNode = result.nodes.find((n) => n.kind === 'import');
  1609. expect(importNode).toBeDefined();
  1610. expect(importNode?.name).toBe('@phosphor-icons/react');
  1611. expect(importNode?.signature).toContain('* as Icons');
  1612. });
  1613. it('should extract side-effect imports', () => {
  1614. const code = `import './styles.css';`;
  1615. const result = extractFromSource('app.tsx', code);
  1616. const importNode = result.nodes.find((n) => n.kind === 'import');
  1617. expect(importNode).toBeDefined();
  1618. expect(importNode?.name).toBe('./styles.css');
  1619. });
  1620. it('should extract mixed imports (default + named)', () => {
  1621. const code = `import React, { useState, useEffect } from 'react';`;
  1622. const result = extractFromSource('app.tsx', code);
  1623. const importNode = result.nodes.find((n) => n.kind === 'import');
  1624. expect(importNode).toBeDefined();
  1625. expect(importNode?.name).toBe('react');
  1626. expect(importNode?.signature).toContain('React');
  1627. expect(importNode?.signature).toContain('useState');
  1628. expect(importNode?.signature).toContain('useEffect');
  1629. });
  1630. it('should extract multiple import statements', () => {
  1631. const code = `
  1632. import React from 'react';
  1633. import { Button } from './components';
  1634. import './styles.css';
  1635. `;
  1636. const result = extractFromSource('app.tsx', code);
  1637. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1638. expect(importNodes.length).toBe(3);
  1639. const names = importNodes.map((n) => n.name);
  1640. expect(names).toContain('react');
  1641. expect(names).toContain('./components');
  1642. expect(names).toContain('./styles.css');
  1643. });
  1644. it('should extract type imports', () => {
  1645. const code = `import type { FC, ReactNode } from 'react';`;
  1646. const result = extractFromSource('types.ts', code);
  1647. const importNode = result.nodes.find((n) => n.kind === 'import');
  1648. expect(importNode).toBeDefined();
  1649. expect(importNode?.name).toBe('react');
  1650. expect(importNode?.signature).toContain('type');
  1651. expect(importNode?.signature).toContain('FC');
  1652. });
  1653. it('should extract aliased named imports', () => {
  1654. const code = `import { useState as useStateAlias } from 'react';`;
  1655. const result = extractFromSource('hooks.ts', code);
  1656. const importNode = result.nodes.find((n) => n.kind === 'import');
  1657. expect(importNode).toBeDefined();
  1658. expect(importNode?.name).toBe('react');
  1659. expect(importNode?.signature).toContain('useState');
  1660. expect(importNode?.signature).toContain('useStateAlias');
  1661. });
  1662. it('should extract relative path imports', () => {
  1663. const code = `import { helper } from '../utils/helper';`;
  1664. const result = extractFromSource('components/Button.tsx', code);
  1665. const importNode = result.nodes.find((n) => n.kind === 'import');
  1666. expect(importNode).toBeDefined();
  1667. expect(importNode?.name).toBe('../utils/helper');
  1668. expect(importNode?.signature).toContain('helper');
  1669. });
  1670. });
  1671. describe('Python imports', () => {
  1672. it('should extract simple import statement', () => {
  1673. const code = `import json`;
  1674. const result = extractFromSource('utils.py', code);
  1675. const importNode = result.nodes.find((n) => n.kind === 'import');
  1676. expect(importNode).toBeDefined();
  1677. expect(importNode?.name).toBe('json');
  1678. });
  1679. it('should extract from import statement', () => {
  1680. const code = `from os import path`;
  1681. const result = extractFromSource('utils.py', code);
  1682. const importNode = result.nodes.find((n) => n.kind === 'import');
  1683. expect(importNode).toBeDefined();
  1684. expect(importNode?.name).toBe('os');
  1685. expect(importNode?.signature).toContain('path');
  1686. });
  1687. it('should extract multiple imports from same module', () => {
  1688. const code = `from typing import List, Dict, Optional`;
  1689. const result = extractFromSource('types.py', code);
  1690. const importNode = result.nodes.find((n) => n.kind === 'import');
  1691. expect(importNode).toBeDefined();
  1692. expect(importNode?.name).toBe('typing');
  1693. expect(importNode?.signature).toContain('List');
  1694. expect(importNode?.signature).toContain('Dict');
  1695. });
  1696. it('should extract multiple import statements', () => {
  1697. const code = `
  1698. import os
  1699. import sys
  1700. `;
  1701. const result = extractFromSource('main.py', code);
  1702. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1703. expect(importNodes.length).toBe(2);
  1704. const names = importNodes.map((n) => n.name);
  1705. expect(names).toContain('os');
  1706. expect(names).toContain('sys');
  1707. });
  1708. it('should extract aliased import', () => {
  1709. const code = `import numpy as np`;
  1710. const result = extractFromSource('data.py', code);
  1711. const importNode = result.nodes.find((n) => n.kind === 'import');
  1712. expect(importNode).toBeDefined();
  1713. expect(importNode?.name).toBe('numpy');
  1714. expect(importNode?.signature).toContain('as np');
  1715. });
  1716. it('should extract relative import', () => {
  1717. const code = `from .utils import helper`;
  1718. const result = extractFromSource('module.py', code);
  1719. const importNode = result.nodes.find((n) => n.kind === 'import');
  1720. expect(importNode).toBeDefined();
  1721. expect(importNode?.name).toBe('.utils');
  1722. expect(importNode?.signature).toContain('helper');
  1723. });
  1724. it('should extract wildcard import', () => {
  1725. const code = `from typing import *`;
  1726. const result = extractFromSource('types.py', code);
  1727. const importNode = result.nodes.find((n) => n.kind === 'import');
  1728. expect(importNode).toBeDefined();
  1729. expect(importNode?.name).toBe('typing');
  1730. expect(importNode?.signature).toContain('*');
  1731. });
  1732. });
  1733. describe('Rust imports', () => {
  1734. it('should extract simple use declaration', () => {
  1735. const code = `use std::io;`;
  1736. const result = extractFromSource('main.rs', code);
  1737. const importNode = result.nodes.find((n) => n.kind === 'import');
  1738. expect(importNode).toBeDefined();
  1739. expect(importNode?.name).toBe('std');
  1740. expect(importNode?.signature).toBe('use std::io;');
  1741. });
  1742. it('should extract scoped use list', () => {
  1743. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1744. const result = extractFromSource('main.rs', code);
  1745. const importNode = result.nodes.find((n) => n.kind === 'import');
  1746. expect(importNode).toBeDefined();
  1747. expect(importNode?.name).toBe('std');
  1748. expect(importNode?.signature).toContain('ffi::OsStr');
  1749. expect(importNode?.signature).toContain('path::Path');
  1750. });
  1751. it('should extract crate imports', () => {
  1752. const code = `use crate::error::Error;`;
  1753. const result = extractFromSource('lib.rs', code);
  1754. const importNode = result.nodes.find((n) => n.kind === 'import');
  1755. expect(importNode).toBeDefined();
  1756. expect(importNode?.name).toBe('crate');
  1757. });
  1758. it('should extract super imports', () => {
  1759. const code = `use super::utils;`;
  1760. const result = extractFromSource('submod.rs', code);
  1761. const importNode = result.nodes.find((n) => n.kind === 'import');
  1762. expect(importNode).toBeDefined();
  1763. expect(importNode?.name).toBe('super');
  1764. });
  1765. it('should extract external crate imports', () => {
  1766. const code = `use serde::{Serialize, Deserialize};`;
  1767. const result = extractFromSource('types.rs', code);
  1768. const importNode = result.nodes.find((n) => n.kind === 'import');
  1769. expect(importNode).toBeDefined();
  1770. expect(importNode?.name).toBe('serde');
  1771. expect(importNode?.signature).toContain('Serialize');
  1772. expect(importNode?.signature).toContain('Deserialize');
  1773. });
  1774. });
  1775. describe('Go imports', () => {
  1776. it('should extract single import', () => {
  1777. const code = `
  1778. package main
  1779. import "fmt"
  1780. `;
  1781. const result = extractFromSource('main.go', code);
  1782. const importNode = result.nodes.find((n) => n.kind === 'import');
  1783. expect(importNode).toBeDefined();
  1784. expect(importNode?.name).toBe('fmt');
  1785. });
  1786. it('should extract grouped imports', () => {
  1787. const code = `
  1788. package main
  1789. import (
  1790. "fmt"
  1791. "os"
  1792. "encoding/json"
  1793. )
  1794. `;
  1795. const result = extractFromSource('main.go', code);
  1796. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1797. expect(importNodes.length).toBe(3);
  1798. const names = importNodes.map((n) => n.name);
  1799. expect(names).toContain('fmt');
  1800. expect(names).toContain('os');
  1801. expect(names).toContain('encoding/json');
  1802. });
  1803. it('should extract aliased import', () => {
  1804. const code = `
  1805. package main
  1806. import f "fmt"
  1807. `;
  1808. const result = extractFromSource('main.go', code);
  1809. const importNode = result.nodes.find((n) => n.kind === 'import');
  1810. expect(importNode).toBeDefined();
  1811. expect(importNode?.name).toBe('fmt');
  1812. expect(importNode?.signature).toContain('f');
  1813. });
  1814. it('should extract dot import', () => {
  1815. const code = `
  1816. package main
  1817. import . "math"
  1818. `;
  1819. const result = extractFromSource('main.go', code);
  1820. const importNode = result.nodes.find((n) => n.kind === 'import');
  1821. expect(importNode).toBeDefined();
  1822. expect(importNode?.name).toBe('math');
  1823. expect(importNode?.signature).toContain('.');
  1824. });
  1825. it('should extract blank import', () => {
  1826. const code = `
  1827. package main
  1828. import _ "github.com/go-sql-driver/mysql"
  1829. `;
  1830. const result = extractFromSource('main.go', code);
  1831. const importNode = result.nodes.find((n) => n.kind === 'import');
  1832. expect(importNode).toBeDefined();
  1833. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1834. expect(importNode?.signature).toContain('_');
  1835. });
  1836. });
  1837. describe('Swift imports', () => {
  1838. it('should extract simple import', () => {
  1839. const code = `import Foundation`;
  1840. const result = extractFromSource('main.swift', code);
  1841. const importNode = result.nodes.find((n) => n.kind === 'import');
  1842. expect(importNode).toBeDefined();
  1843. expect(importNode?.name).toBe('Foundation');
  1844. expect(importNode?.signature).toBe('import Foundation');
  1845. });
  1846. it('should extract @testable import', () => {
  1847. const code = `@testable import Alamofire`;
  1848. const result = extractFromSource('Tests.swift', code);
  1849. const importNode = result.nodes.find((n) => n.kind === 'import');
  1850. expect(importNode).toBeDefined();
  1851. expect(importNode?.name).toBe('Alamofire');
  1852. expect(importNode?.signature).toContain('@testable');
  1853. });
  1854. it('should extract @preconcurrency import', () => {
  1855. const code = `@preconcurrency import Security`;
  1856. const result = extractFromSource('Auth.swift', code);
  1857. const importNode = result.nodes.find((n) => n.kind === 'import');
  1858. expect(importNode).toBeDefined();
  1859. expect(importNode?.name).toBe('Security');
  1860. });
  1861. it('should extract multiple imports', () => {
  1862. const code = `
  1863. import Foundation
  1864. import UIKit
  1865. import Alamofire
  1866. `;
  1867. const result = extractFromSource('App.swift', code);
  1868. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1869. expect(importNodes.length).toBe(3);
  1870. const names = importNodes.map((n) => n.name);
  1871. expect(names).toContain('Foundation');
  1872. expect(names).toContain('UIKit');
  1873. expect(names).toContain('Alamofire');
  1874. });
  1875. });
  1876. describe('Kotlin imports', () => {
  1877. it('should extract simple import', () => {
  1878. const code = `import java.io.IOException`;
  1879. const result = extractFromSource('Main.kt', code);
  1880. const importNode = result.nodes.find((n) => n.kind === 'import');
  1881. expect(importNode).toBeDefined();
  1882. expect(importNode?.name).toBe('java.io.IOException');
  1883. expect(importNode?.signature).toBe('import java.io.IOException');
  1884. });
  1885. it('should extract aliased import', () => {
  1886. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1887. const result = extractFromSource('Utils.kt', code);
  1888. const importNode = result.nodes.find((n) => n.kind === 'import');
  1889. expect(importNode).toBeDefined();
  1890. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1891. expect(importNode?.signature).toContain('as RequestBuilder');
  1892. });
  1893. it('should extract wildcard import', () => {
  1894. const code = `import java.util.concurrent.TimeUnit.*`;
  1895. const result = extractFromSource('Time.kt', code);
  1896. const importNode = result.nodes.find((n) => n.kind === 'import');
  1897. expect(importNode).toBeDefined();
  1898. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1899. expect(importNode?.signature).toContain('.*');
  1900. });
  1901. it('should extract multiple imports', () => {
  1902. const code = `
  1903. import java.io.IOException
  1904. import kotlin.test.assertFailsWith
  1905. import okhttp3.OkHttpClient
  1906. `;
  1907. const result = extractFromSource('Test.kt', code);
  1908. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1909. expect(importNodes.length).toBe(3);
  1910. const names = importNodes.map((n) => n.name);
  1911. expect(names).toContain('java.io.IOException');
  1912. expect(names).toContain('kotlin.test.assertFailsWith');
  1913. expect(names).toContain('okhttp3.OkHttpClient');
  1914. });
  1915. });
  1916. describe('Java imports', () => {
  1917. it('should extract simple import', () => {
  1918. const code = `import java.util.List;`;
  1919. const result = extractFromSource('Main.java', code);
  1920. const importNode = result.nodes.find((n) => n.kind === 'import');
  1921. expect(importNode).toBeDefined();
  1922. expect(importNode?.name).toBe('java.util.List');
  1923. expect(importNode?.signature).toBe('import java.util.List;');
  1924. });
  1925. it('should extract static import', () => {
  1926. const code = `import static java.util.Collections.emptyList;`;
  1927. const result = extractFromSource('Utils.java', code);
  1928. const importNode = result.nodes.find((n) => n.kind === 'import');
  1929. expect(importNode).toBeDefined();
  1930. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1931. expect(importNode?.signature).toContain('static');
  1932. });
  1933. it('should extract wildcard import', () => {
  1934. const code = `import java.util.*;`;
  1935. const result = extractFromSource('App.java', code);
  1936. const importNode = result.nodes.find((n) => n.kind === 'import');
  1937. expect(importNode).toBeDefined();
  1938. expect(importNode?.name).toBe('java.util');
  1939. expect(importNode?.signature).toContain('.*');
  1940. });
  1941. it('should extract nested class import', () => {
  1942. const code = `import java.util.Map.Entry;`;
  1943. const result = extractFromSource('MapUtil.java', code);
  1944. const importNode = result.nodes.find((n) => n.kind === 'import');
  1945. expect(importNode).toBeDefined();
  1946. expect(importNode?.name).toBe('java.util.Map.Entry');
  1947. });
  1948. it('should extract multiple imports', () => {
  1949. const code = `
  1950. import java.util.List;
  1951. import java.util.Map;
  1952. import java.io.IOException;
  1953. `;
  1954. const result = extractFromSource('Service.java', code);
  1955. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1956. expect(importNodes.length).toBe(3);
  1957. const names = importNodes.map((n) => n.name);
  1958. expect(names).toContain('java.util.List');
  1959. expect(names).toContain('java.util.Map');
  1960. expect(names).toContain('java.io.IOException');
  1961. });
  1962. });
  1963. describe('C# imports', () => {
  1964. it('should extract simple using', () => {
  1965. const code = `using System;`;
  1966. const result = extractFromSource('Program.cs', code);
  1967. const importNode = result.nodes.find((n) => n.kind === 'import');
  1968. expect(importNode).toBeDefined();
  1969. expect(importNode?.name).toBe('System');
  1970. expect(importNode?.signature).toBe('using System;');
  1971. });
  1972. it('should extract qualified using', () => {
  1973. const code = `using System.Collections.Generic;`;
  1974. const result = extractFromSource('Utils.cs', code);
  1975. const importNode = result.nodes.find((n) => n.kind === 'import');
  1976. expect(importNode).toBeDefined();
  1977. expect(importNode?.name).toBe('System.Collections.Generic');
  1978. });
  1979. it('should extract static using', () => {
  1980. const code = `using static System.Console;`;
  1981. const result = extractFromSource('App.cs', code);
  1982. const importNode = result.nodes.find((n) => n.kind === 'import');
  1983. expect(importNode).toBeDefined();
  1984. expect(importNode?.name).toBe('System.Console');
  1985. expect(importNode?.signature).toContain('static');
  1986. });
  1987. it('should extract alias using', () => {
  1988. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1989. const result = extractFromSource('Types.cs', code);
  1990. const importNode = result.nodes.find((n) => n.kind === 'import');
  1991. expect(importNode).toBeDefined();
  1992. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1993. expect(importNode?.signature).toContain('MyList =');
  1994. });
  1995. it('should extract multiple usings', () => {
  1996. const code = `
  1997. using System;
  1998. using System.Threading.Tasks;
  1999. using Microsoft.Extensions.DependencyInjection;
  2000. `;
  2001. const result = extractFromSource('Service.cs', code);
  2002. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2003. expect(importNodes.length).toBe(3);
  2004. const names = importNodes.map((n) => n.name);
  2005. expect(names).toContain('System');
  2006. expect(names).toContain('System.Threading.Tasks');
  2007. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  2008. });
  2009. });
  2010. describe('PHP imports', () => {
  2011. it('should extract simple use', () => {
  2012. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  2013. const result = extractFromSource('Test.php', code);
  2014. const importNode = result.nodes.find((n) => n.kind === 'import');
  2015. expect(importNode).toBeDefined();
  2016. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  2017. });
  2018. it('should extract aliased use', () => {
  2019. const code = `<?php use Mockery as m;`;
  2020. const result = extractFromSource('Test.php', code);
  2021. const importNode = result.nodes.find((n) => n.kind === 'import');
  2022. expect(importNode).toBeDefined();
  2023. expect(importNode?.name).toBe('Mockery');
  2024. expect(importNode?.signature).toContain('as m');
  2025. });
  2026. it('should extract function use', () => {
  2027. const code = `<?php use function Illuminate\\Support\\env;`;
  2028. const result = extractFromSource('helpers.php', code);
  2029. const importNode = result.nodes.find((n) => n.kind === 'import');
  2030. expect(importNode).toBeDefined();
  2031. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  2032. expect(importNode?.signature).toContain('function');
  2033. });
  2034. it('should extract grouped use', () => {
  2035. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  2036. const result = extractFromSource('Models.php', code);
  2037. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2038. expect(importNodes.length).toBe(2);
  2039. const names = importNodes.map((n) => n.name);
  2040. expect(names).toContain('Illuminate\\Database\\Model');
  2041. expect(names).toContain('Illuminate\\Database\\Builder');
  2042. });
  2043. it('should extract multiple uses', () => {
  2044. const code = `<?php
  2045. use Illuminate\\Support\\Collection;
  2046. use Illuminate\\Support\\Str;
  2047. use Closure;
  2048. `;
  2049. const result = extractFromSource('Service.php', code);
  2050. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2051. expect(importNodes.length).toBe(3);
  2052. const names = importNodes.map((n) => n.name);
  2053. expect(names).toContain('Illuminate\\Support\\Collection');
  2054. expect(names).toContain('Illuminate\\Support\\Str');
  2055. expect(names).toContain('Closure');
  2056. });
  2057. it('should extract include/require (+_once) static paths as imports (#660)', () => {
  2058. const code = `<?php
  2059. require_once("lib.php");
  2060. include 'other.php';
  2061. require 'r.php';
  2062. include_once("io.php");
  2063. `;
  2064. const result = extractFromSource('page.php', code);
  2065. const names = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  2066. expect(names).toContain('lib.php');
  2067. expect(names).toContain('other.php');
  2068. expect(names).toContain('r.php');
  2069. expect(names).toContain('io.php');
  2070. });
  2071. it('should skip dynamic include/require with no static path (#660)', () => {
  2072. const code = `<?php
  2073. require_once(__DIR__ . '/dyn.php');
  2074. include $file;
  2075. include "tpl/{$name}.php";
  2076. `;
  2077. const result = extractFromSource('page.php', code);
  2078. const imports = result.nodes.filter((n) => n.kind === 'import');
  2079. expect(imports).toHaveLength(0);
  2080. });
  2081. it('should extract include alongside namespace use without interference (#660)', () => {
  2082. const code = `<?php
  2083. use App\\Service\\Mailer;
  2084. require_once("bootstrap.php");
  2085. `;
  2086. const result = extractFromSource('page.php', code);
  2087. const names = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  2088. expect(names).toContain('App\\Service\\Mailer');
  2089. expect(names).toContain('bootstrap.php');
  2090. });
  2091. });
  2092. describe('Ruby imports', () => {
  2093. it('should extract require', () => {
  2094. const code = `require 'json'`;
  2095. const result = extractFromSource('app.rb', code);
  2096. const importNode = result.nodes.find((n) => n.kind === 'import');
  2097. expect(importNode).toBeDefined();
  2098. expect(importNode?.name).toBe('json');
  2099. expect(importNode?.signature).toBe("require 'json'");
  2100. });
  2101. it('should extract require with path', () => {
  2102. const code = `require 'active_support/core_ext/string'`;
  2103. const result = extractFromSource('config.rb', code);
  2104. const importNode = result.nodes.find((n) => n.kind === 'import');
  2105. expect(importNode).toBeDefined();
  2106. expect(importNode?.name).toBe('active_support/core_ext/string');
  2107. });
  2108. it('should extract require_relative', () => {
  2109. const code = `require_relative '../test_helper'`;
  2110. const result = extractFromSource('test/my_test.rb', code);
  2111. const importNode = result.nodes.find((n) => n.kind === 'import');
  2112. expect(importNode).toBeDefined();
  2113. expect(importNode?.name).toBe('../test_helper');
  2114. expect(importNode?.signature).toContain('require_relative');
  2115. });
  2116. it('should not extract non-require calls', () => {
  2117. const code = `puts 'hello'`;
  2118. const result = extractFromSource('app.rb', code);
  2119. const importNode = result.nodes.find((n) => n.kind === 'import');
  2120. expect(importNode).toBeUndefined();
  2121. });
  2122. it('should extract multiple requires', () => {
  2123. const code = `
  2124. require 'json'
  2125. require 'yaml'
  2126. require_relative 'helper'
  2127. `;
  2128. const result = extractFromSource('lib.rb', code);
  2129. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2130. expect(importNodes.length).toBe(3);
  2131. const names = importNodes.map((n) => n.name);
  2132. expect(names).toContain('json');
  2133. expect(names).toContain('yaml');
  2134. expect(names).toContain('helper');
  2135. });
  2136. });
  2137. describe('Ruby modules', () => {
  2138. it('should extract module as module node with containment', () => {
  2139. const code = `
  2140. module CachedCounting
  2141. def self.disable
  2142. @enabled = false
  2143. end
  2144. def perform_increment!(key, count)
  2145. write_cache!(key, count)
  2146. end
  2147. end
  2148. `;
  2149. const result = extractFromSource('concerns/cached_counting.rb', code);
  2150. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  2151. expect(moduleNode).toBeDefined();
  2152. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  2153. // Methods inside module should have module-qualified names
  2154. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  2155. expect(disableMethod).toBeDefined();
  2156. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  2157. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  2158. expect(incrementMethod).toBeDefined();
  2159. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  2160. // Containment edge from module to methods
  2161. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  2162. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  2163. });
  2164. it('should handle nested modules with classes', () => {
  2165. const code = `
  2166. module Discourse
  2167. module Auth
  2168. class AuthProvider
  2169. def authenticate(params)
  2170. validate(params)
  2171. end
  2172. end
  2173. end
  2174. end
  2175. `;
  2176. const result = extractFromSource('lib/auth.rb', code);
  2177. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  2178. expect(discourseModule).toBeDefined();
  2179. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  2180. expect(authModule).toBeDefined();
  2181. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  2182. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  2183. expect(authProvider).toBeDefined();
  2184. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  2185. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  2186. expect(authMethod).toBeDefined();
  2187. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  2188. });
  2189. });
  2190. describe('PHP return type capture (#608)', () => {
  2191. it('captures self/static factory returns as the `self` marker; primitives as undefined', () => {
  2192. const code = `<?php
  2193. class ApiClient {
  2194. public static function for(string $c): self { return new self; }
  2195. public static function make(): static { return new static; }
  2196. public function send(array $p): array { return []; }
  2197. }`;
  2198. const result = extractFromSource('ApiClient.php', code);
  2199. expect(result.nodes.find((n) => n.name === 'for' && n.kind === 'method')?.returnType).toBe('self');
  2200. expect(result.nodes.find((n) => n.name === 'make' && n.kind === 'method')?.returnType).toBe('self');
  2201. // `array` is not a class to chain on → no return type recorded.
  2202. expect(result.nodes.find((n) => n.name === 'send' && n.kind === 'method')?.returnType).toBeUndefined();
  2203. });
  2204. it('captures a concrete return type as its short class name', () => {
  2205. const code = `<?php
  2206. namespace App;
  2207. class WidgetFactory { public static function make(): Widget { return new Widget(); } }`;
  2208. const result = extractFromSource('WidgetFactory.php', code);
  2209. expect(result.nodes.find((n) => n.name === 'make' && n.kind === 'method')?.returnType).toBe('Widget');
  2210. });
  2211. });
  2212. describe('C/C++ return type capture (#645)', () => {
  2213. it('captures the normalized return type of a C++ method/function', () => {
  2214. const code = `
  2215. struct Widget { void draw(); };
  2216. class Factory { public: static Widget create(); };
  2217. Widget Factory::create() { return Widget(); }
  2218. void doNothing() {}
  2219. `;
  2220. const result = extractFromSource('f.cpp', code);
  2221. const create = result.nodes.find(
  2222. (n) => n.name === 'create' && (n.kind === 'method' || n.kind === 'function')
  2223. );
  2224. expect(create?.returnType).toBe('Widget');
  2225. // A `void` return records no type, so resolution never tries to resolve a
  2226. // method on it.
  2227. const doNothing = result.nodes.find((n) => n.name === 'doNothing');
  2228. expect(doNothing).toBeDefined();
  2229. expect(doNothing?.returnType).toBeUndefined();
  2230. });
  2231. it('unwraps a smart-pointer return type to its pointee', () => {
  2232. const code = `
  2233. #include <memory>
  2234. struct Widget {};
  2235. std::unique_ptr<Widget> makeWidget() { return nullptr; }
  2236. `;
  2237. const result = extractFromSource('f.cpp', code);
  2238. const make = result.nodes.find((n) => n.name === 'makeWidget');
  2239. expect(make?.returnType).toBe('Widget');
  2240. });
  2241. });
  2242. describe('C++ macro-prefixed class/struct misparse (#946 → recovered in #1061)', () => {
  2243. // An export/visibility macro before the class name (`class MACRO Name :
  2244. // public Base { … }`) makes tree-sitter read `class MACRO` as an elaborated
  2245. // type and the whole declaration as a function_definition named after the
  2246. // class — a phantom `function` that polluted callers/impact/blast-radius.
  2247. // #946 dropped that phantom; #1061's preParse (`blankCppExportMacros`) now
  2248. // blanks the ALL-CAPS macro before parsing, so the class parses normally and
  2249. // is *recovered* — node, members, and base edge all present — not just
  2250. // de-phantomed. The #946 drop survives as the fallback for any residual
  2251. // misparse the blanking doesn't catch.
  2252. it('recovers a macro-annotated class that inherits (no phantom, real class + base edge)', () => {
  2253. const code = `#pragma once
  2254. #define MAPCORE_EXPORT __attribute__((visibility("default")))
  2255. class DataProvider {
  2256. public:
  2257. virtual bool Request(void* param) = 0;
  2258. };
  2259. class MAPCORE_EXPORT LocalDataProvider : public DataProvider
  2260. {
  2261. public:
  2262. LocalDataProvider(int dataType);
  2263. virtual bool Request(void* param) override;
  2264. };
  2265. `;
  2266. // A header rich in C++ (class / public: / virtual) detects as C++ — the
  2267. // issue's exact scenario (a `.h` file). Guard it so a detection regression
  2268. // can't make this test pass for the wrong reason.
  2269. expect(detectLanguage('provider.h', code)).toBe('cpp');
  2270. const result = extractFromSource('provider.h', code);
  2271. // The misparse used to surface as `function | LocalDataProvider` spanning
  2272. // the whole class body — a false caller in the graph. It's gone.
  2273. expect(
  2274. result.nodes.find((n) => n.name === 'LocalDataProvider' && n.kind === 'function')
  2275. ).toBeUndefined();
  2276. // …and the class is now recovered (was dropped under #946), with its
  2277. // `extends DataProvider` edge — the whole point of #1061.
  2278. expect(result.nodes.find((n) => n.name === 'LocalDataProvider')?.kind).toBe('class');
  2279. expect(
  2280. result.unresolvedReferences.find(
  2281. (r) => r.referenceKind === 'extends' && r.referenceName === 'DataProvider'
  2282. )
  2283. ).toBeTruthy();
  2284. // The sibling class without the macro is unaffected — still a class.
  2285. expect(result.nodes.find((n) => n.name === 'DataProvider')?.kind).toBe('class');
  2286. });
  2287. it('recovers the struct variant too, without disturbing a genuine class', () => {
  2288. const code = `
  2289. #define API __declspec(dllexport)
  2290. struct API Widget : public Base { int x; };
  2291. class Plain : public Base { public: int y; };
  2292. `;
  2293. const result = extractFromSource('widget.cpp', code);
  2294. // `struct MACRO Name : Base { … }` misparses the same way — no phantom
  2295. // function, and the struct is recovered with its base edge.
  2296. expect(
  2297. result.nodes.find((n) => n.name === 'Widget' && n.kind === 'function')
  2298. ).toBeUndefined();
  2299. expect(result.nodes.find((n) => n.name === 'Widget')?.kind).toBe('struct');
  2300. // A normal class with a base clause and no macro is untouched.
  2301. expect(result.nodes.find((n) => n.name === 'Plain')?.kind).toBe('class');
  2302. const exts = result.unresolvedReferences
  2303. .filter((r) => r.referenceKind === 'extends')
  2304. .map((r) => r.referenceName);
  2305. expect(exts.filter((n) => n === 'Base').length).toBe(2); // Widget + Plain both extend Base
  2306. });
  2307. });
  2308. describe('C++ export-macro class recovery (#1061)', () => {
  2309. // Unreal-Engine style: `class MYGAME_API UMyComponent : public UActorComponent`.
  2310. // The leading `*_API` macro alone (base clause or not) triggers the #946
  2311. // misparse and dropped the class — breaking subclass / type-hierarchy /
  2312. // inheritance-impact queries for effectively every gameplay class in a UE
  2313. // project. blankCppExportMacros recovers them.
  2314. it('recovers UE *_API classes and the inheritance edge (the issue repro)', () => {
  2315. const code = `class ENGINE_API UActorComponent { };
  2316. class MYGAME_API UMyComponent : public UActorComponent { };
  2317. `;
  2318. const result = extractFromSource('ue.cpp', code);
  2319. const classes = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  2320. expect(classes).toContain('UActorComponent'); // macro, no base — also was dropped
  2321. expect(classes).toContain('UMyComponent');
  2322. expect(result.nodes.find((n) => n.kind === 'function')).toBeUndefined(); // no phantom
  2323. expect(
  2324. result.unresolvedReferences.find(
  2325. (r) => r.referenceKind === 'extends' && r.referenceName === 'UActorComponent'
  2326. )
  2327. ).toBeTruthy();
  2328. });
  2329. it('blankCppExportMacros blanks only the header macro, offset-preserving', () => {
  2330. // Blanking replaces the macro with equal-length spaces, so the output is
  2331. // byte-for-byte the same length and identical *except* the macro is gone —
  2332. // every downstream line/column stays exact.
  2333. const check = (inp: string, macro: string, rest: string) => {
  2334. const out = blankCppExportMacros(inp);
  2335. expect(out.length).toBe(inp.length); // every byte offset preserved
  2336. expect(out).not.toContain(macro); // the macro token is blanked
  2337. expect(out.replace(/ +/g, ' ')).toBe(rest); // nothing else changed
  2338. };
  2339. // Generalizes across the export-macro space: UE _API, Qt/Boost _EXPORT,
  2340. // LLVM _ABI, bare API.
  2341. check(
  2342. 'class MYGAME_API UMyComponent : public UActorComponent { };',
  2343. 'MYGAME_API',
  2344. 'class UMyComponent : public UActorComponent { };'
  2345. );
  2346. check('struct MAPCORE_EXPORT W : B {}', 'MAPCORE_EXPORT', 'struct W : B {}');
  2347. check('class LLVM_ABI Foo {}', 'LLVM_ABI', 'class Foo {}');
  2348. });
  2349. it('does NOT blank an all-caps class NAME or an elaborated-type var decl', () => {
  2350. // The name itself being ALL-CAPS (with or without a base) must survive —
  2351. // the macro is only the token *before* the name, gated on a `: { ` def.
  2352. for (const c of [
  2353. 'class FOO { int x; };',
  2354. 'class FOO : public Base { int x; };',
  2355. 'struct BAR : public Base { int y; };',
  2356. 'enum class COLOR { Red, Green };',
  2357. // elaborated-type variable declarations end in ; = [ — never : {
  2358. 'struct FOO bar;',
  2359. 'class FOO obj = make();',
  2360. 'struct FOO arr[10];',
  2361. // a *_API macro used as an ordinary value elsewhere
  2362. 'int x = SOME_API; void f() { use(MYMODULE_API); }',
  2363. ]) {
  2364. expect(blankCppExportMacros(c)).toBe(c);
  2365. }
  2366. // And the all-caps-named class keeps its base edge through real extraction.
  2367. const result = extractFromSource('ctrl.cpp', 'class FOO : public Base { int x; };');
  2368. expect(result.nodes.find((n) => n.name === 'FOO')?.kind).toBe('class');
  2369. expect(
  2370. result.unresolvedReferences.find(
  2371. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base'
  2372. )
  2373. ).toBeTruthy();
  2374. });
  2375. });
  2376. describe('Metal shader extraction (#1121)', () => {
  2377. // Metal Shading Language (≈ C++14) parses with the C++ grammar. MSL puts
  2378. // `[[attribute]]` annotations AFTER the declarator — a position
  2379. // tree-sitter-cpp misparses: a struct field with a trailing attribute
  2380. // emitted a spurious `extends` ref from the struct to the field's own type.
  2381. // blankMetalAttributes (preParse, `.metal`-gated) blanks them so extraction
  2382. // matches plain C++.
  2383. const METAL = `#include <metal_stdlib>
  2384. using namespace metal;
  2385. struct VertexIn {
  2386. float3 position [[attribute(0)]];
  2387. float2 texCoord [[attribute(1)]];
  2388. };
  2389. struct VertexOut {
  2390. float4 position [[position]];
  2391. float2 texCoord;
  2392. };
  2393. struct Uniforms {
  2394. float4x4 modelViewProjection;
  2395. };
  2396. static float4 applyGamma(float4 color) {
  2397. return pow(color, float4(1.0 / 2.2));
  2398. }
  2399. vertex VertexOut vertexShader(VertexIn in [[stage_in]],
  2400. constant Uniforms &uniforms [[buffer(0)]]) {
  2401. VertexOut out;
  2402. out.position = uniforms.modelViewProjection * float4(in.position, 1.0);
  2403. out.texCoord = in.texCoord;
  2404. return out;
  2405. }
  2406. fragment float4 fragmentShader(VertexOut in [[stage_in]],
  2407. texture2d<float> colorTexture [[texture(0)]],
  2408. sampler textureSampler [[sampler(0)]]) {
  2409. float4 color = colorTexture.sample(textureSampler, in.texCoord);
  2410. return applyGamma(color);
  2411. }
  2412. kernel void computeBlur(texture2d<float, access::read> inTexture [[texture(0)]],
  2413. texture2d<float, access::write> outTexture [[texture(1)]],
  2414. uint2 gid [[thread_position_in_grid]]) {
  2415. float4 color = inTexture.read(gid);
  2416. outTexture.write(color, gid);
  2417. }
  2418. `;
  2419. it('extracts vertex/fragment/kernel functions, structs, and calls from a .metal file', () => {
  2420. const result = extractFromSource('Shaders.metal', METAL);
  2421. expect(result.errors).toHaveLength(0);
  2422. const functions = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  2423. expect(functions).toEqual(
  2424. expect.arrayContaining(['applyGamma', 'vertexShader', 'fragmentShader', 'computeBlur'])
  2425. );
  2426. const structs = result.nodes.filter((n) => n.kind === 'struct').map((n) => n.name);
  2427. expect(structs).toEqual(expect.arrayContaining(['VertexIn', 'VertexOut', 'Uniforms']));
  2428. expect(result.nodes.find((n) => n.kind === 'import')?.name).toBe('metal_stdlib');
  2429. // Attribute blanking is offset-preserving, so positions stay exact.
  2430. const vertexFn = result.nodes.find((n) => n.name === 'vertexShader')!;
  2431. expect(vertexFn.startLine).toBe(22);
  2432. // The shader call graph connects: fragmentShader → applyGamma.
  2433. expect(
  2434. result.unresolvedReferences.find(
  2435. (r) => r.referenceKind === 'calls' && r.referenceName === 'applyGamma'
  2436. )
  2437. ).toBeTruthy();
  2438. // The regression the blanking fixes: field attributes (`float3 position
  2439. // [[attribute(0)]];`) misparsed into `extends` refs from the struct to the
  2440. // field's type — a wrong inheritance edge whenever the repo defines that
  2441. // type itself (simd typedefs in a shared ShaderTypes.h are common).
  2442. expect(result.unresolvedReferences.filter((r) => r.referenceKind === 'extends')).toHaveLength(0);
  2443. });
  2444. it('blankMetalAttributes blanks every attribute form, offset-preserving', () => {
  2445. const inp = [
  2446. 'float4 position [[position]];',
  2447. 'constant Uniforms &u [[buffer(0)]]',
  2448. 'float2 uv [[user(locn0)]];',
  2449. 'device float *out [[buffer(0), raster_order_group(0)]]',
  2450. ].join('\n');
  2451. const out = blankMetalAttributes(inp);
  2452. expect(out.length).toBe(inp.length); // every byte offset preserved
  2453. expect(out).not.toContain('[[');
  2454. // Nothing but the attributes changed: collapsing the blank runs gives the
  2455. // plain declarations back, newlines untouched.
  2456. expect(out.split('\n').map((l) => l.replace(/ +/g, ' ').trimEnd())).toEqual([
  2457. 'float4 position ;',
  2458. 'constant Uniforms &u',
  2459. 'float2 uv ;',
  2460. 'device float *out',
  2461. ]);
  2462. });
  2463. it('blankMetalAttributes never touches non-attribute [[ sequences', () => {
  2464. for (const c of [
  2465. 'auto x = arr[[]{ return 0; }()];', // lambda in subscript — the only other [[ in C++-family code
  2466. 'int y = a[b[i]];', // nested subscript
  2467. 'int z = 1;', // no [[ at all — early-return path
  2468. ]) {
  2469. expect(blankMetalAttributes(c)).toBe(c);
  2470. }
  2471. });
  2472. });
  2473. describe('C++ forward declarations do not mint phantom class nodes (#1093)', () => {
  2474. // `class Foo;` parses as a bodiless class_specifier. Repeated across headers,
  2475. // each forward decl minted a phantom bodiless `class` node that crowded out —
  2476. // and could be picked as the blast-radius representative over — the single
  2477. // real definition. Bodiless struct/enum specifiers were already skipped;
  2478. // classes now are too, but ONLY for C/C++ (opt-in flag), never for languages
  2479. // where a bodiless class is a complete definition.
  2480. it('keeps only the real definition, dropping repeated forward decls', () => {
  2481. const code = `
  2482. class APXCharacter; // forward decl (header 1)
  2483. class APXCharacter; // forward decl (header 2)
  2484. friend class APXCharacter; // elaborated / friend forward reference
  2485. class APXCharacter { // the one real definition
  2486. int hp;
  2487. void takeDamage(int amount) { hp -= amount; }
  2488. };
  2489. `;
  2490. const result = extractFromSource('character.cpp', code);
  2491. const classes = result.nodes.filter(
  2492. (n) => n.kind === 'class' && n.name === 'APXCharacter'
  2493. );
  2494. // Exactly one class node, and it's the definition (carries the member).
  2495. expect(classes).toHaveLength(1);
  2496. expect(classes[0].startLine).toBe(6);
  2497. expect(
  2498. result.nodes.some((n) => n.kind === 'method' && n.name === 'takeDamage')
  2499. ).toBe(true);
  2500. });
  2501. it('elaborated type references in declarations create no phantom class', () => {
  2502. // `class Foo obj;` is a variable declaration using an elaborated type, not
  2503. // a class definition — it must not mint a `Foo` class node.
  2504. const result = extractFromSource('use.cpp', 'class Foo;\nvoid f() { class Foo *p = nullptr; (void)p; }\n');
  2505. expect(result.nodes.filter((n) => n.kind === 'class' && n.name === 'Foo')).toHaveLength(0);
  2506. });
  2507. it('does NOT affect languages where a bodiless class is complete', () => {
  2508. // Kotlin `class Empty` and Scala `trait`/`case object`/`class` with no body
  2509. // are complete definitions — the C/C++-only skip must leave them indexed.
  2510. const kt = extractFromSource('Empty.kt', 'class Empty\nclass Full { val x = 1 }\n');
  2511. const ktClasses = kt.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  2512. expect(ktClasses).toContain('Empty');
  2513. expect(ktClasses).toContain('Full');
  2514. const scala = extractFromSource('M.scala', 'trait Marker\ncase object Red\nclass Foo\n');
  2515. const scalaNames = scala.nodes
  2516. .filter((n) => ['class', 'trait', 'interface'].includes(n.kind))
  2517. .map((n) => n.name);
  2518. expect(scalaNames).toEqual(expect.arrayContaining(['Marker', 'Red', 'Foo']));
  2519. });
  2520. });
  2521. describe('C++ reference-return method/function names (#1093 follow-up)', () => {
  2522. // An inline method/function returning a reference parses with a
  2523. // `reference_declarator` wrapping the `function_declarator`. That wrapper
  2524. // wasn't unwrapped (only `pointer_declarator` was), so the name captured the
  2525. // whole declarator — `const int& getRef() const {…}` became the method named
  2526. // "& getRef() const" instead of "getRef", polluting search and callers. Very
  2527. // common in Unreal Engine headers (`const FGameplayTagContainer& GetActiveTags() const`).
  2528. const namesOf = (code: string) =>
  2529. extractFromSource('r.cpp', code).nodes
  2530. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2531. .map((n) => n.name);
  2532. it('names an inline reference-returning method by its identifier, not the declarator', () => {
  2533. const names = namesOf('class C {\npublic:\n const int& getRef() const { return x; }\n int& mutRef() { return x; }\n int x;\n};');
  2534. expect(names).toContain('getRef');
  2535. expect(names).toContain('mutRef');
  2536. // No name leaks the reference sigil or the parameter/qualifier tail.
  2537. expect(names.some((n) => /[&()]/.test(n))).toBe(false);
  2538. });
  2539. it('handles rvalue-reference returns and reference-returning free functions', () => {
  2540. expect(namesOf('class C { int&& take() { return 1; } };')).toContain('take');
  2541. expect(namesOf('const int& globalRef() { static int x; return x; }')).toContain('globalRef');
  2542. });
  2543. it('leaves pointer, value, and out-of-line reference returns unchanged (controls)', () => {
  2544. expect(namesOf('class C { int* getPtr() { return &x; } int x; };')).toContain('getPtr');
  2545. expect(namesOf('class C { int getVal() const { return x; } int x; };')).toContain('getVal');
  2546. // Out-of-line `T& C::f()` already resolves via the qualified-name hook.
  2547. expect(namesOf('const int& C::getRef() const { return x; }')).toContain('getRef');
  2548. });
  2549. });
  2550. describe('C++ user-defined conversion operator names (#1093 follow-up)', () => {
  2551. // A conversion operator's declarator is an `operator_cast` (target type +
  2552. // `() const` tail). It was named with the whole declarator —
  2553. // `operator EALSMovementState() const` — so it didn't match the symbolic-
  2554. // overload style (`operator+`) and carried parameter noise. It's now named
  2555. // `operator <type>`. Common in Unreal Engine enum-wrapper structs.
  2556. const namesOf = (code: string) =>
  2557. extractFromSource('o.cpp', code).nodes
  2558. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2559. .map((n) => n.name);
  2560. it('names a conversion operator as "operator <type>", not the full declarator', () => {
  2561. const names = namesOf('struct S {\n operator int() const { return 1; }\n operator bool() { return true; }\n int x;\n};');
  2562. expect(names).toContain('operator int');
  2563. expect(names).toContain('operator bool');
  2564. expect(names.some((n) => n.includes('(') || n.includes('const'))).toBe(false);
  2565. });
  2566. it('handles a user-type conversion operator', () => {
  2567. expect(
  2568. namesOf('struct FALSMovementState {\n operator EALSMovementState() const { return State; }\n EALSMovementState State;\n};')
  2569. ).toContain('operator EALSMovementState');
  2570. });
  2571. it('leaves symbolic operator overloads unchanged (control)', () => {
  2572. const names = namesOf('struct S {\n S operator+(const S& o) const { return o; }\n int& operator[](int i) { return x; }\n int x;\n};');
  2573. expect(names).toContain('operator+');
  2574. expect(names).toContain('operator[]'); // reference-returning subscript, name still clean
  2575. });
  2576. });
  2577. describe('C++ macro-prefixed function names (#1093 follow-up)', () => {
  2578. // An unknown inline-specifier macro before the return type
  2579. // (`FORCEINLINE FString GetName(…)`) threw tree-sitter into error recovery:
  2580. // the macro became the return type and — for a non-primitive return — the
  2581. // return type was glued onto the name (`"FString GetName"`), so the function
  2582. // was unfindable by name and its callers didn't link. `blankCppInlineMacros`
  2583. // blanks the known UE inline macros before parsing (offset-preserving), the
  2584. // same recover-don't-drop approach as the macro-annotated-class fix. Pervasive
  2585. // in Unreal Engine (`FORCEINLINE`).
  2586. const infoOf = (code: string) =>
  2587. extractFromSource('m.cpp', code).nodes
  2588. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2589. .map((n) => ({ name: n.name, ret: n.returnType }));
  2590. it('recovers the real name AND return type of a FORCEINLINE function', () => {
  2591. expect(infoOf('static FORCEINLINE FString GetName(int V) { return H(V); }')).toEqual([
  2592. { name: 'GetName', ret: 'FString' },
  2593. ]);
  2594. });
  2595. it('handles the templated UE helper shape (GetEnumerationToString)', () => {
  2596. const names = infoOf(
  2597. 'template <typename E> static FORCEINLINE FString GetEnumerationToString(const E V) { return H(V); }'
  2598. ).map((x) => x.name);
  2599. expect(names).toContain('GetEnumerationToString');
  2600. });
  2601. it('handles FORCENOINLINE / FORCEINLINE_DEBUGGABLE, methods, void, and reference returns', () => {
  2602. expect(infoOf('FORCENOINLINE FString A(int V){return H(V);}').map((x) => x.name)).toContain('A');
  2603. expect(infoOf('FORCEINLINE_DEBUGGABLE FString B(int V){return H(V);}').map((x) => x.name)).toContain('B');
  2604. expect(infoOf('struct S { FORCEINLINE FString GetName(int V) { return H(V); } };').map((x) => x.name)).toContain('GetName');
  2605. expect(infoOf('static FORCEINLINE void DoThing(int V) { H(V); }').map((x) => x.name)).toContain('DoThing');
  2606. expect(infoOf('static FORCEINLINE const FString& GetRef(int V) { return H(V); }').map((x) => x.name)).toContain('GetRef');
  2607. });
  2608. it('handles common third-party inline macros (pugixml, Godot, Boost, generic)', () => {
  2609. // pugixml: PUGI__FN before the return type; PUGIXML_FUNCTION (linkage)
  2610. // between the return type and the name — both recovered.
  2611. expect(infoOf('PUGI__FN void* default_allocate(size_t n) { return H(n); }').map((x) => x.name)).toContain('default_allocate');
  2612. expect(infoOf('PUGI__FN_NO_INLINE bool strequal(const char_t* a) { return H(a); }').map((x) => x.name)).toContain('strequal');
  2613. expect(infoOf('std::string PUGIXML_FUNCTION as_utf8(const wchar_t* s) { return H(s); }').map((x) => x.name)).toContain('as_utf8');
  2614. // Godot / Boost / generic inline hints
  2615. expect(infoOf('_FORCE_INLINE_ String get_name() const { return H(); }').map((x) => x.name)).toContain('get_name');
  2616. expect(infoOf('_ALWAYS_INLINE_ Vector2 get_pos() { return H(); }').map((x) => x.name)).toContain('get_pos');
  2617. expect(infoOf('BOOST_FORCEINLINE result_type call() { return H(); }').map((x) => x.name)).toContain('call');
  2618. expect(infoOf('ALWAYS_INLINE MyType compute() { return H(); }').map((x) => x.name)).toContain('compute');
  2619. });
  2620. it('leaves ordinary functions and real all-caps return types untouched (controls)', () => {
  2621. expect(infoOf('FString GetName(int V) { return H(V); }')).toEqual([{ name: 'GetName', ret: 'FString' }]);
  2622. // A real all-caps type that is NOT a listed inline macro stays the return type.
  2623. expect(infoOf('HRESULT DoIt(int V) { return H(V); }')).toEqual([{ name: 'DoIt', ret: 'HRESULT' }]);
  2624. });
  2625. it('blankCppInlineMacros preserves offsets and only touches specifier-position macros', () => {
  2626. // Blanked with equal-length spaces (byte offsets preserved).
  2627. expect(blankCppInlineMacros('FORCEINLINE FString F()')).toBe(' FString F()');
  2628. expect(blankCppInlineMacros('FORCEINLINE FString F()')).toHaveLength('FORCEINLINE FString F()'.length);
  2629. // Not in specifier position → untouched: string literals, expressions,
  2630. // longer word (`FORCEINLINE_COUNT`), and the fast path.
  2631. expect(blankCppInlineMacros('const char* s = "FORCEINLINE";')).toBe('const char* s = "FORCEINLINE";');
  2632. expect(blankCppInlineMacros('x = FORCEINLINE + 1;')).toBe('x = FORCEINLINE + 1;');
  2633. expect(blankCppInlineMacros('int FORCEINLINE_COUNT = 3;')).toBe('int FORCEINLINE_COUNT = 3;');
  2634. expect(blankCppInlineMacros('no macros here')).toBe('no macros here');
  2635. });
  2636. });
  2637. describe('C++ universal macro-mangled name recovery', () => {
  2638. // Curated pre-parse blanking can't list every library's inline macro, so a
  2639. // post-parse salvage recovers the real function name from ANY leftover
  2640. // `MACRO Ret name(…)` mangle — no list needed. It only ever touches an
  2641. // already-mangled name, so it can't corrupt a clean one.
  2642. const namesOf = (code: string, file = 's.cpp') =>
  2643. extractFromSource(file, code).nodes
  2644. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2645. .map((n) => n.name);
  2646. it('recovers the name from a completely unknown macro (no list entry)', () => {
  2647. expect(namesOf('WEBKIT_EXPORT WTFString computeThing(int x) { return H(x); }')).toContain('computeThing');
  2648. expect(namesOf('SOMELIB_INLINE MyResult doWork(int x) { return H(x); }')).toContain('doWork');
  2649. expect(namesOf('MZ_FORCEINLINE char_t* to_str(double v) { return H(v); }')).toContain('to_str');
  2650. });
  2651. it('recoverMangledCppName only touches already-mangled names, with guards', () => {
  2652. // Recovered:
  2653. expect(recoverMangledCppName('WTFString computeThing')).toBe('computeThing');
  2654. expect(recoverMangledCppName('char_t* to_str(double v)')).toBe('to_str');
  2655. expect(recoverMangledCppName('unspecified_bool_type() const')).toBe('unspecified_bool_type');
  2656. // Left unchanged — clean names, operators, destructors, the `Ret (name)`
  2657. // idiom, and non-identifier tails:
  2658. expect(recoverMangledCppName('computeThing')).toBe('computeThing');
  2659. expect(recoverMangledCppName('operator EALSMovementState')).toBe('operator EALSMovementState');
  2660. expect(recoverMangledCppName('~Widget')).toBe('~Widget');
  2661. expect(recoverMangledCppName('bool (likely)')).toBe('bool (likely)');
  2662. expect(recoverMangledCppName('void (free)')).toBe('void (free)');
  2663. expect(recoverMangledCppName('QDockWidget *')).toBe('QDockWidget *');
  2664. });
  2665. it('does not disturb clean C++ names or non-C++ (Kotlin backtick) names', () => {
  2666. expect(namesOf('int foo(int x) { return x; }')).toEqual(['foo']);
  2667. // Kotlin backtick identifiers legitimately contain spaces; the salvage is
  2668. // C/C++-only, so they are untouched.
  2669. const kt = extractFromSource('T.kt', 'class T {\n fun `decode simple cert`() { }\n}').nodes
  2670. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2671. .map((n) => n.name);
  2672. expect(kt).toContain('`decode simple cert`');
  2673. });
  2674. it('curated list now also covers Qt / Folly / Abseil / LLVM / V8 / Eigen / rapidjson (full recovery)', () => {
  2675. const info = (c: string) =>
  2676. extractFromSource('x.cpp', c).nodes
  2677. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2678. .map((n) => ({ name: n.name, ret: n.returnType }));
  2679. expect(info('FOLLY_ALWAYS_INLINE Str f(int x) { return H(x); }')).toEqual([{ name: 'f', ret: 'Str' }]);
  2680. expect(namesOf('Q_INVOKABLE void onClicked() { H(); }')).toContain('onClicked');
  2681. expect(namesOf('ABSL_ATTRIBUTE_ALWAYS_INLINE int hash(int x) { return H(x); }')).toContain('hash');
  2682. expect(namesOf('EIGEN_STRONG_INLINE Scalar dot(const V& v) { return H(v); }')).toContain('dot');
  2683. expect(namesOf('V8_INLINE MaybeLocal Get(int i) { return H(i); }')).toContain('Get');
  2684. expect(namesOf('RAPIDJSON_FORCEINLINE bool Parse(const char* s) { return H(s); }')).toContain('Parse');
  2685. });
  2686. it('curated list spans the broader ecosystem (Mozilla, GLM, Bullet, OpenCV, Skia, EASTL, protobuf, fmt, Windows conventions)', () => {
  2687. const info = (c: string) =>
  2688. extractFromSource('x.cpp', c).nodes
  2689. .filter((n) => n.kind === 'method' || n.kind === 'function')
  2690. .map((n) => ({ name: n.name, ret: n.returnType }));
  2691. expect(info('MOZ_ALWAYS_INLINE Value get(int i) { return H(i); }')).toEqual([{ name: 'get', ret: 'Value' }]);
  2692. expect(info('GLM_FUNC_QUALIFIER vec3 cross(const vec3& a) { return H(a); }')).toEqual([{ name: 'cross', ret: 'vec3' }]);
  2693. expect(info('SIMD_FORCE_INLINE btScalar dot(const btVector3& v) const { return H(v); }')).toEqual([{ name: 'dot', ret: 'btScalar' }]);
  2694. expect(info('CV_INLINE Mat clone() const { return H(); }')).toEqual([{ name: 'clone', ret: 'Mat' }]);
  2695. expect(namesOf('PROTOBUF_ALWAYS_INLINE int size() const { return H(); }')).toContain('size');
  2696. expect(namesOf('FMT_CONSTEXPR auto parse(int x) { return H(x); }')).toContain('parse');
  2697. expect(namesOf('SK_ALWAYS_INLINE SkScalar width() const { return H(); }')).toContain('width');
  2698. expect(namesOf('EA_FORCE_INLINE size_type size() const { return H(); }')).toContain('size');
  2699. // Windows calling-convention macros sit between return type and name; the
  2700. // macro is blanked so the real return type survives.
  2701. expect(info('HRESULT WINAPI CreateThing(int x) { return H(x); }')).toEqual([{ name: 'CreateThing', ret: 'HRESULT' }]);
  2702. expect(info('ULONG STDMETHODCALLTYPE AddRef() { return H(); }')).toEqual([{ name: 'AddRef', ret: 'ULONG' }]);
  2703. });
  2704. });
  2705. describe('C++ templated base-class inheritance (#1043)', () => {
  2706. // Inheriting from a template (`class D : public Base<int>`) recorded the base
  2707. // ref as the full instantiation `Base<int>`, which never name-matched the
  2708. // template indexed as the bare node `Base`. The `<…>` args are stripped so the
  2709. // `extends` reference matches.
  2710. it('strips template args from a templated base so the extends ref is the bare name', () => {
  2711. const code = `
  2712. template<typename T> class Base {};
  2713. template<typename D> class CRTPBase {};
  2714. namespace ns { template<typename T> class Tpl {}; }
  2715. class Plain {};
  2716. class Widget : public Base<int> {};
  2717. class App : public CRTPBase<App> {};
  2718. class Q : public ns::Tpl<int> {};
  2719. class Both : public Base<char>, public Plain {};
  2720. `;
  2721. const extendsRefs = extractFromSource('f.cpp', code).unresolvedReferences.filter(
  2722. (r) => r.referenceKind === 'extends'
  2723. );
  2724. const names = extendsRefs.map((r) => r.referenceName);
  2725. // Templated bases carry the bare name, NOT the `<…>` instantiation.
  2726. expect(names).toContain('Base'); // from Base<int> / Base<char>
  2727. expect(names).toContain('CRTPBase'); // from CRTPBase<App> (CRTP)
  2728. expect(names).toContain('ns::Tpl'); // qualified head preserved, args dropped
  2729. expect(names).toContain('Plain'); // non-templated base unchanged
  2730. // No reference still carries angle brackets.
  2731. expect(names.find((n) => n.includes('<'))).toBeUndefined();
  2732. });
  2733. it('stripCppTemplateArgs removes balanced <…> at any depth and is a no-op without them', () => {
  2734. expect(stripCppTemplateArgs('Base<int>')).toBe('Base');
  2735. expect(stripCppTemplateArgs('ns::Tpl<int>')).toBe('ns::Tpl');
  2736. expect(stripCppTemplateArgs('ns::Tpl<Foo<int>>')).toBe('ns::Tpl'); // nested
  2737. expect(stripCppTemplateArgs('Outer<int>::Inner')).toBe('Outer::Inner'); // mid-name
  2738. expect(stripCppTemplateArgs('Base')).toBe('Base'); // no-op
  2739. expect(stripCppTemplateArgs('ns::Plain')).toBe('ns::Plain'); // no-op qualified
  2740. });
  2741. });
  2742. describe('C++ stack-allocation construction (#1035)', () => {
  2743. // `Calculator calc(0)` (direct-init) and `Widget w{1, 2}` (brace-init) carry
  2744. // the constructor args directly on the declarator — no call/new node — so
  2745. // they emitted no constructor reference, unlike heap `new Calculator(0)`. An
  2746. // `instantiates` ref to the constructed type is now emitted for both.
  2747. const instNames = (code: string) =>
  2748. extractFromSource('f.cpp', `void run() {\n${code}\n}`)
  2749. .unresolvedReferences.filter((r) => r.referenceKind === 'instantiates')
  2750. .map((r) => r.referenceName);
  2751. it('emits an instantiates ref for direct-init and brace-init', () => {
  2752. expect(instNames('Calculator calc(0);')).toEqual(['Calculator']);
  2753. expect(instNames('Widget w{1, 2};')).toEqual(['Widget']);
  2754. });
  2755. it('strips template args and namespace to the bare class name', () => {
  2756. // `std::vector<int> v(10)` → `vector`; `ns::Widget w(0)` → `Widget`.
  2757. expect(instNames('std::vector<int> v(10);')).toEqual(['vector']);
  2758. expect(instNames('ns::Widget w(0);')).toEqual(['Widget']);
  2759. });
  2760. it('does not emit for primitives, default construction, or the most-vexing parse', () => {
  2761. expect(instNames('int x(5);')).toEqual([]); // primitive direct-init
  2762. expect(instNames('int y{6};')).toEqual([]); // primitive brace-init
  2763. expect(instNames('auto z = make();')).toEqual([]); // auto + call (handled elsewhere)
  2764. expect(instNames('Calculator deferred;')).toEqual([]); // default construction, no args
  2765. expect(instNames('Calculator calc();')).toEqual([]); // function declaration (most-vexing parse)
  2766. });
  2767. it('emits a single instantiates ref for a multi-declarator statement', () => {
  2768. // `Calculator a(1), b(2);` shares one `type` field; both construct a
  2769. // Calculator, so one ref suffices (it dedups to one edge regardless).
  2770. expect(instNames('Calculator a(1), b(2);')).toEqual(['Calculator']);
  2771. });
  2772. });
  2773. describe('C/C++ imports', () => {
  2774. it('should extract system include', () => {
  2775. const code = `#include <iostream>`;
  2776. const result = extractFromSource('main.cpp', code);
  2777. const importNode = result.nodes.find((n) => n.kind === 'import');
  2778. expect(importNode).toBeDefined();
  2779. expect(importNode?.name).toBe('iostream');
  2780. expect(importNode?.signature).toBe('#include <iostream>');
  2781. });
  2782. it('should extract system include with path', () => {
  2783. const code = `#include <nlohmann/json.hpp>`;
  2784. const result = extractFromSource('app.cpp', code);
  2785. const importNode = result.nodes.find((n) => n.kind === 'import');
  2786. expect(importNode).toBeDefined();
  2787. expect(importNode?.name).toBe('nlohmann/json.hpp');
  2788. });
  2789. it('should extract local include', () => {
  2790. const code = `#include "myheader.h"`;
  2791. const result = extractFromSource('main.cpp', code);
  2792. const importNode = result.nodes.find((n) => n.kind === 'import');
  2793. expect(importNode).toBeDefined();
  2794. expect(importNode?.name).toBe('myheader.h');
  2795. });
  2796. it('should extract C header', () => {
  2797. const code = `#include <stdio.h>`;
  2798. const result = extractFromSource('main.c', code);
  2799. const importNode = result.nodes.find((n) => n.kind === 'import');
  2800. expect(importNode).toBeDefined();
  2801. expect(importNode?.name).toBe('stdio.h');
  2802. });
  2803. it('should extract multiple includes', () => {
  2804. const code = `
  2805. #include <iostream>
  2806. #include <vector>
  2807. #include "config.h"
  2808. `;
  2809. const result = extractFromSource('app.cpp', code);
  2810. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2811. expect(importNodes.length).toBe(3);
  2812. const names = importNodes.map((n) => n.name);
  2813. expect(names).toContain('iostream');
  2814. expect(names).toContain('vector');
  2815. expect(names).toContain('config.h');
  2816. });
  2817. it('should create unresolved references for local includes', () => {
  2818. const code = `#include "myheader.h"`;
  2819. const result = extractFromSource('main.cpp', code);
  2820. const importRef = result.unresolvedReferences.find(
  2821. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  2822. );
  2823. expect(importRef).toBeDefined();
  2824. expect(importRef?.line).toBe(1);
  2825. });
  2826. it('should create unresolved references for system includes', () => {
  2827. const code = `#include <iostream>`;
  2828. const result = extractFromSource('main.cpp', code);
  2829. const importRef = result.unresolvedReferences.find(
  2830. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  2831. );
  2832. expect(importRef).toBeDefined();
  2833. });
  2834. });
  2835. describe('Dart imports', () => {
  2836. it('should extract dart: import', () => {
  2837. const code = `import 'dart:async';`;
  2838. const result = extractFromSource('main.dart', code);
  2839. const importNode = result.nodes.find((n) => n.kind === 'import');
  2840. expect(importNode).toBeDefined();
  2841. expect(importNode?.name).toBe('dart:async');
  2842. expect(importNode?.signature).toBe("import 'dart:async';");
  2843. });
  2844. it('should extract package import', () => {
  2845. const code = `import 'package:flutter/material.dart';`;
  2846. const result = extractFromSource('app.dart', code);
  2847. const importNode = result.nodes.find((n) => n.kind === 'import');
  2848. expect(importNode).toBeDefined();
  2849. expect(importNode?.name).toBe('package:flutter/material.dart');
  2850. });
  2851. it('should extract aliased import', () => {
  2852. const code = `import 'package:http/http.dart' as http;`;
  2853. const result = extractFromSource('api.dart', code);
  2854. const importNode = result.nodes.find((n) => n.kind === 'import');
  2855. expect(importNode).toBeDefined();
  2856. expect(importNode?.name).toBe('package:http/http.dart');
  2857. expect(importNode?.signature).toContain('as http');
  2858. });
  2859. it('should extract multiple imports', () => {
  2860. const code = `
  2861. import 'dart:async';
  2862. import 'dart:convert';
  2863. import 'package:flutter/material.dart';
  2864. `;
  2865. const result = extractFromSource('main.dart', code);
  2866. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2867. expect(importNodes.length).toBe(3);
  2868. const names = importNodes.map((n) => n.name);
  2869. expect(names).toContain('dart:async');
  2870. expect(names).toContain('dart:convert');
  2871. expect(names).toContain('package:flutter/material.dart');
  2872. });
  2873. it('should extract relative import', () => {
  2874. const code = `import '../utils/helpers.dart';`;
  2875. const result = extractFromSource('lib/main.dart', code);
  2876. const importNode = result.nodes.find((n) => n.kind === 'import');
  2877. expect(importNode).toBeDefined();
  2878. expect(importNode?.name).toBe('../utils/helpers.dart');
  2879. });
  2880. });
  2881. describe('Liquid imports', () => {
  2882. it('should extract render tag', () => {
  2883. const code = `{% render 'loading-spinner' %}`;
  2884. const result = extractFromSource('template.liquid', code);
  2885. const importNode = result.nodes.find((n) => n.kind === 'import');
  2886. expect(importNode).toBeDefined();
  2887. expect(importNode?.name).toBe('loading-spinner');
  2888. expect(importNode?.signature).toContain('render');
  2889. });
  2890. it('should extract section tag', () => {
  2891. const code = `{% section 'header' %}`;
  2892. const result = extractFromSource('layout/theme.liquid', code);
  2893. const importNode = result.nodes.find((n) => n.kind === 'import');
  2894. expect(importNode).toBeDefined();
  2895. expect(importNode?.name).toBe('header');
  2896. expect(importNode?.signature).toContain('section');
  2897. });
  2898. it('should extract include tag', () => {
  2899. const code = `{% include 'icon-cart' %}`;
  2900. const result = extractFromSource('snippets/header.liquid', code);
  2901. const importNode = result.nodes.find((n) => n.kind === 'import');
  2902. expect(importNode).toBeDefined();
  2903. expect(importNode?.name).toBe('icon-cart');
  2904. expect(importNode?.signature).toContain('include');
  2905. });
  2906. it('should extract render with whitespace control', () => {
  2907. const code = `{%- render 'price' -%}`;
  2908. const result = extractFromSource('snippets/product.liquid', code);
  2909. const importNode = result.nodes.find((n) => n.kind === 'import');
  2910. expect(importNode).toBeDefined();
  2911. expect(importNode?.name).toBe('price');
  2912. });
  2913. it('should extract multiple imports', () => {
  2914. const code = `
  2915. {% section 'header' %}
  2916. {% render 'loading-spinner' %}
  2917. {% render 'cart-drawer' %}
  2918. `;
  2919. const result = extractFromSource('layout/theme.liquid', code);
  2920. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  2921. expect(importNodes.length).toBe(3);
  2922. const names = importNodes.map((n) => n.name);
  2923. expect(names).toContain('header');
  2924. expect(names).toContain('loading-spinner');
  2925. expect(names).toContain('cart-drawer');
  2926. });
  2927. });
  2928. });
  2929. // =============================================================================
  2930. // Pascal / Delphi Extraction
  2931. // =============================================================================
  2932. describe('Pascal / Delphi Extraction', () => {
  2933. describe('Language detection', () => {
  2934. it('should detect Pascal files', () => {
  2935. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2936. expect(detectLanguage('App.dpr')).toBe('pascal');
  2937. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2938. expect(detectLanguage('App.lpr')).toBe('pascal');
  2939. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2940. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2941. });
  2942. it('should report Pascal as supported', () => {
  2943. expect(isLanguageSupported('pascal')).toBe(true);
  2944. expect(getSupportedLanguages()).toContain('pascal');
  2945. });
  2946. });
  2947. describe('Unit extraction', () => {
  2948. it('should extract unit as module', () => {
  2949. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2950. const result = extractFromSource('MyUnit.pas', code);
  2951. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2952. expect(moduleNode).toBeDefined();
  2953. expect(moduleNode?.name).toBe('MyUnit');
  2954. expect(moduleNode?.language).toBe('pascal');
  2955. });
  2956. it('should extract program as module', () => {
  2957. const code = `program MyApp;\nbegin\nend.`;
  2958. const result = extractFromSource('MyApp.dpr', code);
  2959. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2960. expect(moduleNode).toBeDefined();
  2961. expect(moduleNode?.name).toBe('MyApp');
  2962. });
  2963. it('should fallback to filename when module name is empty', () => {
  2964. // Some .dpr templates use "program;" without a name
  2965. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2966. const result = extractFromSource('Console.dpr', code);
  2967. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2968. expect(moduleNode).toBeDefined();
  2969. expect(moduleNode?.name).toBe('Console');
  2970. });
  2971. });
  2972. describe('Uses clause (imports)', () => {
  2973. it('should extract uses as individual imports', () => {
  2974. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2975. const result = extractFromSource('Test.pas', code);
  2976. const imports = result.nodes.filter((n) => n.kind === 'import');
  2977. expect(imports.length).toBe(2);
  2978. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2979. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2980. });
  2981. it('should create unresolved references for imports', () => {
  2982. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2983. const result = extractFromSource('Test.pas', code);
  2984. const importRef = result.unresolvedReferences.find(
  2985. (r) => r.referenceKind === 'imports'
  2986. );
  2987. expect(importRef).toBeDefined();
  2988. expect(importRef?.referenceName).toBe('UAuth');
  2989. });
  2990. });
  2991. describe('Class extraction', () => {
  2992. it('should extract class declarations', () => {
  2993. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2994. const result = extractFromSource('Test.pas', code);
  2995. const classNode = result.nodes.find((n) => n.kind === 'class');
  2996. expect(classNode).toBeDefined();
  2997. expect(classNode?.name).toBe('TMyClass');
  2998. });
  2999. it('should extract class with inheritance', () => {
  3000. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  3001. const result = extractFromSource('Test.pas', code);
  3002. const extendsRef = result.unresolvedReferences.find(
  3003. (r) => r.referenceKind === 'extends'
  3004. );
  3005. expect(extendsRef).toBeDefined();
  3006. expect(extendsRef?.referenceName).toBe('TParent');
  3007. });
  3008. it('should extract class with interface implementation', () => {
  3009. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  3010. const result = extractFromSource('Test.pas', code);
  3011. const extendsRef = result.unresolvedReferences.find(
  3012. (r) => r.referenceKind === 'extends'
  3013. );
  3014. const implementsRef = result.unresolvedReferences.find(
  3015. (r) => r.referenceKind === 'implements'
  3016. );
  3017. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  3018. expect(implementsRef?.referenceName).toBe('ILogger');
  3019. });
  3020. });
  3021. describe('Record extraction', () => {
  3022. it('should extract records as class nodes', () => {
  3023. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  3024. const result = extractFromSource('Test.pas', code);
  3025. const classNode = result.nodes.find((n) => n.kind === 'class');
  3026. expect(classNode).toBeDefined();
  3027. expect(classNode?.name).toBe('TPoint');
  3028. const fields = result.nodes.filter((n) => n.kind === 'field');
  3029. expect(fields.length).toBe(2);
  3030. expect(fields.map((f) => f.name)).toContain('X');
  3031. expect(fields.map((f) => f.name)).toContain('Y');
  3032. });
  3033. });
  3034. describe('Interface extraction', () => {
  3035. it('should extract interface declarations', () => {
  3036. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  3037. const result = extractFromSource('Test.pas', code);
  3038. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  3039. expect(ifaceNode).toBeDefined();
  3040. expect(ifaceNode?.name).toBe('ILogger');
  3041. });
  3042. });
  3043. describe('Method extraction', () => {
  3044. it('should extract methods with visibility', () => {
  3045. 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.`;
  3046. const result = extractFromSource('Test.pas', code);
  3047. const methods = result.nodes.filter((n) => n.kind === 'method');
  3048. expect(methods.length).toBe(2);
  3049. const createMethod = methods.find((m) => m.name === 'Create');
  3050. expect(createMethod?.visibility).toBe('public');
  3051. const getValue = methods.find((m) => m.name === 'GetValue');
  3052. expect(getValue?.visibility).toBe('public');
  3053. const fields = result.nodes.filter((n) => n.kind === 'field');
  3054. const fValue = fields.find((f) => f.name === 'FValue');
  3055. expect(fValue?.visibility).toBe('private');
  3056. });
  3057. it('should detect static methods (class methods)', () => {
  3058. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  3059. const result = extractFromSource('Test.pas', code);
  3060. const methods = result.nodes.filter((n) => n.kind === 'method');
  3061. const staticMethod = methods.find((m) => m.name === 'Create');
  3062. expect(staticMethod?.isStatic).toBe(true);
  3063. });
  3064. });
  3065. describe('Enum extraction', () => {
  3066. it('should extract enums with members', () => {
  3067. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  3068. const result = extractFromSource('Test.pas', code);
  3069. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  3070. expect(enumNode).toBeDefined();
  3071. expect(enumNode?.name).toBe('TColor');
  3072. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  3073. expect(members.length).toBe(3);
  3074. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  3075. });
  3076. });
  3077. describe('Property extraction', () => {
  3078. it('should extract properties', () => {
  3079. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  3080. const result = extractFromSource('Test.pas', code);
  3081. const propNode = result.nodes.find((n) => n.kind === 'property');
  3082. expect(propNode).toBeDefined();
  3083. expect(propNode?.name).toBe('Name');
  3084. expect(propNode?.visibility).toBe('public');
  3085. });
  3086. });
  3087. describe('Constant extraction', () => {
  3088. it('should extract constants', () => {
  3089. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  3090. const result = extractFromSource('Test.pas', code);
  3091. const constants = result.nodes.filter((n) => n.kind === 'constant');
  3092. expect(constants.length).toBe(2);
  3093. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  3094. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  3095. });
  3096. });
  3097. describe('Type alias extraction', () => {
  3098. it('should extract type aliases', () => {
  3099. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  3100. const result = extractFromSource('Test.pas', code);
  3101. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  3102. expect(aliasNode).toBeDefined();
  3103. expect(aliasNode?.name).toBe('TUserName');
  3104. });
  3105. });
  3106. describe('Call extraction', () => {
  3107. it('should extract calls from implementation bodies', () => {
  3108. 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.`;
  3109. const result = extractFromSource('Test.pas', code);
  3110. const callRef = result.unresolvedReferences.find(
  3111. (r) => r.referenceKind === 'calls'
  3112. );
  3113. expect(callRef).toBeDefined();
  3114. expect(callRef?.referenceName).toBe('WriteLn');
  3115. });
  3116. });
  3117. describe('Containment edges', () => {
  3118. it('should create contains edges for class members', () => {
  3119. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  3120. const result = extractFromSource('Test.pas', code);
  3121. const classNode = result.nodes.find((n) => n.kind === 'class');
  3122. const methodNode = result.nodes.find((n) => n.kind === 'method');
  3123. expect(classNode).toBeDefined();
  3124. expect(methodNode).toBeDefined();
  3125. const containsEdge = result.edges.find(
  3126. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  3127. );
  3128. expect(containsEdge).toBeDefined();
  3129. });
  3130. });
  3131. describe('Full fixture: UAuth.pas', () => {
  3132. const code = `unit UAuth;
  3133. interface
  3134. uses
  3135. System.SysUtils,
  3136. System.Classes;
  3137. type
  3138. ITokenValidator = interface
  3139. ['{11111111-1111-1111-1111-111111111111}']
  3140. function Validate(const AToken: string): Boolean;
  3141. end;
  3142. TAuthService = class(TInterfacedObject, ITokenValidator)
  3143. private
  3144. FToken: string;
  3145. FLoginCount: Integer;
  3146. procedure IncLoginCount;
  3147. protected
  3148. function GetToken: string;
  3149. public
  3150. constructor Create;
  3151. destructor Destroy; override;
  3152. function Validate(const AToken: string): Boolean;
  3153. function Login(const AUser, APass: string): string;
  3154. property Token: string read GetToken;
  3155. property LoginCount: Integer read FLoginCount;
  3156. end;
  3157. implementation
  3158. constructor TAuthService.Create;
  3159. begin
  3160. inherited Create;
  3161. FToken := '';
  3162. FLoginCount := 0;
  3163. end;
  3164. destructor TAuthService.Destroy;
  3165. begin
  3166. FToken := '';
  3167. inherited Destroy;
  3168. end;
  3169. procedure TAuthService.IncLoginCount;
  3170. begin
  3171. Inc(FLoginCount);
  3172. end;
  3173. function TAuthService.GetToken: string;
  3174. begin
  3175. Result := FToken;
  3176. end;
  3177. function TAuthService.Validate(const AToken: string): Boolean;
  3178. begin
  3179. Result := AToken <> '';
  3180. end;
  3181. function TAuthService.Login(const AUser, APass: string): string;
  3182. begin
  3183. IncLoginCount;
  3184. if Validate(AUser + ':' + APass) then
  3185. begin
  3186. FToken := AUser;
  3187. Result := 'ok';
  3188. end
  3189. else
  3190. Result := '';
  3191. end;
  3192. end.`;
  3193. it('should extract all expected nodes', () => {
  3194. const result = extractFromSource('UAuth.pas', code);
  3195. expect(result.errors).toHaveLength(0);
  3196. // Module
  3197. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  3198. expect(moduleNode?.name).toBe('UAuth');
  3199. // Imports
  3200. const imports = result.nodes.filter((n) => n.kind === 'import');
  3201. expect(imports.length).toBe(2);
  3202. // Interface
  3203. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  3204. expect(ifaceNode?.name).toBe('ITokenValidator');
  3205. // Class
  3206. const classNode = result.nodes.find((n) => n.kind === 'class');
  3207. expect(classNode?.name).toBe('TAuthService');
  3208. // Methods
  3209. const methods = result.nodes.filter((n) => n.kind === 'method');
  3210. expect(methods.length).toBeGreaterThanOrEqual(6);
  3211. expect(methods.map((m) => m.name)).toContain('Create');
  3212. expect(methods.map((m) => m.name)).toContain('Destroy');
  3213. expect(methods.map((m) => m.name)).toContain('Login');
  3214. // Fields
  3215. const fields = result.nodes.filter((n) => n.kind === 'field');
  3216. expect(fields.length).toBe(2);
  3217. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  3218. // Properties
  3219. const props = result.nodes.filter((n) => n.kind === 'property');
  3220. expect(props.length).toBe(2);
  3221. expect(props.map((p) => p.name)).toContain('Token');
  3222. expect(props.map((p) => p.name)).toContain('LoginCount');
  3223. });
  3224. it('should extract inheritance and interface implementation', () => {
  3225. const result = extractFromSource('UAuth.pas', code);
  3226. const extendsRef = result.unresolvedReferences.find(
  3227. (r) => r.referenceKind === 'extends'
  3228. );
  3229. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  3230. const implementsRef = result.unresolvedReferences.find(
  3231. (r) => r.referenceKind === 'implements'
  3232. );
  3233. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  3234. });
  3235. it('should extract calls from implementation', () => {
  3236. const result = extractFromSource('UAuth.pas', code);
  3237. const callRefs = result.unresolvedReferences.filter(
  3238. (r) => r.referenceKind === 'calls'
  3239. );
  3240. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  3241. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  3242. });
  3243. });
  3244. describe('Full fixture: UTypes.pas', () => {
  3245. const code = `unit UTypes;
  3246. interface
  3247. uses
  3248. System.SysUtils;
  3249. const
  3250. C_MAX_RETRIES = 3;
  3251. C_DEFAULT_NAME = 'Guest';
  3252. type
  3253. TUserRole = (urAdmin, urEditor, urViewer);
  3254. TPoint2D = record
  3255. X: Double;
  3256. Y: Double;
  3257. end;
  3258. TUserName = string;
  3259. TUserInfo = class
  3260. public
  3261. type
  3262. TAddress = record
  3263. Street: string;
  3264. City: string;
  3265. Zip: string;
  3266. end;
  3267. private
  3268. FName: TUserName;
  3269. FRole: TUserRole;
  3270. FAddress: TAddress;
  3271. public
  3272. constructor Create(const AName: TUserName; ARole: TUserRole);
  3273. function GetDisplayName: string;
  3274. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  3275. property Name: TUserName read FName write FName;
  3276. property Role: TUserRole read FRole;
  3277. property Address: TAddress read FAddress write FAddress;
  3278. end;
  3279. implementation
  3280. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  3281. begin
  3282. FName := AName;
  3283. FRole := ARole;
  3284. end;
  3285. function TUserInfo.GetDisplayName: string;
  3286. begin
  3287. if FRole = urAdmin then
  3288. Result := '[Admin] ' + FName
  3289. else
  3290. Result := FName;
  3291. end;
  3292. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  3293. begin
  3294. Result := TUserInfo.Create(AName, urAdmin);
  3295. end;
  3296. end.`;
  3297. it('should extract enums with members', () => {
  3298. const result = extractFromSource('UTypes.pas', code);
  3299. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  3300. expect(enumNode?.name).toBe('TUserRole');
  3301. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  3302. expect(members.length).toBe(3);
  3303. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  3304. });
  3305. it('should extract constants', () => {
  3306. const result = extractFromSource('UTypes.pas', code);
  3307. const constants = result.nodes.filter((n) => n.kind === 'constant');
  3308. expect(constants.length).toBe(2);
  3309. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  3310. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  3311. });
  3312. it('should extract type aliases', () => {
  3313. const result = extractFromSource('UTypes.pas', code);
  3314. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3315. expect(aliases.map((a) => a.name)).toContain('TUserName');
  3316. });
  3317. it('should extract records as classes with fields', () => {
  3318. const result = extractFromSource('UTypes.pas', code);
  3319. const classes = result.nodes.filter((n) => n.kind === 'class');
  3320. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  3321. // TPoint2D fields
  3322. const fields = result.nodes.filter((n) => n.kind === 'field');
  3323. expect(fields.map((f) => f.name)).toContain('X');
  3324. expect(fields.map((f) => f.name)).toContain('Y');
  3325. });
  3326. it('should extract static class methods', () => {
  3327. const result = extractFromSource('UTypes.pas', code);
  3328. const methods = result.nodes.filter((n) => n.kind === 'method');
  3329. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  3330. expect(staticMethod).toBeDefined();
  3331. expect(staticMethod?.isStatic).toBe(true);
  3332. });
  3333. it('should extract nested types', () => {
  3334. const result = extractFromSource('UTypes.pas', code);
  3335. const classes = result.nodes.filter((n) => n.kind === 'class');
  3336. expect(classes.map((c) => c.name)).toContain('TAddress');
  3337. });
  3338. });
  3339. });
  3340. // =============================================================================
  3341. // DFM/FMX Extraction
  3342. // =============================================================================
  3343. describe('DFM/FMX Extraction', () => {
  3344. it('should extract components from DFM', () => {
  3345. const code = `object Form1: TForm1
  3346. Left = 0
  3347. Top = 0
  3348. Caption = 'My Form'
  3349. object Button1: TButton
  3350. Left = 10
  3351. Top = 10
  3352. Caption = 'Click Me'
  3353. end
  3354. end`;
  3355. const result = extractFromSource('Form1.dfm', code);
  3356. const components = result.nodes.filter((n) => n.kind === 'component');
  3357. expect(components.length).toBe(2);
  3358. expect(components.map((c) => c.name)).toContain('Form1');
  3359. expect(components.map((c) => c.name)).toContain('Button1');
  3360. const button = components.find((c) => c.name === 'Button1');
  3361. expect(button?.signature).toBe('TButton');
  3362. });
  3363. it('should extract nested component hierarchy', () => {
  3364. const code = `object Form1: TForm1
  3365. object Panel1: TPanel
  3366. object Label1: TLabel
  3367. Caption = 'Hello'
  3368. end
  3369. end
  3370. end`;
  3371. const result = extractFromSource('Form1.dfm', code);
  3372. const components = result.nodes.filter((n) => n.kind === 'component');
  3373. expect(components.length).toBe(3);
  3374. // Check nesting: Panel1 contains Label1
  3375. const panel = components.find((c) => c.name === 'Panel1');
  3376. const label = components.find((c) => c.name === 'Label1');
  3377. const containsEdge = result.edges.find(
  3378. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  3379. );
  3380. expect(containsEdge).toBeDefined();
  3381. });
  3382. it('should extract event handler references', () => {
  3383. const code = `object Form1: TForm1
  3384. OnCreate = FormCreate
  3385. OnDestroy = FormDestroy
  3386. object Button1: TButton
  3387. OnClick = Button1Click
  3388. end
  3389. end`;
  3390. const result = extractFromSource('Form1.dfm', code);
  3391. const refs = result.unresolvedReferences;
  3392. expect(refs.length).toBe(3);
  3393. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  3394. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  3395. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  3396. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  3397. });
  3398. it('should handle multi-line properties', () => {
  3399. const code = `object Form1: TForm1
  3400. SQL.Strings = (
  3401. 'SELECT * FROM users'
  3402. 'WHERE active = 1')
  3403. object Button1: TButton
  3404. OnClick = Button1Click
  3405. end
  3406. end`;
  3407. const result = extractFromSource('Form1.dfm', code);
  3408. const components = result.nodes.filter((n) => n.kind === 'component');
  3409. expect(components.length).toBe(2);
  3410. const refs = result.unresolvedReferences;
  3411. expect(refs.length).toBe(1);
  3412. expect(refs[0]?.referenceName).toBe('Button1Click');
  3413. });
  3414. it('should handle inherited keyword', () => {
  3415. const code = `inherited Form1: TForm1
  3416. Caption = 'Inherited Form'
  3417. object Button1: TButton
  3418. OnClick = Button1Click
  3419. end
  3420. end`;
  3421. const result = extractFromSource('Form1.dfm', code);
  3422. const components = result.nodes.filter((n) => n.kind === 'component');
  3423. expect(components.length).toBe(2);
  3424. expect(components.map((c) => c.name)).toContain('Form1');
  3425. });
  3426. it('should handle item collection properties', () => {
  3427. const code = `object Form1: TForm1
  3428. object StatusBar1: TStatusBar
  3429. Panels = <
  3430. item
  3431. Width = 200
  3432. end
  3433. item
  3434. Width = 200
  3435. end>
  3436. end
  3437. end`;
  3438. const result = extractFromSource('Form1.dfm', code);
  3439. const components = result.nodes.filter((n) => n.kind === 'component');
  3440. expect(components.length).toBe(2);
  3441. });
  3442. describe('Full fixture: MainForm.dfm', () => {
  3443. const code = `object frmMain: TfrmMain
  3444. Left = 0
  3445. Top = 0
  3446. Caption = 'CodeGraph DFM Fixture'
  3447. ClientHeight = 480
  3448. ClientWidth = 640
  3449. OnCreate = FormCreate
  3450. OnDestroy = FormDestroy
  3451. object pnlTop: TPanel
  3452. Left = 0
  3453. Top = 0
  3454. Width = 640
  3455. Height = 50
  3456. object lblTitle: TLabel
  3457. Left = 16
  3458. Top = 16
  3459. Caption = 'Authentication Service'
  3460. end
  3461. object btnLogin: TButton
  3462. Left = 540
  3463. Top = 12
  3464. OnClick = btnLoginClick
  3465. end
  3466. end
  3467. object pnlContent: TPanel
  3468. Left = 0
  3469. Top = 50
  3470. object edtUsername: TEdit
  3471. Left = 16
  3472. Top = 16
  3473. OnChange = edtUsernameChange
  3474. end
  3475. object edtPassword: TEdit
  3476. Left = 16
  3477. Top = 48
  3478. OnKeyPress = edtPasswordKeyPress
  3479. end
  3480. object mmoLog: TMemo
  3481. Left = 16
  3482. Top = 88
  3483. end
  3484. end
  3485. object pnlStatus: TStatusBar
  3486. Left = 0
  3487. Top = 440
  3488. Panels = <
  3489. item
  3490. Width = 200
  3491. end
  3492. item
  3493. Width = 200
  3494. end>
  3495. end
  3496. end`;
  3497. it('should extract all components', () => {
  3498. const result = extractFromSource('MainForm.dfm', code);
  3499. const components = result.nodes.filter((n) => n.kind === 'component');
  3500. expect(components.length).toBe(9);
  3501. expect(components.map((c) => c.name)).toEqual(
  3502. expect.arrayContaining([
  3503. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  3504. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  3505. ])
  3506. );
  3507. });
  3508. it('should extract all event handlers', () => {
  3509. const result = extractFromSource('MainForm.dfm', code);
  3510. const refs = result.unresolvedReferences;
  3511. expect(refs.length).toBe(5);
  3512. expect(refs.map((r) => r.referenceName)).toEqual(
  3513. expect.arrayContaining([
  3514. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  3515. 'edtUsernameChange', 'edtPasswordKeyPress',
  3516. ])
  3517. );
  3518. });
  3519. });
  3520. });
  3521. describe('Kotlin Multiplatform expect/actual', () => {
  3522. let tempDir: string;
  3523. let cg: CodeGraph;
  3524. beforeEach(() => {
  3525. tempDir = createTempDir();
  3526. });
  3527. afterEach(() => {
  3528. if (cg) cg.close();
  3529. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3530. });
  3531. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  3532. const common = path.join(tempDir, 'src', 'commonMain');
  3533. const jvm = path.join(tempDir, 'src', 'jvmMain');
  3534. fs.mkdirSync(common, { recursive: true });
  3535. fs.mkdirSync(jvm, { recursive: true });
  3536. // common source set: expect declarations + a caller that uses them
  3537. fs.writeFileSync(
  3538. path.join(common, 'SystemProps.kt'),
  3539. `package demo.internal
  3540. expect fun systemProp(name: String): String?
  3541. expect class Platform {
  3542. fun describe(): String
  3543. }
  3544. `
  3545. );
  3546. fs.writeFileSync(
  3547. path.join(common, 'Caller.kt'),
  3548. `package demo
  3549. import demo.internal.systemProp
  3550. import demo.internal.Platform
  3551. fun useIt(): String {
  3552. val v = systemProp("os.name")
  3553. return Platform().describe() + v
  3554. }
  3555. `
  3556. );
  3557. // jvm source set: actual implementations
  3558. fs.writeFileSync(
  3559. path.join(jvm, 'SystemProps.kt'),
  3560. `package demo.internal
  3561. actual fun systemProp(name: String): String? = System.getProperty(name)
  3562. actual class Platform {
  3563. actual fun describe(): String = "JVM"
  3564. }
  3565. `
  3566. );
  3567. cg = CodeGraph.initSync(tempDir);
  3568. await cg.indexAll();
  3569. cg.resolveReferences();
  3570. // The expect/actual markers are captured onto the node's decorators.
  3571. const fns = cg.getNodesByKind('function');
  3572. const actualFn = fns.find(
  3573. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  3574. );
  3575. const expectFn = fns.find(
  3576. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  3577. );
  3578. expect(actualFn).toBeDefined();
  3579. expect(expectFn).toBeDefined();
  3580. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  3581. // Editing the JVM actual must surface the common expect AND its caller —
  3582. // before the expect/actual bridge the actual had zero dependents.
  3583. const impact = cg.getImpactRadius(actualFn!.id, 3);
  3584. const impacted = [...impact.nodes.values()].map((n) => n.name);
  3585. expect(impacted).toContain('systemProp'); // the common expect
  3586. expect(impacted).toContain('useIt'); // the caller, reached transitively
  3587. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  3588. const bridge = impact.edges.find(
  3589. (e) =>
  3590. e.target === actualFn!.id &&
  3591. e.provenance === 'heuristic' &&
  3592. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  3593. 'kotlin-expect-actual'
  3594. );
  3595. expect(bridge).toBeDefined();
  3596. expect(bridge!.source).toBe(expectFn!.id);
  3597. });
  3598. it('links an expect class to an actual typealias (different node kinds)', async () => {
  3599. const common = path.join(tempDir, 'src', 'commonMain');
  3600. const jvm = path.join(tempDir, 'src', 'jvmMain');
  3601. fs.mkdirSync(common, { recursive: true });
  3602. fs.mkdirSync(jvm, { recursive: true });
  3603. fs.writeFileSync(
  3604. path.join(common, 'Lock.kt'),
  3605. `package demo
  3606. expect class Lock {
  3607. fun acquire()
  3608. }
  3609. `
  3610. );
  3611. fs.writeFileSync(
  3612. path.join(jvm, 'Lock.kt'),
  3613. `package demo
  3614. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  3615. `
  3616. );
  3617. cg = CodeGraph.initSync(tempDir);
  3618. await cg.indexAll();
  3619. cg.resolveReferences();
  3620. const aliasNode = cg
  3621. .getNodesByKind('type_alias')
  3622. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  3623. expect(aliasNode).toBeDefined();
  3624. // The actual typealias is now a cross-file dependency target (linked from
  3625. // the expect class), so it participates in impact rather than being orphaned.
  3626. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  3627. const bridge = impact.edges.find(
  3628. (e) =>
  3629. e.target === aliasNode!.id &&
  3630. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  3631. 'kotlin-expect-actual'
  3632. );
  3633. expect(bridge).toBeDefined();
  3634. });
  3635. });
  3636. describe('Scala cross-file dependencies', () => {
  3637. let tempDir: string;
  3638. let cg: CodeGraph;
  3639. beforeEach(() => {
  3640. tempDir = createTempDir();
  3641. });
  3642. afterEach(() => {
  3643. if (cg) cg.close();
  3644. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3645. });
  3646. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  3647. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  3648. fs.mkdirSync(src, { recursive: true });
  3649. fs.writeFileSync(
  3650. path.join(src, 'Semigroup.scala'),
  3651. `package demo
  3652. trait Semigroup[A] {
  3653. def combine(x: A, y: A): A
  3654. }
  3655. `
  3656. );
  3657. fs.writeFileSync(
  3658. path.join(src, 'Monoid.scala'),
  3659. `package demo
  3660. trait Monoid[A] extends Semigroup[A] {
  3661. def empty: A
  3662. }
  3663. `
  3664. );
  3665. fs.writeFileSync(
  3666. path.join(src, 'Instances.scala'),
  3667. `package demo
  3668. object Instances {
  3669. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  3670. def empty: Int = 0
  3671. def combine(x: Int, y: Int): Int = x + y
  3672. }
  3673. }
  3674. `
  3675. );
  3676. fs.writeFileSync(
  3677. path.join(src, 'Folding.scala'),
  3678. `package demo
  3679. object Folding {
  3680. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  3681. xs.foldLeft(M.empty)(M.combine)
  3682. }
  3683. `
  3684. );
  3685. cg = CodeGraph.initSync(tempDir);
  3686. await cg.indexAll();
  3687. cg.resolveReferences();
  3688. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  3689. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  3690. expect(monoid).toBeDefined();
  3691. expect(semigroup).toBeDefined();
  3692. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  3693. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  3694. // the whole point of the fix (the `[A]` used to defeat name matching).
  3695. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  3696. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  3697. // Editing Monoid surfaces the cross-file users: the instance val typed
  3698. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  3699. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  3700. expect(impacted).toContain('intMonoid'); // field type annotation
  3701. expect(impacted).toContain('fold'); // trailing implicit parameter list
  3702. });
  3703. });
  3704. describe('PHP namespace + import resolution', () => {
  3705. let tempDir: string;
  3706. let cg: CodeGraph;
  3707. beforeEach(() => {
  3708. tempDir = createTempDir();
  3709. });
  3710. afterEach(() => {
  3711. if (cg) cg.close();
  3712. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3713. });
  3714. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  3715. const src = path.join(tempDir, 'src');
  3716. // Two interfaces with the SAME simple name in different namespaces — the
  3717. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  3718. // resolve. The namespace qualifies them; the `use` import disambiguates.
  3719. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  3720. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  3721. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  3722. fs.writeFileSync(
  3723. path.join(src, 'Cache', 'Factory.php'),
  3724. `<?php
  3725. namespace Contracts\\Cache;
  3726. interface Factory {
  3727. public function store(): object;
  3728. }
  3729. `
  3730. );
  3731. fs.writeFileSync(
  3732. path.join(src, 'Mail', 'Factory.php'),
  3733. `<?php
  3734. namespace Contracts\\Mail;
  3735. interface Factory {
  3736. public function mailer(): object;
  3737. }
  3738. `
  3739. );
  3740. fs.writeFileSync(
  3741. path.join(src, 'App', 'Service.php'),
  3742. `<?php
  3743. namespace App;
  3744. use Contracts\\Cache\\Factory;
  3745. class Service {
  3746. public function make(): Factory {
  3747. return resolve(Factory::class);
  3748. }
  3749. }
  3750. `
  3751. );
  3752. cg = CodeGraph.initSync(tempDir);
  3753. await cg.indexAll();
  3754. cg.resolveReferences();
  3755. // The PHP namespace is captured into the qualified name, so the two
  3756. // same-named interfaces are distinguishable.
  3757. const cacheFactory = cg
  3758. .getNodesByKind('interface')
  3759. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  3760. const mailFactory = cg
  3761. .getNodesByKind('interface')
  3762. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  3763. expect(cacheFactory).toBeDefined();
  3764. expect(mailFactory).toBeDefined();
  3765. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  3766. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  3767. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  3768. const serviceFile = 'src/App/Service.php';
  3769. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  3770. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3771. );
  3772. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  3773. (n) => (n.filePath ?? '').endsWith(serviceFile)
  3774. );
  3775. expect(cacheReaches).toBe(true);
  3776. expect(mailReaches).toBe(false);
  3777. });
  3778. });
  3779. describe('Ruby mixins (include/extend/prepend)', () => {
  3780. let tempDir: string;
  3781. let cg: CodeGraph;
  3782. beforeEach(() => {
  3783. tempDir = createTempDir();
  3784. });
  3785. afterEach(() => {
  3786. if (cg) cg.close();
  3787. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3788. });
  3789. it('links include/extend/prepend to the mixed-in module across files', async () => {
  3790. const lib = path.join(tempDir, 'lib');
  3791. fs.mkdirSync(lib, { recursive: true });
  3792. fs.writeFileSync(
  3793. path.join(lib, 'concerns.rb'),
  3794. `module Trackable
  3795. def track; end
  3796. end
  3797. module Cacheable
  3798. def cache; end
  3799. end
  3800. module Loggable
  3801. def log; end
  3802. end
  3803. `
  3804. );
  3805. fs.writeFileSync(
  3806. path.join(lib, 'model.rb'),
  3807. `class Model
  3808. include Trackable
  3809. prepend Cacheable
  3810. extend Loggable
  3811. end
  3812. `
  3813. );
  3814. cg = CodeGraph.initSync(tempDir);
  3815. await cg.indexAll();
  3816. cg.resolveReferences();
  3817. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  3818. expect(model).toBeDefined();
  3819. // All three mixin forms create an `implements` edge Model → module, so
  3820. // editing a concern surfaces every class that mixes it in (across files).
  3821. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  3822. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  3823. expect(mod, moduleName).toBeDefined();
  3824. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  3825. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  3826. }
  3827. });
  3828. it('resolves require / require_relative to the required file', async () => {
  3829. const lib = path.join(tempDir, 'lib');
  3830. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  3831. // A leaf file whose class is referenced only dynamically — so without
  3832. // require resolution it would look like nothing depends on it.
  3833. fs.writeFileSync(
  3834. path.join(lib, 'app', 'fetcher.rb'),
  3835. `module App
  3836. class Fetcher
  3837. def fetch; end
  3838. end
  3839. end
  3840. `
  3841. );
  3842. // Pulled in by a load-path `require` …
  3843. fs.writeFileSync(
  3844. path.join(lib, 'app', 'worker.rb'),
  3845. `require "app/fetcher"
  3846. module App
  3847. class Worker; end
  3848. end
  3849. `
  3850. );
  3851. // … and a sibling pulled in by `require_relative`.
  3852. fs.writeFileSync(
  3853. path.join(lib, 'app', 'boot.rb'),
  3854. `require_relative "fetcher"
  3855. `
  3856. );
  3857. cg = CodeGraph.initSync(tempDir);
  3858. await cg.indexAll();
  3859. cg.resolveReferences();
  3860. // The require edges target fetcher.rb's FILE node. Editing it should reach
  3861. // BOTH the load-path requirer (worker.rb) and the require_relative one
  3862. // (boot.rb) — without require resolution its file would have no dependents.
  3863. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  3864. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  3865. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  3866. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  3867. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  3868. });
  3869. });
  3870. describe('C++ free-function name extraction', () => {
  3871. let tempDir: string;
  3872. let cg: CodeGraph;
  3873. beforeEach(() => {
  3874. tempDir = createTempDir();
  3875. });
  3876. afterEach(() => {
  3877. if (cg) cg.close();
  3878. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3879. });
  3880. it('names a free function correctly when it has qualified-type params or a trailing return type', async () => {
  3881. const src = path.join(tempDir, 'src');
  3882. fs.mkdirSync(src, { recursive: true });
  3883. // TableFileName has a `const std::string&` parameter; BuildName uses an
  3884. // `auto … -> std::string` trailing return type. Both used to be named
  3885. // `string` (picked up from the parameter / return type), so callers never
  3886. // resolved and the defining file looked like nothing depended on it.
  3887. fs.writeFileSync(
  3888. path.join(src, 'names.cc'),
  3889. `#include <string>
  3890. std::string TableFileName(const std::string& dbname, int number) {
  3891. return dbname;
  3892. }
  3893. auto BuildName(const std::string& a) -> std::string {
  3894. return a;
  3895. }
  3896. `
  3897. );
  3898. fs.writeFileSync(
  3899. path.join(src, 'user.cc'),
  3900. `#include <string>
  3901. std::string use() {
  3902. return TableFileName("db", 1) + BuildName("x");
  3903. }
  3904. `
  3905. );
  3906. cg = CodeGraph.initSync(tempDir);
  3907. await cg.indexAll();
  3908. cg.resolveReferences();
  3909. // The functions are extracted under their real names, not `string`.
  3910. const fns = cg.getNodesByKind('function');
  3911. const tableFn = fns.find((n) => n.name === 'TableFileName');
  3912. const buildFn = fns.find((n) => n.name === 'BuildName');
  3913. expect(tableFn, 'TableFileName extracted (not "string")').toBeDefined();
  3914. expect(buildFn, 'BuildName extracted (not "string")').toBeDefined();
  3915. // And the cross-file calls resolve to them, so editing names.cc surfaces user.cc.
  3916. for (const fn of [tableFn!, buildFn!]) {
  3917. const reached = [...cg.getImpactRadius(fn.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3918. expect(reached.some((p) => p.endsWith('user.cc')), `${fn.name} should be called from user.cc`).toBe(true);
  3919. }
  3920. });
  3921. });
  3922. describe('Dart mixins and type references', () => {
  3923. let tempDir: string;
  3924. let cg: CodeGraph;
  3925. beforeEach(() => {
  3926. tempDir = createTempDir();
  3927. });
  3928. afterEach(() => {
  3929. if (cg) cg.close();
  3930. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3931. });
  3932. it('links `with` mixins and method parameter/return types across files', async () => {
  3933. const lib = path.join(tempDir, 'lib');
  3934. fs.mkdirSync(lib, { recursive: true });
  3935. fs.writeFileSync(
  3936. path.join(lib, 'models.dart'),
  3937. `class User {
  3938. final String name;
  3939. User(this.name);
  3940. }
  3941. mixin Loggable {
  3942. void log() {}
  3943. }
  3944. abstract class Repository {
  3945. User find(int id);
  3946. }
  3947. `
  3948. );
  3949. fs.writeFileSync(
  3950. path.join(lib, 'service.dart'),
  3951. `import 'models.dart';
  3952. class UserService extends Repository with Loggable {
  3953. @override
  3954. User find(int id) => User('x');
  3955. List<User> all() => [];
  3956. }
  3957. `
  3958. );
  3959. cg = CodeGraph.initSync(tempDir);
  3960. await cg.indexAll();
  3961. cg.resolveReferences();
  3962. const inModels = (name: string) =>
  3963. cg.getNodesByKind('class').concat(cg.getNodesByKind('module'))
  3964. .find((n) => n.name === name && n.filePath.endsWith('models.dart'));
  3965. // The `with Loggable` mixin records a dependency — editing the mixin surfaces
  3966. // the class that mixes it in (across files). Loggable is a `mixin`, indexed
  3967. // as a class-like node.
  3968. const loggable = cg.getNodesByKind('class').find((n) => n.name === 'Loggable')
  3969. ?? cg.getNodesByKind('module').find((n) => n.name === 'Loggable');
  3970. expect(loggable, 'Loggable mixin indexed').toBeDefined();
  3971. const mixinUsers = [...cg.getImpactRadius(loggable!.id, 3).nodes.values()].map((n) => n.name);
  3972. expect(mixinUsers).toContain('UserService');
  3973. // `User` is used only as a method parameter/return type in service.dart —
  3974. // editing it must still surface service.dart via the type references.
  3975. const user = inModels('User') ?? cg.getNodesByKind('class').find((n) => n.name === 'User');
  3976. expect(user, 'User indexed').toBeDefined();
  3977. const userDeps = [...cg.getImpactRadius(user!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  3978. expect(userDeps.some((p) => p.endsWith('service.dart'))).toBe(true);
  3979. });
  3980. });
  3981. describe('Static-member / value-read references', () => {
  3982. let tempDir: string;
  3983. let cg: CodeGraph;
  3984. beforeEach(() => {
  3985. tempDir = createTempDir();
  3986. });
  3987. afterEach(() => {
  3988. if (cg) cg.close();
  3989. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  3990. });
  3991. it('links a type referenced only via a static field / enum value (and ignores lowercase receivers)', async () => {
  3992. fs.writeFileSync(
  3993. path.join(tempDir, 'JsonScope.java'),
  3994. `class JsonScope {
  3995. static final int EMPTY_DOCUMENT = 1;
  3996. }
  3997. `
  3998. );
  3999. fs.writeFileSync(
  4000. path.join(tempDir, 'Reader.java'),
  4001. `class Reader {
  4002. private int helper;
  4003. int peek() {
  4004. return JsonScope.EMPTY_DOCUMENT;
  4005. }
  4006. int noop() {
  4007. return this.helper;
  4008. }
  4009. }
  4010. `
  4011. );
  4012. cg = CodeGraph.initSync(tempDir);
  4013. await cg.indexAll();
  4014. cg.resolveReferences();
  4015. // JsonScope is used ONLY as `JsonScope.EMPTY_DOCUMENT` (a static-field value
  4016. // read — never constructed or called), so before the static-member pass it
  4017. // had no dependents. Editing it now surfaces Reader.java.
  4018. const scope = cg.getNodesByKind('class').find((n) => n.name === 'JsonScope');
  4019. expect(scope, 'JsonScope indexed').toBeDefined();
  4020. const reached = [...cg.getImpactRadius(scope!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  4021. expect(reached.some((p) => p.endsWith('Reader.java'))).toBe(true);
  4022. // A lowercase receiver (`this.helper`) must NOT be emitted as a type ref —
  4023. // only Capitalized receivers (types) are. No node named `this`/`helper`
  4024. // should appear as a reference target from peek/noop beyond JsonScope.
  4025. const refTargets = cg
  4026. .getNodesByKind('class')
  4027. .filter((n) => n.name === 'this' || n.name === 'helper');
  4028. expect(refTargets.length).toBe(0);
  4029. });
  4030. it('does not link a static-member read across language families (coincidental name)', async () => {
  4031. // A native (Kotlin) `Build.VERSION` reads the Android system class — it must
  4032. // NOT link to a coincidentally same-named TS class (the cross-language false
  4033. // positive that name-matching produces; `references` edges are language-local).
  4034. fs.writeFileSync(
  4035. path.join(tempDir, 'Build.ts'),
  4036. `export class Build {\n static version = 1;\n}\n`
  4037. );
  4038. fs.writeFileSync(
  4039. path.join(tempDir, 'Device.kt'),
  4040. `package app\nclass Device {\n fun sdk(): Int = Build.VERSION\n}\n`
  4041. );
  4042. cg = CodeGraph.initSync(tempDir);
  4043. await cg.indexAll();
  4044. cg.resolveReferences();
  4045. const tsBuild = cg.getNodesByKind('class').find((n) => n.name === 'Build' && n.filePath.endsWith('Build.ts'));
  4046. expect(tsBuild).toBeDefined();
  4047. // The Kotlin file is `app/Device.kt`; the TS Build must have NO dependent there.
  4048. const deps = [...cg.getImpactRadius(tsBuild!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4049. expect(deps.some((p) => p.endsWith('Device.kt'))).toBe(false);
  4050. });
  4051. });
  4052. describe('Cross-language type/import gate (RN name collisions)', () => {
  4053. let tempDir: string;
  4054. let cg: CodeGraph;
  4055. beforeEach(() => {
  4056. tempDir = createTempDir();
  4057. });
  4058. afterEach(() => {
  4059. if (cg) cg.close();
  4060. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4061. });
  4062. it('a TS PascalCase type ref lands on the TS type, never a same-named native class', async () => {
  4063. // react-native-async-storage's example app has a TS `type TestRunner` AND a
  4064. // Kotlin `class TestRunner`. The React PascalCase resolver name-matched the
  4065. // Kotlin `class` (its COMPONENT_KINDS includes `class`) with no language
  4066. // check at confidence 0.8, outranking the (cross-language-penalized 0.5)
  4067. // TS name-match — so a TS ref to `TestRunner` crossed web→jvm. The ref here
  4068. // is intentionally NOT imported: a clean relative import would mask the bug
  4069. // by resolving via the import map before the framework strategy can win.
  4070. fs.writeFileSync(
  4071. path.join(tempDir, 'package.json'),
  4072. JSON.stringify({ dependencies: { 'react-native': '*' } })
  4073. );
  4074. fs.writeFileSync(
  4075. path.join(tempDir, 'useTests.ts'),
  4076. `export type TestRunner = { run: () => void };\n`
  4077. );
  4078. fs.writeFileSync(
  4079. path.join(tempDir, 'basic.tsx'),
  4080. `export function useBasicTest(r: TestRunner): TestRunner {\n return r;\n}\n`
  4081. );
  4082. fs.writeFileSync(
  4083. path.join(tempDir, 'TestUtils.kt'),
  4084. `package app\nclass TestRunner {\n fun run() {}\n}\n`
  4085. );
  4086. cg = CodeGraph.initSync(tempDir);
  4087. await cg.indexAll();
  4088. cg.resolveReferences();
  4089. const ktRunner = cg
  4090. .getNodesByKind('class')
  4091. .find((n) => n.name === 'TestRunner' && n.filePath.endsWith('TestUtils.kt'));
  4092. expect(ktRunner, 'Kotlin TestRunner class').toBeDefined();
  4093. const ktDeps = [...cg.getImpactRadius(ktRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4094. expect(ktDeps.some((p) => p.endsWith('basic.tsx')), 'Kotlin class has NO TS dependent').toBe(false);
  4095. const tsRunner = cg.getNodesByKind('type_alias').find((n) => n.name === 'TestRunner');
  4096. expect(tsRunner, 'TS TestRunner type_alias').toBeDefined();
  4097. const tsDeps = [...cg.getImpactRadius(tsRunner!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4098. expect(tsDeps.some((p) => p.endsWith('basic.tsx')), 'TS type captured the ref (re-pointed)').toBe(true);
  4099. });
  4100. it('gates a cross-family import name collision but keeps same-family imports', async () => {
  4101. // A TS `import { Widget }` that only matches a Swift `class Widget` must not
  4102. // create a web→apple dependency — but a sibling TS module imported by
  4103. // another TS file (same family) must still resolve (no over-gating).
  4104. fs.writeFileSync(path.join(tempDir, 'Widget.swift'), `class Widget {\n func render() {}\n}\n`);
  4105. fs.writeFileSync(
  4106. path.join(tempDir, 'widget.ts'),
  4107. `import { Widget } from './native';\nexport function mount(w: Widget) {}\n`
  4108. );
  4109. fs.writeFileSync(path.join(tempDir, 'util.ts'), `export class Helper {}\n`);
  4110. fs.writeFileSync(
  4111. path.join(tempDir, 'app.ts'),
  4112. `import { Helper } from './util';\nexport const h = new Helper();\n`
  4113. );
  4114. cg = CodeGraph.initSync(tempDir);
  4115. await cg.indexAll();
  4116. cg.resolveReferences();
  4117. const swiftWidget = cg
  4118. .getNodesByKind('class')
  4119. .find((n) => n.name === 'Widget' && n.filePath.endsWith('.swift'));
  4120. expect(swiftWidget, 'Swift Widget class').toBeDefined();
  4121. const wDeps = [...cg.getImpactRadius(swiftWidget!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4122. expect(wDeps.some((p) => p.endsWith('widget.ts')), 'Swift class has NO TS dependent').toBe(false);
  4123. // Same-family control — the TS Helper must still see its TS dependent.
  4124. const helper = cg.getNodesByKind('class').find((n) => n.name === 'Helper');
  4125. expect(helper, 'TS Helper class').toBeDefined();
  4126. const hDeps = [...cg.getImpactRadius(helper!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4127. expect(hDeps.some((p) => p.endsWith('app.ts')), 'same-family TS import preserved').toBe(true);
  4128. });
  4129. });
  4130. describe('Python absolute module import resolution', () => {
  4131. let tempDir: string;
  4132. let cg: CodeGraph;
  4133. beforeEach(() => {
  4134. tempDir = createTempDir();
  4135. });
  4136. afterEach(() => {
  4137. if (cg) cg.close();
  4138. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4139. });
  4140. it('links a bare `import pkg.module` of an internal module to its file', async () => {
  4141. // `import conduit.apps.signals` (a Django-style side-effect import, and any
  4142. // dotted absolute module import) had no edge to the module file — only
  4143. // `from x import y` was linked — so a module imported by its dotted path
  4144. // looked like nothing depended on it.
  4145. fs.mkdirSync(path.join(tempDir, 'conduit/apps'), { recursive: true });
  4146. fs.writeFileSync(path.join(tempDir, 'conduit/__init__.py'), '');
  4147. fs.writeFileSync(path.join(tempDir, 'conduit/apps/__init__.py'), '');
  4148. fs.writeFileSync(path.join(tempDir, 'conduit/apps/signals.py'), `def handler():\n pass\n`);
  4149. fs.writeFileSync(
  4150. path.join(tempDir, 'conduit/apps/app.py'),
  4151. `import conduit.apps.signals\nimport os\n\nVALUE = 1\n`
  4152. );
  4153. cg = CodeGraph.initSync(tempDir);
  4154. await cg.indexAll();
  4155. cg.resolveReferences();
  4156. const signals = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('conduit/apps/signals.py'));
  4157. expect(signals, 'signals.py indexed').toBeDefined();
  4158. const deps = [...cg.getImpactRadius(signals!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4159. expect(deps.some((p) => p.endsWith('app.py')), 'importer depends on the module').toBe(true);
  4160. // `import os` (stdlib) must NOT fabricate an edge — no os.py file in the repo.
  4161. const osNode = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('/os.py'));
  4162. expect(osNode, 'no stdlib os.py node').toBeUndefined();
  4163. });
  4164. it('Django include() links the root URLconf to the included app urls module', async () => {
  4165. // `url(r'^api/', include('app.urls'))` should record a dependency from the
  4166. // root urlconf onto the included app's `urls.py` — so editing an app's routes
  4167. // surfaces the project urlconf that mounts them.
  4168. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  4169. fs.writeFileSync(path.join(tempDir, 'requirements.txt'), `django==4.0\n`);
  4170. fs.writeFileSync(path.join(tempDir, 'app/__init__.py'), '');
  4171. fs.writeFileSync(path.join(tempDir, 'app/views.py'), `def home(request):\n return None\n`);
  4172. fs.writeFileSync(
  4173. path.join(tempDir, 'app/urls.py'),
  4174. `from django.conf.urls import url\nfrom . import views\nurlpatterns = [url(r'^$', views.home)]\n`
  4175. );
  4176. fs.writeFileSync(
  4177. path.join(tempDir, 'urls.py'),
  4178. `from django.conf.urls import include, url\nurlpatterns = [url(r'^app/', include('app.urls'))]\n`
  4179. );
  4180. cg = CodeGraph.initSync(tempDir);
  4181. await cg.indexAll();
  4182. cg.resolveReferences();
  4183. const appUrls = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/urls.py'));
  4184. expect(appUrls, 'app/urls.py indexed').toBeDefined();
  4185. const deps = [...cg.getImpactRadius(appUrls!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4186. expect(deps.some((p) => p.endsWith('urls.py') && !p.endsWith('app/urls.py')), 'root urlconf depends on the included app urls').toBe(true);
  4187. });
  4188. it('resolves `from pkg import submodule` to the submodule under that package, not a same-named one', async () => {
  4189. // FastAPI router-aggregator pattern: `from app.api.routes import authentication`
  4190. // with same-named modules in sibling packages must resolve via the import's
  4191. // SOURCE (the package), not a coincidental same-basename file elsewhere.
  4192. fs.mkdirSync(path.join(tempDir, 'app/api/routes'), { recursive: true });
  4193. fs.mkdirSync(path.join(tempDir, 'app/api/dependencies'), { recursive: true });
  4194. for (const p of ['app/__init__.py', 'app/api/__init__.py', 'app/api/routes/__init__.py', 'app/api/dependencies/__init__.py']) {
  4195. fs.writeFileSync(path.join(tempDir, p), '');
  4196. }
  4197. fs.writeFileSync(path.join(tempDir, 'app/api/routes/authentication.py'), `def login():\n pass\n`);
  4198. fs.writeFileSync(path.join(tempDir, 'app/api/dependencies/authentication.py'), `def get_user():\n pass\n`);
  4199. fs.writeFileSync(
  4200. path.join(tempDir, 'app/api/routes/api.py'),
  4201. `from app.api.routes import authentication\n\nROUTER = authentication\n`
  4202. );
  4203. cg = CodeGraph.initSync(tempDir);
  4204. await cg.indexAll();
  4205. cg.resolveReferences();
  4206. const routesAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('routes/authentication.py'));
  4207. const depsAuth = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('dependencies/authentication.py'));
  4208. expect(routesAuth && depsAuth).toBeTruthy();
  4209. const routesDeps = [...cg.getImpactRadius(routesAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4210. const depsDeps = [...cg.getImpactRadius(depsAuth!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4211. expect(routesDeps.some((p) => p.endsWith('routes/api.py')), 'submodule under the imported package is the dependent').toBe(true);
  4212. expect(depsDeps.some((p) => p.endsWith('routes/api.py')), 'same-named module in a sibling package is NOT').toBe(false);
  4213. });
  4214. });
  4215. describe('Razor / Blazor markup extraction', () => {
  4216. let tempDir: string;
  4217. let cg: CodeGraph;
  4218. beforeEach(() => {
  4219. tempDir = createTempDir();
  4220. });
  4221. afterEach(() => {
  4222. if (cg) cg.close();
  4223. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4224. });
  4225. it('links @model and Blazor component tags to their C# types; ignores HTML elements', async () => {
  4226. fs.mkdirSync(path.join(tempDir, 'Views'), { recursive: true });
  4227. fs.writeFileSync(
  4228. path.join(tempDir, 'LoginViewModel.cs'),
  4229. `namespace App { public class LoginViewModel { public string Email { get; set; } } }`
  4230. );
  4231. fs.writeFileSync(
  4232. path.join(tempDir, 'ToastComponent.cs'),
  4233. `namespace App { public class ToastComponent { } }`
  4234. );
  4235. fs.writeFileSync(
  4236. path.join(tempDir, 'Views/Login.cshtml'),
  4237. `@model LoginViewModel\n<div class="form">\n <input asp-for="Email" />\n</div>\n`
  4238. );
  4239. fs.writeFileSync(
  4240. path.join(tempDir, 'Index.razor'),
  4241. `<div>\n <ToastComponent />\n</div>\n`
  4242. );
  4243. cg = CodeGraph.initSync(tempDir);
  4244. await cg.indexAll();
  4245. cg.resolveReferences();
  4246. // `@model LoginViewModel` → the view-model class.
  4247. const vm = cg.getNodesByKind('class').find((n) => n.name === 'LoginViewModel');
  4248. expect(vm, 'LoginViewModel class').toBeDefined();
  4249. const vmDeps = [...cg.getImpactRadius(vm!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4250. expect(vmDeps.some((p) => p.endsWith('Login.cshtml')), '@model links the view').toBe(true);
  4251. // `<ToastComponent />` → the component class.
  4252. const toast = cg.getNodesByKind('class').find((n) => n.name === 'ToastComponent');
  4253. expect(toast, 'ToastComponent class').toBeDefined();
  4254. const toastDeps = [...cg.getImpactRadius(toast!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4255. expect(toastDeps.some((p) => p.endsWith('Index.razor')), 'Blazor tag links the component').toBe(true);
  4256. // HTML elements (`<div>`, `<input>`) must NOT become component references.
  4257. const htmlNodes = cg.getNodesByKind('class').filter((n) => n.name === 'div' || n.name === 'input');
  4258. expect(htmlNodes.length, 'no node for HTML elements').toBe(0);
  4259. });
  4260. it('C# namespaces qualify type names so same-named types are distinct', async () => {
  4261. fs.writeFileSync(path.join(tempDir, 'entity.cs'), `namespace App.Entities { public class CatalogBrand { } }`);
  4262. fs.writeFileSync(path.join(tempDir, 'dto.cs'), `namespace App.Models { public class CatalogBrand { } }`);
  4263. cg = CodeGraph.initSync(tempDir);
  4264. await cg.indexAll();
  4265. const brands = cg.getNodesByKind('class').filter((n) => n.name === 'CatalogBrand');
  4266. expect(brands.length, 'both CatalogBrand classes indexed').toBe(2);
  4267. const qns = brands.map((b) => b.qualifiedName).sort();
  4268. expect(qns[0]).not.toBe(qns[1]); // distinct qualified names (namespace-scoped)
  4269. expect(qns.some((q) => q.includes('Entities') && q.endsWith('CatalogBrand'))).toBe(true);
  4270. expect(qns.some((q) => q.includes('Models') && q.endsWith('CatalogBrand'))).toBe(true);
  4271. });
  4272. it('disambiguates a Razor type ref via @using (incl. folder _Imports.razor)', async () => {
  4273. // `CatalogBrand` exists as both a domain entity and a DTO; the component
  4274. // `@using`s the DTO's namespace (here via the folder _Imports.razor), so the
  4275. // ref must resolve to the DTO, not the same-named entity.
  4276. fs.mkdirSync(path.join(tempDir, 'Models'), { recursive: true });
  4277. fs.mkdirSync(path.join(tempDir, 'Entities'), { recursive: true });
  4278. fs.mkdirSync(path.join(tempDir, 'Pages'), { recursive: true });
  4279. fs.writeFileSync(path.join(tempDir, 'Models/CatalogBrand.cs'), `namespace App.Models { public class CatalogBrand { public int Id { get; set; } } }`);
  4280. fs.writeFileSync(path.join(tempDir, 'Entities/CatalogBrand.cs'), `namespace App.Entities { public class CatalogBrand { public int Id { get; set; } } }`);
  4281. fs.writeFileSync(path.join(tempDir, 'Pages/_Imports.razor'), `@using App.Models\n`);
  4282. fs.writeFileSync(
  4283. path.join(tempDir, 'Pages/List.razor'),
  4284. `<h1>List</h1>\n@code {\n private CatalogBrand _b = new CatalogBrand();\n}\n`
  4285. );
  4286. cg = CodeGraph.initSync(tempDir);
  4287. await cg.indexAll();
  4288. cg.resolveReferences();
  4289. const dto = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Models::CatalogBrand');
  4290. const entity = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'App.Entities::CatalogBrand');
  4291. expect(dto && entity, 'both CatalogBrand classes').toBeTruthy();
  4292. const dtoDeps = [...cg.getImpactRadius(dto!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4293. const entityDeps = [...cg.getImpactRadius(entity!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4294. expect(dtoDeps.some((p) => p.endsWith('List.razor')), 'resolves to the @using\'d DTO').toBe(true);
  4295. expect(entityDeps.some((p) => p.endsWith('List.razor')), 'NOT the same-named entity').toBe(false);
  4296. });
  4297. it('delegates Blazor @code block C# to cover types used in component logic', async () => {
  4298. fs.writeFileSync(
  4299. path.join(tempDir, 'CatalogService.cs'),
  4300. `namespace App { public class CatalogService { public void Load() { } } }`
  4301. );
  4302. fs.writeFileSync(
  4303. path.join(tempDir, 'List.razor'),
  4304. `<h1>Catalog</h1>\n\n@code {\n private CatalogService _svc = new CatalogService();\n void Refresh() { _svc.Load(); }\n}\n`
  4305. );
  4306. cg = CodeGraph.initSync(tempDir);
  4307. await cg.indexAll();
  4308. cg.resolveReferences();
  4309. const svc = cg.getNodesByKind('class').find((n) => n.name === 'CatalogService');
  4310. expect(svc, 'CatalogService class').toBeDefined();
  4311. const deps = [...cg.getImpactRadius(svc!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4312. expect(deps.some((p) => p.endsWith('List.razor')), '@code usage links the component to the service').toBe(true);
  4313. });
  4314. });
  4315. describe('Default import resolution (renamed default export)', () => {
  4316. let tempDir: string;
  4317. let cg: CodeGraph;
  4318. beforeEach(() => {
  4319. tempDir = createTempDir();
  4320. });
  4321. afterEach(() => {
  4322. if (cg) cg.close();
  4323. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4324. });
  4325. it('links a renamed default import to the module file', async () => {
  4326. // Express route aggregator: `import articlesController from './controller'`
  4327. // where the module does `export default router`. The renamed local can't be
  4328. // found as a symbol, so the controller file had no dependent — the dependency
  4329. // is on the module file regardless of the default export's name.
  4330. fs.mkdirSync(path.join(tempDir, 'app'), { recursive: true });
  4331. fs.writeFileSync(path.join(tempDir, 'app/controller.ts'), `const router = { get() {} };\nexport default router;\n`);
  4332. fs.writeFileSync(path.join(tempDir, 'app/routes.ts'), `import myController from './controller';\nexport const api = myController;\n`);
  4333. cg = CodeGraph.initSync(tempDir);
  4334. await cg.indexAll();
  4335. cg.resolveReferences();
  4336. const controller = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/controller.ts'));
  4337. expect(controller, 'controller.ts indexed').toBeDefined();
  4338. const deps = [...cg.getImpactRadius(controller!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4339. expect(deps.some((p) => p.endsWith('routes.ts')), 'importer depends on the default-exporting module').toBe(true);
  4340. });
  4341. });
  4342. describe('Chained method-call resolution (C# extension methods)', () => {
  4343. let tempDir: string;
  4344. let cg: CodeGraph;
  4345. beforeEach(() => {
  4346. tempDir = createTempDir();
  4347. });
  4348. afterEach(() => {
  4349. if (cg) cg.close();
  4350. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4351. });
  4352. it('resolves a chained extension-method call (a.b.Method()) to its definition', async () => {
  4353. // ASP.NET DI registration: `builder.Services.AddCoreServices(...)` calls a
  4354. // static extension method elsewhere. A multi-dot receiver chain matched no
  4355. // method-call pattern before, so the extension method had no caller.
  4356. fs.mkdirSync(path.join(tempDir, 'cfg'), { recursive: true });
  4357. fs.writeFileSync(
  4358. path.join(tempDir, 'cfg/Ext.cs'),
  4359. `namespace App {\n public static class Ext {\n public static object AddCoreServices(this object services, int x) { return services; }\n }\n}\n`
  4360. );
  4361. fs.writeFileSync(
  4362. path.join(tempDir, 'Program.cs'),
  4363. `namespace App {\n public class Program {\n public void Run(object builder) {\n builder.Services.AddCoreServices(1);\n }\n }\n}\n`
  4364. );
  4365. cg = CodeGraph.initSync(tempDir);
  4366. await cg.indexAll();
  4367. cg.resolveReferences();
  4368. const ext = cg
  4369. .getNodesByKind('method')
  4370. .find((n) => n.name === 'AddCoreServices')
  4371. ?? cg.getNodesByKind('function').find((n) => n.name === 'AddCoreServices');
  4372. expect(ext, 'AddCoreServices defined').toBeDefined();
  4373. const callers = [...cg.getImpactRadius(ext!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4374. expect(callers.some((p) => p.endsWith('Program.cs')), 'chained extension call resolves to its definition').toBe(true);
  4375. });
  4376. });
  4377. describe('Same-directory include + KMP import resolution', () => {
  4378. let tempDir: string;
  4379. let cg: CodeGraph;
  4380. beforeEach(() => {
  4381. tempDir = createTempDir();
  4382. });
  4383. afterEach(() => {
  4384. if (cg) cg.close();
  4385. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4386. });
  4387. it('a C/C++ #include resolves to the same-directory header, not a same-named one elsewhere', async () => {
  4388. // A multi-platform native module has a header of the same basename per
  4389. // platform. `windows/Provider.cpp`'s `#include "Storage.h"` means its OWN
  4390. // sibling header — not `apple/Storage.h` (which sorts first and so was
  4391. // picked arbitrarily before, leaving the real local header with 0 deps).
  4392. fs.mkdirSync(path.join(tempDir, 'apple'), { recursive: true });
  4393. fs.mkdirSync(path.join(tempDir, 'windows'), { recursive: true });
  4394. fs.writeFileSync(path.join(tempDir, 'apple', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  4395. fs.writeFileSync(path.join(tempDir, 'windows', 'Storage.h'), `#pragma once\nstruct Storage { int n; };\n`);
  4396. fs.writeFileSync(
  4397. path.join(tempDir, 'windows', 'Provider.cpp'),
  4398. `#include "Storage.h"\nint use() { Storage s; return s.n; }\n`
  4399. );
  4400. cg = CodeGraph.initSync(tempDir);
  4401. await cg.indexAll();
  4402. cg.resolveReferences();
  4403. const winHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('windows/Storage.h'));
  4404. const appleHeader = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('apple/Storage.h'));
  4405. expect(winHeader, 'windows/Storage.h indexed').toBeDefined();
  4406. expect(appleHeader, 'apple/Storage.h indexed').toBeDefined();
  4407. const winDeps = [...cg.getImpactRadius(winHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4408. const appleDeps = [...cg.getImpactRadius(appleHeader!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4409. expect(winDeps.some((p) => p.endsWith('Provider.cpp')), 'same-dir header gets the includer').toBe(true);
  4410. expect(appleDeps.some((p) => p.endsWith('Provider.cpp')), 'other-platform header does NOT').toBe(false);
  4411. });
  4412. it('a Kotlin Multiplatform commonMain import resolves to the expect, not a platform actual', async () => {
  4413. const common = path.join(tempDir, 'src/commonMain/kotlin/app');
  4414. const android = path.join(tempDir, 'src/androidMain/kotlin/app');
  4415. fs.mkdirSync(common, { recursive: true });
  4416. fs.mkdirSync(android, { recursive: true });
  4417. fs.writeFileSync(path.join(common, 'Platform.kt'), `package app\nexpect class PlatformContext\n`);
  4418. fs.writeFileSync(path.join(android, 'Platform.android.kt'), `package app\nactual class PlatformContext\n`);
  4419. fs.writeFileSync(
  4420. path.join(common, 'Db.kt'),
  4421. `package app\nimport app.PlatformContext\nclass Db {\n fun open(ctx: PlatformContext) {}\n}\n`
  4422. );
  4423. cg = CodeGraph.initSync(tempDir);
  4424. await cg.indexAll();
  4425. cg.resolveReferences();
  4426. const expectCtx = cg
  4427. .getNodesByKind('class')
  4428. .find((n) => n.name === 'PlatformContext' && n.filePath.endsWith('commonMain/kotlin/app/Platform.kt'));
  4429. expect(expectCtx, 'commonMain expect PlatformContext').toBeDefined();
  4430. const deps = [...cg.getImpactRadius(expectCtx!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4431. expect(deps.some((p) => p.endsWith('Db.kt')), 'commonMain import lands on the expect, not the actual').toBe(true);
  4432. });
  4433. });
  4434. describe('Delphi form code-behind pairing', () => {
  4435. let tempDir: string;
  4436. let cg: CodeGraph;
  4437. beforeEach(() => {
  4438. tempDir = createTempDir();
  4439. });
  4440. afterEach(() => {
  4441. if (cg) cg.close();
  4442. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4443. });
  4444. it('links a `.dfm` form to its sibling `.pas` code-behind unit', async () => {
  4445. // A Delphi form unit owns its visual form definition via `{$R *.dfm}`, not a
  4446. // `uses` clause — so a `.dfm` used only as a form definition looked orphaned.
  4447. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.dfm'),
  4448. `object FRMAbout: TFRMAbout\n Caption = 'About'\nend\n`);
  4449. fs.writeFileSync(path.join(tempDir, 'UFRMAbout.pas'),
  4450. `unit UFRMAbout;\ninterface\nuses Forms;\ntype\n TFRMAbout = class(TForm)\n end;\nimplementation\n{$R *.dfm}\nend.\n`);
  4451. cg = CodeGraph.initSync(tempDir);
  4452. await cg.indexAll();
  4453. cg.resolveReferences();
  4454. const dfm = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('UFRMAbout.dfm'));
  4455. expect(dfm, 'UFRMAbout.dfm file node').toBeDefined();
  4456. const deps = cg.getFileDependents(dfm!.filePath);
  4457. expect(deps.some((p) => p.endsWith('UFRMAbout.pas')), 'the .pas unit links its .dfm form').toBe(true);
  4458. });
  4459. });
  4460. describe('Liquid Shopify JSON template section resolution', () => {
  4461. let tempDir: string;
  4462. let cg: CodeGraph;
  4463. beforeEach(() => {
  4464. tempDir = createTempDir();
  4465. });
  4466. afterEach(() => {
  4467. if (cg) cg.close();
  4468. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4469. });
  4470. it('links a Shopify JSON template section `type` to its sections/<type>.liquid', async () => {
  4471. // Shopify OS 2.0 templates are JSON, referencing sections by `type` — not
  4472. // a `{% section %}` Liquid tag — so a section used only from a JSON template
  4473. // looked unused. The JSON is now indexed and its `type`s linked.
  4474. fs.mkdirSync(path.join(tempDir, 'sections'), { recursive: true });
  4475. fs.mkdirSync(path.join(tempDir, 'templates/customers'), { recursive: true });
  4476. fs.writeFileSync(path.join(tempDir, 'sections/main-product.liquid'), `<div>{{ product.title }}</div>\n`);
  4477. fs.writeFileSync(path.join(tempDir, 'sections/main-login.liquid'), `<form>{{ 'customer.login' | t }}</form>\n`);
  4478. fs.writeFileSync(path.join(tempDir, 'templates/product.json'), JSON.stringify({ sections: { main: { type: 'main-product' } }, order: ['main'] }));
  4479. // Nested template dir (templates/customers/login.json) must resolve too.
  4480. fs.writeFileSync(path.join(tempDir, 'templates/customers/login.json'), JSON.stringify({ sections: { main: { type: 'main-login' } }, order: ['main'] }));
  4481. cg = CodeGraph.initSync(tempDir);
  4482. await cg.indexAll();
  4483. cg.resolveReferences();
  4484. const product = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-product.liquid'));
  4485. const login = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('sections/main-login.liquid'));
  4486. expect(product, 'main-product section').toBeDefined();
  4487. expect(login, 'main-login section').toBeDefined();
  4488. expect(cg.getFileDependents(product!.filePath).some((p) => p.endsWith('templates/product.json')), 'top-level JSON template links its section').toBe(true);
  4489. expect(cg.getFileDependents(login!.filePath).some((p) => p.endsWith('customers/login.json')), 'nested JSON template links its section').toBe(true);
  4490. });
  4491. });
  4492. describe('Lua/Luau require resolution', () => {
  4493. let tempDir: string;
  4494. let cg: CodeGraph;
  4495. beforeEach(() => {
  4496. tempDir = createTempDir();
  4497. });
  4498. afterEach(() => {
  4499. if (cg) cg.close();
  4500. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4501. });
  4502. it('resolves a dotted Lua require and an instance-path Luau require to their module files', async () => {
  4503. // The require is the ONLY link (no method call), so coverage here proves the
  4504. // require resolver specifically, not method-call name-matching.
  4505. // Lua dotted module path: require("myapp.config") → lua/myapp/config.lua.
  4506. fs.mkdirSync(path.join(tempDir, 'lua/myapp'), { recursive: true });
  4507. fs.writeFileSync(path.join(tempDir, 'lua/myapp/config.lua'), `local M = {}\nfunction M.setup() end\nreturn M\n`);
  4508. fs.writeFileSync(path.join(tempDir, 'lua/myapp/init.lua'), `local config = require("myapp.config")\nreturn config\n`);
  4509. // Luau Roblox instance-path require (only the leaf survives extraction):
  4510. // require(script.Util.helper) → src/Util/helper.luau.
  4511. fs.mkdirSync(path.join(tempDir, 'src/Util'), { recursive: true });
  4512. fs.writeFileSync(path.join(tempDir, 'src/Util/helper.luau'), `local H = {}\nfunction H.go() end\nreturn H\n`);
  4513. fs.writeFileSync(path.join(tempDir, 'src/init.luau'), `local helper = require(script.Util.helper)\nreturn helper\n`);
  4514. cg = CodeGraph.initSync(tempDir);
  4515. await cg.indexAll();
  4516. cg.resolveReferences();
  4517. const config = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('myapp/config.lua'));
  4518. const helper = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('Util/helper.luau'));
  4519. expect(config, 'config.lua file node').toBeDefined();
  4520. expect(helper, 'helper.luau file node').toBeDefined();
  4521. const cfgDeps = cg.getFileDependents(config!.filePath);
  4522. const helpDeps = cg.getFileDependents(helper!.filePath);
  4523. expect(cfgDeps.some((p) => p.endsWith('myapp/init.lua')), 'dotted Lua require resolves to the module').toBe(true);
  4524. expect(helpDeps.some((p) => p.endsWith('src/init.luau')), 'instance-path Luau require resolves to the module').toBe(true);
  4525. });
  4526. });
  4527. describe('Rust module-path call resolution', () => {
  4528. let tempDir: string;
  4529. let cg: CodeGraph;
  4530. beforeEach(() => {
  4531. tempDir = createTempDir();
  4532. });
  4533. afterEach(() => {
  4534. if (cg) cg.close();
  4535. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4536. });
  4537. it('a bare submodule call (`users::router()`) resolves self-relative to the submodule fn', async () => {
  4538. // The canonical Axum router-assembly pattern: a parent module calls each
  4539. // submodule's `router()`. `users::` / `profiles::` are SELF-relative
  4540. // submodule prefixes (2018 edition) — `mod users;` makes `users` a child of
  4541. // the CURRENT module, NOT `crate::users`. Before the fix the bare prefix was
  4542. // resolved crate-relative only (looking for `src/users.rs`), so it found
  4543. // nothing and the handler modules looked dependent-less.
  4544. const http = path.join(tempDir, 'src/http');
  4545. fs.mkdirSync(http, { recursive: true });
  4546. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod http;\n`);
  4547. fs.writeFileSync(
  4548. path.join(http, 'mod.rs'),
  4549. `mod users;\nmod profiles;\npub fn api_router() {\n users::router();\n profiles::router();\n}\n`
  4550. );
  4551. fs.writeFileSync(path.join(http, 'users.rs'), `pub fn router() -> i32 { 1 }\n`);
  4552. fs.writeFileSync(path.join(http, 'profiles.rs'), `pub fn router() -> i32 { 2 }\n`);
  4553. cg = CodeGraph.initSync(tempDir);
  4554. await cg.indexAll();
  4555. cg.resolveReferences();
  4556. // Each submodule's same-named `router` fn must get mod.rs as a dependent —
  4557. // proving the bare prefix resolved self-relative AND disambiguated the
  4558. // colliding `router` name to the correct file (not an arbitrary one).
  4559. const routers = cg.getNodesByKind('function').filter((n) => n.name === 'router');
  4560. const usersRouter = routers.find((n) => n.filePath.endsWith('http/users.rs'));
  4561. const profilesRouter = routers.find((n) => n.filePath.endsWith('http/profiles.rs'));
  4562. expect(usersRouter, 'users.rs router fn').toBeDefined();
  4563. expect(profilesRouter, 'profiles.rs router fn').toBeDefined();
  4564. const usersDeps = [...cg.getImpactRadius(usersRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4565. const profilesDeps = [...cg.getImpactRadius(profilesRouter!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4566. expect(usersDeps.some((p) => p.endsWith('http/mod.rs')), 'users::router() lands on users.rs').toBe(true);
  4567. expect(profilesDeps.some((p) => p.endsWith('http/mod.rs')), 'profiles::router() lands on profiles.rs').toBe(true);
  4568. });
  4569. it('a 3-segment module-path call (`database::profiles::find()`) resolves to the leaf fn', async () => {
  4570. // A 2-level module path — the common `db.run(move |c| database::profiles::find(c))`
  4571. // / `crate::a::b::func()` shape. The reference-resolver pre-filter used to drop any
  4572. // `a::b::c` whose leaf it never checked (it tested only the first segment and the
  4573. // `b::c` remainder, neither of which names a symbol), so the call never reached the
  4574. // Rust path resolver and the leaf module looked dependent-less.
  4575. const routes = path.join(tempDir, 'src/routes');
  4576. const database = path.join(tempDir, 'src/database');
  4577. fs.mkdirSync(routes, { recursive: true });
  4578. fs.mkdirSync(database, { recursive: true });
  4579. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'), `pub mod routes;\npub mod database;\n`);
  4580. fs.writeFileSync(path.join(database, 'mod.rs'), `pub mod profiles;\n`);
  4581. fs.writeFileSync(path.join(database, 'profiles.rs'), `pub fn find(id: i32) -> i32 { id }\n`);
  4582. fs.writeFileSync(
  4583. path.join(routes, 'mod.rs'),
  4584. `use crate::database;\npub fn get_profile(id: i32) -> i32 {\n database::profiles::find(id)\n}\n`
  4585. );
  4586. cg = CodeGraph.initSync(tempDir);
  4587. await cg.indexAll();
  4588. cg.resolveReferences();
  4589. const find = cg
  4590. .getNodesByKind('function')
  4591. .find((n) => n.name === 'find' && n.filePath.endsWith('database/profiles.rs'));
  4592. expect(find, 'database/profiles.rs find fn').toBeDefined();
  4593. const deps = [...cg.getImpactRadius(find!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4594. expect(deps.some((p) => p.endsWith('routes/mod.rs')), 'database::profiles::find() resolves to the leaf fn').toBe(true);
  4595. });
  4596. it('Rocket `routes![…]` / `catchers![…]` macros link the mount to the handler fns', async () => {
  4597. // Tree-sitter leaves the macro body as a raw token tree, so the handler
  4598. // paths inside `routes![a::b::handler, …]` are invisible to the call walker
  4599. // and the handlers — mounted by Rocket at runtime, not called in-repo — look
  4600. // like they have no caller. The route-macro extractor reconstructs each path
  4601. // and emits a reference, which the Rust path resolver links to the handler.
  4602. const routes = path.join(tempDir, 'src/routes');
  4603. fs.mkdirSync(routes, { recursive: true });
  4604. fs.writeFileSync(path.join(tempDir, 'src/lib.rs'),
  4605. `mod routes;\nfn not_found() {}\npub fn rocket() {\n` +
  4606. ` rocket::build()\n` +
  4607. ` .mount("/api", routes![routes::users::post_users, routes::users::get_user])\n` +
  4608. ` .register("/", catchers![not_found]);\n}\n`);
  4609. fs.writeFileSync(path.join(routes, 'mod.rs'), `pub mod users;\n`);
  4610. fs.writeFileSync(path.join(routes, 'users.rs'), `pub fn post_users() {}\npub fn get_user() {}\n`);
  4611. cg = CodeGraph.initSync(tempDir);
  4612. await cg.indexAll();
  4613. cg.resolveReferences();
  4614. const handlers = cg.getNodesByKind('function').filter((n) => n.filePath.endsWith('routes/users.rs'));
  4615. expect(handlers.length, 'both handler fns indexed').toBe(2);
  4616. for (const h of handlers) {
  4617. const deps = [...cg.getImpactRadius(h.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4618. expect(deps.some((p) => p.endsWith('lib.rs')), `routes![] links ${h.name} to its mount in lib.rs`).toBe(true);
  4619. }
  4620. });
  4621. });
  4622. describe('SvelteKit load → page synthesizer', () => {
  4623. let tempDir: string;
  4624. let cg: CodeGraph;
  4625. beforeEach(() => {
  4626. tempDir = createTempDir();
  4627. });
  4628. afterEach(() => {
  4629. if (cg) cg.close();
  4630. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4631. });
  4632. it('links a +page.svelte to its OWN directory\'s +page.server.js load, not another route\'s', async () => {
  4633. // SvelteKit wires +page.server.js's `load` to +page.svelte's `data` BY FILE
  4634. // PATH — there is no static import — so editing a loader showed no impact on
  4635. // the page it feeds. The synthesizer links each page component to the `load`
  4636. // in its OWN directory (path-deterministic, so it never crosses routes).
  4637. const login = path.join(tempDir, 'src/routes/login');
  4638. const register = path.join(tempDir, 'src/routes/register');
  4639. fs.mkdirSync(login, { recursive: true });
  4640. fs.mkdirSync(register, { recursive: true });
  4641. fs.writeFileSync(path.join(login, '+page.svelte'), `<script>export let data;</script>\n<h1>Login {data.x}</h1>\n`);
  4642. fs.writeFileSync(path.join(login, '+page.server.js'), `export function load() { return { x: 1 }; }\n`);
  4643. fs.writeFileSync(path.join(register, '+page.svelte'), `<script>export let data;</script>\n<h1>Register</h1>\n`);
  4644. fs.writeFileSync(path.join(register, '+page.server.js'), `export function load() { return { y: 2 }; }\n`);
  4645. cg = CodeGraph.initSync(tempDir);
  4646. await cg.indexAll();
  4647. cg.resolveReferences();
  4648. const loginLoad = cg
  4649. .getNodesByKind('function')
  4650. .find((n) => n.name === 'load' && n.filePath.endsWith('login/+page.server.js'));
  4651. expect(loginLoad, 'login load fn').toBeDefined();
  4652. const impacted = [...cg.getImpactRadius(loginLoad!.id, 3).nodes.values()].map((n) => n.filePath ?? '');
  4653. // editing login's load surfaces login's page (the framework-wired data flow)…
  4654. expect(impacted.some((p) => p.endsWith('login/+page.svelte')), 'load links to its own page').toBe(true);
  4655. // …but never register's page (same-directory only).
  4656. expect(impacted.some((p) => p.endsWith('register/+page.svelte')), 'does not cross routes').toBe(false);
  4657. });
  4658. });
  4659. describe('Nuxt nested auto-imported component resolution', () => {
  4660. let tempDir: string;
  4661. let cg: CodeGraph;
  4662. beforeEach(() => {
  4663. tempDir = createTempDir();
  4664. });
  4665. afterEach(() => {
  4666. if (cg) cg.close();
  4667. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4668. });
  4669. it('links a `<MediaCard/>` usage to components/media/Card.vue (Nuxt dir-prefixed auto-import)', async () => {
  4670. // Nuxt auto-imports a nested component by a DIRECTORY-PREFIXED name —
  4671. // components/media/Card.vue is used as <MediaCard/>, not <Card/> — but the
  4672. // component node is named by basename (`Card`), so the PascalCase usage
  4673. // didn't resolve and the nested component looked unused.
  4674. const media = path.join(tempDir, 'components/media');
  4675. fs.mkdirSync(media, { recursive: true });
  4676. fs.writeFileSync(path.join(media, 'Card.vue'), `<template><div>card</div></template>\n<script setup>defineProps(['item'])</script>\n`);
  4677. fs.writeFileSync(
  4678. path.join(tempDir, 'components/Grid.vue'),
  4679. `<template>\n <div><MediaCard :item="i" /></div>\n</template>\n<script setup>const i = {}</script>\n`
  4680. );
  4681. cg = CodeGraph.initSync(tempDir);
  4682. await cg.indexAll();
  4683. cg.resolveReferences();
  4684. const card = cg.getNodesByKind('component').find((n) => n.filePath.endsWith('media/Card.vue'));
  4685. expect(card, 'media/Card.vue component').toBeDefined();
  4686. const deps = [...cg.getImpactRadius(card!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4687. expect(deps.some((p) => p.endsWith('components/Grid.vue')), '<MediaCard> links Grid to media/Card.vue').toBe(true);
  4688. });
  4689. });
  4690. describe('Swift property-wrapper attribute type references', () => {
  4691. let tempDir: string;
  4692. let cg: CodeGraph;
  4693. beforeEach(() => {
  4694. tempDir = createTempDir();
  4695. });
  4696. afterEach(() => {
  4697. if (cg) cg.close();
  4698. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4699. });
  4700. it('a Fluent `@Siblings(through: Pivot.self)` links the model to the pivot type', async () => {
  4701. // A many-to-many pivot/join model is referenced ONLY through the relationship
  4702. // property wrapper's metatype argument (`Pivot.self`), never by a controller
  4703. // query. The wrapper type was captured but the argument expression wasn't
  4704. // walked, so the pivot model looked like nothing depended on it.
  4705. fs.writeFileSync(path.join(tempDir, 'Pivot.swift'),
  4706. `import Fluent\nfinal class AcronymCategoryPivot: Model {\n static let schema = "acronym-category"\n}\n`);
  4707. fs.writeFileSync(path.join(tempDir, 'Acronym.swift'),
  4708. `import Fluent\nfinal class Acronym: Model {\n` +
  4709. ` @Siblings(through: AcronymCategoryPivot.self, from: \\.$acronym, to: \\.$category)\n` +
  4710. ` var categories: [Category]\n}\n`);
  4711. cg = CodeGraph.initSync(tempDir);
  4712. await cg.indexAll();
  4713. cg.resolveReferences();
  4714. const pivot = cg.getNodesByKind('class').find((n) => n.name === 'AcronymCategoryPivot');
  4715. expect(pivot, 'pivot model class').toBeDefined();
  4716. const deps = [...cg.getImpactRadius(pivot!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4717. expect(deps.some((p) => p.endsWith('Acronym.swift')), '@Siblings metatype arg links Acronym to the pivot').toBe(true);
  4718. });
  4719. });
  4720. describe('Objective-C messages, class receivers, and #import', () => {
  4721. let tempDir: string;
  4722. let cg: CodeGraph;
  4723. beforeEach(() => {
  4724. tempDir = createTempDir();
  4725. });
  4726. afterEach(() => {
  4727. if (cg) cg.close();
  4728. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  4729. });
  4730. it('resolves single-arg selectors, class-message receivers, and #import headers', async () => {
  4731. fs.writeFileSync(
  4732. path.join(tempDir, 'SDImageCache.h'),
  4733. `#import <Foundation/Foundation.h>
  4734. @interface SDImageCache : NSObject
  4735. + (instancetype)sharedCache;
  4736. + (void)storeImage:(NSString *)key;
  4737. @end
  4738. `
  4739. );
  4740. fs.writeFileSync(
  4741. path.join(tempDir, 'SDImageCache.m'),
  4742. `#import "SDImageCache.h"
  4743. @implementation SDImageCache
  4744. + (instancetype)sharedCache { return nil; }
  4745. + (void)storeImage:(NSString *)key { }
  4746. @end
  4747. `
  4748. );
  4749. fs.writeFileSync(
  4750. path.join(tempDir, 'SDManager.m'),
  4751. `#import "SDImageCache.h"
  4752. @interface SDManager : NSObject
  4753. @end
  4754. @implementation SDManager
  4755. - (void)run {
  4756. [SDImageCache sharedCache];
  4757. [SDImageCache storeImage:@"k"];
  4758. }
  4759. @end
  4760. `
  4761. );
  4762. cg = CodeGraph.initSync(tempDir);
  4763. await cg.indexAll();
  4764. cg.resolveReferences();
  4765. // 1. The single-argument selector `[SDImageCache storeImage:@"k"]` resolves
  4766. // to the `storeImage:` method — named WITH its colon both at the call site
  4767. // and the definition (before the fix the call site dropped the colon).
  4768. const storeImage = cg.getNodesByKind('method').find((n) => n.name === 'storeImage:');
  4769. expect(storeImage, 'storeImage: method').toBeDefined();
  4770. const storeCallers = [...cg.getImpactRadius(storeImage!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4771. expect(storeCallers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4772. // 2. The class-message receiver `[SDImageCache sharedCache]` references the
  4773. // SDImageCache class (whose @interface lives in the header).
  4774. const cache = cg.getNodesByKind('class').find((n) => n.name === 'SDImageCache');
  4775. expect(cache, 'SDImageCache class').toBeDefined();
  4776. const classDeps = [...cg.getImpactRadius(cache!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4777. expect(classDeps.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4778. // 3. `#import "SDImageCache.h"` resolves to the header FILE — editing it
  4779. // surfaces both importers.
  4780. const header = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('SDImageCache.h'));
  4781. expect(header, 'SDImageCache.h indexed').toBeDefined();
  4782. const importers = [...cg.getImpactRadius(header!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  4783. expect(importers.some((p) => p.endsWith('SDManager.m'))).toBe(true);
  4784. });
  4785. });
  4786. describe('Full Indexing', () => {
  4787. let tempDir: string;
  4788. beforeEach(() => {
  4789. tempDir = createTempDir();
  4790. });
  4791. afterEach(() => {
  4792. cleanupTempDir(tempDir);
  4793. });
  4794. it('should index a TypeScript file', async () => {
  4795. // Create test file
  4796. const srcDir = path.join(tempDir, 'src');
  4797. fs.mkdirSync(srcDir);
  4798. fs.writeFileSync(
  4799. path.join(srcDir, 'utils.ts'),
  4800. `
  4801. export function add(a: number, b: number): number {
  4802. return a + b;
  4803. }
  4804. export function multiply(a: number, b: number): number {
  4805. return a * b;
  4806. }
  4807. `
  4808. );
  4809. // Initialize and index
  4810. const cg = CodeGraph.initSync(tempDir);
  4811. const result = await cg.indexAll();
  4812. expect(result.success).toBe(true);
  4813. expect(result.filesIndexed).toBe(1);
  4814. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  4815. // Check nodes were stored
  4816. const nodes = cg.getNodesInFile('src/utils.ts');
  4817. expect(nodes.length).toBeGreaterThanOrEqual(2);
  4818. const addFunc = nodes.find((n) => n.name === 'add');
  4819. expect(addFunc).toBeDefined();
  4820. expect(addFunc?.kind).toBe('function');
  4821. cg.close();
  4822. });
  4823. it('should index multiple files', async () => {
  4824. // Create test files
  4825. const srcDir = path.join(tempDir, 'src');
  4826. fs.mkdirSync(srcDir);
  4827. fs.writeFileSync(
  4828. path.join(srcDir, 'math.ts'),
  4829. `export function add(a: number, b: number) { return a + b; }`
  4830. );
  4831. fs.writeFileSync(
  4832. path.join(srcDir, 'string.ts'),
  4833. `export function capitalize(s: string) { return s.toUpperCase(); }`
  4834. );
  4835. // Initialize and index
  4836. const cg = CodeGraph.initSync(tempDir);
  4837. const result = await cg.indexAll();
  4838. expect(result.success).toBe(true);
  4839. expect(result.filesIndexed).toBe(2);
  4840. const files = cg.getFiles();
  4841. expect(files.length).toBe(2);
  4842. cg.close();
  4843. });
  4844. it('should track file hashes for incremental updates', async () => {
  4845. // Create initial file
  4846. const srcDir = path.join(tempDir, 'src');
  4847. fs.mkdirSync(srcDir);
  4848. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  4849. // Initialize and index
  4850. const cg = CodeGraph.initSync(tempDir);
  4851. await cg.indexAll();
  4852. // Check file is tracked
  4853. const file = cg.getFile('src/main.ts');
  4854. expect(file).toBeDefined();
  4855. expect(file?.contentHash).toBeDefined();
  4856. // Modify file
  4857. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  4858. // Check for changes
  4859. const changes = cg.getChangedFiles();
  4860. expect(changes.modified).toContain('src/main.ts');
  4861. cg.close();
  4862. });
  4863. it('should sync and detect changes', async () => {
  4864. // Create initial file
  4865. const srcDir = path.join(tempDir, 'src');
  4866. fs.mkdirSync(srcDir);
  4867. fs.writeFileSync(
  4868. path.join(srcDir, 'main.ts'),
  4869. `export function original() { return 1; }`
  4870. );
  4871. // Initialize and index
  4872. const cg = CodeGraph.initSync(tempDir);
  4873. await cg.indexAll();
  4874. const initialNodes = cg.getNodesInFile('src/main.ts');
  4875. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  4876. // Modify file
  4877. fs.writeFileSync(
  4878. path.join(srcDir, 'main.ts'),
  4879. `export function updated() { return 2; }`
  4880. );
  4881. // Sync
  4882. const syncResult = await cg.sync();
  4883. expect(syncResult.filesModified).toBe(1);
  4884. // Check nodes were updated
  4885. const updatedNodes = cg.getNodesInFile('src/main.ts');
  4886. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  4887. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  4888. cg.close();
  4889. });
  4890. it('should count file-level tracked YAML files as indexed', async () => {
  4891. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4892. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  4893. const cg = CodeGraph.initSync(tempDir);
  4894. const result = await cg.indexAll();
  4895. expect(result.success).toBe(true);
  4896. expect(result.filesIndexed).toBe(2);
  4897. expect(result.filesSkipped).toBe(0);
  4898. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  4899. cg.close();
  4900. });
  4901. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  4902. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4903. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4904. const cg = CodeGraph.initSync(tempDir);
  4905. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  4906. expect(result.success).toBe(true);
  4907. expect(result.filesIndexed).toBe(2);
  4908. expect(result.filesSkipped).toBe(0);
  4909. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4910. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  4911. cg.close();
  4912. });
  4913. it('should count file-level tracked .properties files as indexed', async () => {
  4914. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4915. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  4916. const cg = CodeGraph.initSync(tempDir);
  4917. const result = await cg.indexAll();
  4918. expect(result.success).toBe(true);
  4919. expect(result.filesIndexed).toBe(2);
  4920. expect(result.filesSkipped).toBe(0);
  4921. cg.close();
  4922. });
  4923. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  4924. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  4925. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  4926. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  4927. const cg = CodeGraph.initSync(tempDir);
  4928. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  4929. expect(result.success).toBe(true);
  4930. expect(result.filesIndexed).toBe(3);
  4931. expect(result.filesSkipped).toBe(0);
  4932. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  4933. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  4934. cg.close();
  4935. });
  4936. });
  4937. describe('Path Normalization', () => {
  4938. it('should convert backslashes to forward slashes', () => {
  4939. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  4940. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  4941. });
  4942. it('should leave forward-slash paths unchanged', () => {
  4943. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  4944. });
  4945. it('should handle empty string', () => {
  4946. expect(normalizePath('')).toBe('');
  4947. });
  4948. });
  4949. describe('Directory Exclusion', () => {
  4950. let tempDir: string;
  4951. beforeEach(() => {
  4952. tempDir = createTempDir();
  4953. });
  4954. afterEach(() => {
  4955. cleanupTempDir(tempDir);
  4956. });
  4957. it('should exclude directories listed in .gitignore', () => {
  4958. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  4959. const srcDir = path.join(tempDir, 'src');
  4960. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  4961. fs.mkdirSync(srcDir, { recursive: true });
  4962. fs.mkdirSync(nmDir, { recursive: true });
  4963. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4964. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4965. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4966. const files = scanDirectory(tempDir);
  4967. expect(files).toContain('src/index.ts');
  4968. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4969. });
  4970. it('should exclude nested node_modules via a root .gitignore', () => {
  4971. // A trailing-slash pattern with no leading slash matches at any depth.
  4972. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  4973. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  4974. fs.mkdirSync(srcDir, { recursive: true });
  4975. fs.mkdirSync(nmDir, { recursive: true });
  4976. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  4977. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  4978. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  4979. const files = scanDirectory(tempDir);
  4980. expect(files).toContain('packages/app/src/index.ts');
  4981. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  4982. });
  4983. it('should apply a nested .gitignore only to its own subtree', () => {
  4984. const appSrc = path.join(tempDir, 'app', 'src');
  4985. fs.mkdirSync(appSrc, { recursive: true });
  4986. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  4987. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  4988. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  4989. // A sibling with the same name outside app/ must NOT be ignored.
  4990. const otherDir = path.join(tempDir, 'other', 'src');
  4991. fs.mkdirSync(otherDir, { recursive: true });
  4992. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  4993. const files = scanDirectory(tempDir);
  4994. expect(files).toContain('app/src/keep.ts');
  4995. expect(files).not.toContain('app/src/skip.ts');
  4996. expect(files).toContain('other/src/skip.ts');
  4997. });
  4998. it('should always skip .git directories', () => {
  4999. const srcDir = path.join(tempDir, 'src');
  5000. const gitDir = path.join(tempDir, '.git', 'objects');
  5001. fs.mkdirSync(srcDir, { recursive: true });
  5002. fs.mkdirSync(gitDir, { recursive: true });
  5003. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  5004. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  5005. const files = scanDirectory(tempDir);
  5006. expect(files).toContain('src/index.ts');
  5007. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  5008. });
  5009. it('should return forward-slash paths on all platforms', () => {
  5010. const srcDir = path.join(tempDir, 'src', 'components');
  5011. fs.mkdirSync(srcDir, { recursive: true });
  5012. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  5013. const files = scanDirectory(tempDir);
  5014. expect(files.length).toBe(1);
  5015. expect(files[0]).toBe('src/components/Button.tsx');
  5016. expect(files[0]).not.toContain('\\');
  5017. });
  5018. });
  5019. describe('Git Submodules', () => {
  5020. let tempDir: string;
  5021. beforeEach(() => {
  5022. tempDir = createTempDir();
  5023. });
  5024. afterEach(() => {
  5025. cleanupTempDir(tempDir);
  5026. });
  5027. it('should index files inside git submodules (issue #147)', async () => {
  5028. const { execFileSync } = await import('child_process');
  5029. const git = (cwd: string, ...args: string[]) =>
  5030. execFileSync('git', args, { cwd, stdio: 'pipe' });
  5031. // Build a separate "library" repo to use as a submodule source.
  5032. const libDir = path.join(tempDir, '_lib');
  5033. fs.mkdirSync(libDir, { recursive: true });
  5034. git(libDir, 'init', '-q');
  5035. git(libDir, 'config', 'user.email', 'test@test.com');
  5036. git(libDir, 'config', 'user.name', 'Test');
  5037. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  5038. git(libDir, 'add', '-A');
  5039. git(libDir, 'commit', '-q', '-m', 'lib init');
  5040. // Build the main repo and add the lib repo as a submodule.
  5041. const mainDir = path.join(tempDir, 'main');
  5042. fs.mkdirSync(mainDir, { recursive: true });
  5043. git(mainDir, 'init', '-q');
  5044. git(mainDir, 'config', 'user.email', 'test@test.com');
  5045. git(mainDir, 'config', 'user.name', 'Test');
  5046. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  5047. git(mainDir, 'add', '-A');
  5048. git(mainDir, 'commit', '-q', '-m', 'app init');
  5049. // protocol.file.allow=always is required to add a local-path submodule on
  5050. // recent git versions (CVE-2022-39253 mitigation).
  5051. execFileSync(
  5052. 'git',
  5053. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  5054. { cwd: mainDir, stdio: 'pipe' }
  5055. );
  5056. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  5057. const files = scanDirectory(mainDir);
  5058. expect(files).toContain('app.ts');
  5059. expect(files).toContain('libs/lib/lib.ts');
  5060. });
  5061. });
  5062. describe('Nested gitlink repos (#1031, #1033)', () => {
  5063. let tempDir: string;
  5064. // Helper: make a self-contained git repo at `dir` with one committed TS file.
  5065. const makeRepo = async (dir: string, base: string) => {
  5066. const { execFileSync } = await import('child_process');
  5067. const git = (...args: string[]) => execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
  5068. fs.mkdirSync(dir, { recursive: true });
  5069. git('init', '-q');
  5070. git('config', 'user.email', 'test@test.com');
  5071. git('config', 'user.name', 'Test');
  5072. fs.writeFileSync(path.join(dir, `${base}.ts`), `export const ${base} = 1;`);
  5073. git('add', '-A');
  5074. git('commit', '-q', '-m', `${base} init`);
  5075. };
  5076. beforeEach(() => {
  5077. tempDir = createTempDir();
  5078. });
  5079. afterEach(() => {
  5080. cleanupTempDir(tempDir);
  5081. });
  5082. // The #1031 case: a nested repo `git add`ed inside the super-repo becomes a
  5083. // gitlink (mode 160000) with NO `.gitmodules`. It is tracked (so it never shows
  5084. // in the untracked `-o` listing) yet not an active submodule (so
  5085. // `--recurse-submodules` won't expand it) — it used to fall through both passes
  5086. // and only the super-repo's own files got indexed.
  5087. it('indexes a bare gitlink (git add\'ed embedded repo, no .gitmodules), recursively', async () => {
  5088. const { execFileSync } = await import('child_process');
  5089. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  5090. const root = path.join(tempDir, 'root');
  5091. await makeRepo(root, 'app');
  5092. // An embedded clone, itself holding a further nested clone (untracked inside it).
  5093. await makeRepo(path.join(root, 'embedded'), 'inner');
  5094. await makeRepo(path.join(root, 'embedded', 'deep'), 'deep');
  5095. // `git add embedded` records it as a 160000 gitlink (no fetch, no .gitmodules).
  5096. git(root, 'add', 'embedded');
  5097. git(root, 'commit', '-q', '-m', 'add embedded as gitlink');
  5098. expect(fs.existsSync(path.join(root, '.gitmodules'))).toBe(false);
  5099. const files = scanDirectory(root);
  5100. expect(files).toContain('app.ts');
  5101. expect(files).toContain('embedded/inner.ts'); // the gitlink's own source
  5102. expect(files).toContain('embedded/deep/deep.ts'); // recursion continues into its nested repo
  5103. });
  5104. // The -c → -s switch must not regress active submodules (#147): a repo can hold
  5105. // BOTH an active submodule (expanded by --recurse-submodules) and a bare gitlink
  5106. // (handled by the new pass), and the mixed 160000/100644 modes must parse right.
  5107. it('indexes a gitlink alongside an active submodule', async () => {
  5108. const { execFileSync } = await import('child_process');
  5109. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  5110. const lib = path.join(tempDir, '_lib');
  5111. await makeRepo(lib, 'lib');
  5112. const root = path.join(tempDir, 'root');
  5113. await makeRepo(root, 'app');
  5114. // A proper, active submodule.
  5115. execFileSync('git', ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', lib, 'libs/lib'], { cwd: root, stdio: 'pipe' });
  5116. git(root, 'commit', '-q', '-m', 'add submodule');
  5117. // A bare gitlink in the same repo (under a non-ignored dir name).
  5118. await makeRepo(path.join(root, 'external', 'tool'), 'tool');
  5119. git(root, 'add', 'external/tool');
  5120. git(root, 'commit', '-q', '-m', 'add gitlink');
  5121. const files = scanDirectory(root);
  5122. expect(files).toContain('app.ts');
  5123. expect(files).toContain('libs/lib/lib.ts'); // active submodule still expands (#147)
  5124. expect(files).toContain('external/tool/tool.ts'); // bare gitlink now indexed
  5125. });
  5126. // A gitlink under a built-in default-ignored directory (vendor/, node_modules/,
  5127. // …) stays excluded — a committed dependency doesn't become project code just
  5128. // because it's a nested repo. Mirrors how the untracked-embedded path treats
  5129. // the same dirs (#407), so the two passes agree.
  5130. it('does not index a gitlink under a default-ignored directory (e.g. vendor/)', async () => {
  5131. const { execFileSync } = await import('child_process');
  5132. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  5133. const root = path.join(tempDir, 'root');
  5134. await makeRepo(root, 'app');
  5135. await makeRepo(path.join(root, 'vendor', 'pkg'), 'dep');
  5136. git(root, 'add', 'vendor/pkg');
  5137. git(root, 'commit', '-q', '-m', 'add vendored gitlink');
  5138. const files = scanDirectory(root);
  5139. expect(files).toContain('app.ts');
  5140. expect(files).not.toContain('vendor/pkg/dep.ts');
  5141. });
  5142. // A gitlink with NO working tree on disk (the common "cloned without
  5143. // --recurse-submodules" state) has nothing to index — we must leave it alone,
  5144. // not fabricate entries, and must not break the rest of the scan.
  5145. it('leaves an uninitialized submodule (no checkout on disk) alone', async () => {
  5146. const { execFileSync } = await import('child_process');
  5147. const lib = path.join(tempDir, '_lib');
  5148. await makeRepo(lib, 'lib');
  5149. const sup = path.join(tempDir, 'super');
  5150. await makeRepo(sup, 'app');
  5151. execFileSync('git', ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', lib, 'libs/lib'], { cwd: sup, stdio: 'pipe' });
  5152. execFileSync('git', ['commit', '-q', '-m', 'add submodule'], { cwd: sup, stdio: 'pipe' });
  5153. // Clone the super-repo WITHOUT --recurse-submodules → libs/lib is an empty
  5154. // gitlink dir (mode 160000, no `.git` inside, no files).
  5155. const clone = path.join(tempDir, 'clone');
  5156. execFileSync('git', ['clone', '-q', sup, clone], { stdio: 'pipe' });
  5157. expect(fs.readdirSync(path.join(clone, 'libs', 'lib'))).toHaveLength(0);
  5158. const files = scanDirectory(clone);
  5159. expect(files).toContain('app.ts');
  5160. expect(files).not.toContain('libs/lib/lib.ts'); // not on disk → correctly absent
  5161. });
  5162. // #1065: a gitlink under a path the super-repo's OWN `.gitignore` covers is the
  5163. // tracked-gitlink twin of the untracked-ignored embedded repo (#514, #970). The
  5164. // gitlink-discovery pass must honor that `.gitignore` the same way — otherwise a
  5165. // gitignored reference/benchmark corpus full of `git add`ed clones gets pulled
  5166. // into the index (the 138k-file blow-up the reporter hit). Respect it by default;
  5167. // re-include only via `codegraph.json` `includeIgnored`.
  5168. it('does not index a gitlink under a gitignored directory by default (#1065)', async () => {
  5169. const { execFileSync } = await import('child_process');
  5170. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  5171. const root = path.join(tempDir, 'root');
  5172. await makeRepo(root, 'app');
  5173. // An embedded clone under a path the super-repo gitignores (a benchmark corpus).
  5174. await makeRepo(path.join(root, 'benchmark', 'repos', 'ref'), 'ref');
  5175. git(root, 'add', 'benchmark/repos/ref'); // tracked as a 160000 gitlink
  5176. fs.writeFileSync(path.join(root, '.gitignore'), 'benchmark/repos/\n');
  5177. git(root, 'add', '.gitignore');
  5178. git(root, 'commit', '-q', '-m', 'add gitignored gitlink + ignore rule');
  5179. const files = scanDirectory(root);
  5180. expect(files).toContain('app.ts');
  5181. expect(files).not.toContain('benchmark/repos/ref/ref.ts'); // gitignored → excluded
  5182. // The watcher path agrees: the ignored root is never discovered, and the dir is
  5183. // pruned (the reporter's exact clue — `ignores('benchmark/repos/')` was false).
  5184. expect(discoverEmbeddedRepoRoots(root)).toEqual([]);
  5185. expect(buildScopeIgnore(root).ignores('benchmark/repos/')).toBe(true);
  5186. expect(buildScopeIgnore(root).ignores('benchmark/repos/ref/ref.ts')).toBe(true);
  5187. });
  5188. it('re-includes a gitignored gitlink when codegraph.json includeIgnored opts in (#1065)', async () => {
  5189. const { execFileSync } = await import('child_process');
  5190. const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
  5191. const root = path.join(tempDir, 'root');
  5192. await makeRepo(root, 'app');
  5193. await makeRepo(path.join(root, 'benchmark', 'repos', 'ref'), 'ref');
  5194. git(root, 'add', 'benchmark/repos/ref');
  5195. fs.writeFileSync(path.join(root, '.gitignore'), 'benchmark/repos/\n');
  5196. fs.writeFileSync(path.join(root, 'codegraph.json'), JSON.stringify({ includeIgnored: ['benchmark/repos/'] }));
  5197. git(root, 'add', '.gitignore', 'codegraph.json');
  5198. git(root, 'commit', '-q', '-m', 'opt the gitignored gitlink back in');
  5199. const files = scanDirectory(root);
  5200. expect(files).toContain('app.ts');
  5201. expect(files).toContain('benchmark/repos/ref/ref.ts'); // opted in → indexed
  5202. expect(discoverEmbeddedRepoRoots(root)).toContain('benchmark/repos/ref/');
  5203. });
  5204. });
  5205. describe('Nested non-submodule git repos', () => {
  5206. let tempDir: string;
  5207. beforeEach(() => {
  5208. tempDir = createTempDir();
  5209. });
  5210. afterEach(() => {
  5211. cleanupTempDir(tempDir);
  5212. });
  5213. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  5214. const { execFileSync } = await import('child_process');
  5215. const git = (cwd: string, ...args: string[]) =>
  5216. execFileSync('git', args, { cwd, stdio: 'pipe' });
  5217. // Top-level workspace is itself a git repo, holding no source directly —
  5218. // the CMake "super-repo" layout from the issue.
  5219. const root = path.join(tempDir, 'root');
  5220. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  5221. git(root, 'init', '-q');
  5222. git(root, 'config', 'user.email', 'test@test.com');
  5223. git(root, 'config', 'user.name', 'Test');
  5224. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  5225. // Two independent clones living inside the workspace (NOT submodules):
  5226. // one with committed source, one with only untracked source.
  5227. const sub1 = path.join(root, 'sub_repo1', 'src');
  5228. fs.mkdirSync(sub1, { recursive: true });
  5229. git(path.join(root, 'sub_repo1'), 'init', '-q');
  5230. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  5231. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  5232. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  5233. git(path.join(root, 'sub_repo1'), 'add', '-A');
  5234. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  5235. const sub2 = path.join(root, 'sub_repo2', 'src');
  5236. fs.mkdirSync(sub2, { recursive: true });
  5237. git(path.join(root, 'sub_repo2'), 'init', '-q');
  5238. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  5239. const files = scanDirectory(root);
  5240. // Both committed and untracked source from the nested repos must be found.
  5241. expect(files).toContain('sub_repo1/src/one.ts');
  5242. expect(files).toContain('sub_repo2/src/two.ts');
  5243. });
  5244. it('should respect each embedded repo\'s own .gitignore', async () => {
  5245. const { execFileSync } = await import('child_process');
  5246. const git = (cwd: string, ...args: string[]) =>
  5247. execFileSync('git', args, { cwd, stdio: 'pipe' });
  5248. const root = path.join(tempDir, 'root');
  5249. fs.mkdirSync(root, { recursive: true });
  5250. git(root, 'init', '-q');
  5251. const sub = path.join(root, 'sub_repo', 'src');
  5252. fs.mkdirSync(sub, { recursive: true });
  5253. git(path.join(root, 'sub_repo'), 'init', '-q');
  5254. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  5255. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  5256. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  5257. const files = scanDirectory(root);
  5258. expect(files).toContain('sub_repo/src/real.ts');
  5259. expect(files).not.toContain('sub_repo/src/generated.ts');
  5260. });
  5261. // A .gitignore the `ignore` library can't compile to a regex must not abort
  5262. // the whole scan — the bad pattern is dropped, valid ones still apply (#682).
  5263. it('does not crash on a .gitignore with an uncompilable pattern (#682)', () => {
  5264. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  5265. fs.mkdirSync(path.join(tempDir, 'build'), { recursive: true });
  5266. fs.writeFileSync(path.join(tempDir, 'src', 'real.ts'), 'export const x = 1;');
  5267. fs.writeFileSync(path.join(tempDir, 'build', 'out.ts'), 'export const y = 2;');
  5268. // `\\[` makes the matcher build an unterminated character class — the throw
  5269. // is lazy (at match time), which is what escaped and killed sync.
  5270. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'build/\n\\\\[\n');
  5271. let files: string[] = [];
  5272. expect(() => {
  5273. files = scanDirectory(tempDir);
  5274. }).not.toThrow();
  5275. expect(files).toContain('src/real.ts');
  5276. // The still-valid `build/` rule is honored; only the bad line was dropped.
  5277. expect(files.some((f) => f.startsWith('build/'))).toBe(false);
  5278. });
  5279. // A .gitignore that isn't valid UTF-8 — e.g. encrypted in place by corporate
  5280. // DLP / endpoint software (UTF-16 header + ciphertext) — is skipped whole,
  5281. // not fed to the matcher as garbage patterns (#682).
  5282. it('does not crash on a non-UTF-8 (DLP-encrypted) .gitignore (#682)', () => {
  5283. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  5284. fs.writeFileSync(path.join(tempDir, 'src', 'real.ts'), 'export const x = 1;');
  5285. const header = Buffer.concat([
  5286. Buffer.from([0x00, 0x00]),
  5287. Buffer.from('[notice][user]', 'utf16le'),
  5288. ]);
  5289. const junk = Buffer.from([0x5b, 0x99, 0xc3, 0x28, 0x5c, 0x5b, 0xff, 0xfd]);
  5290. fs.writeFileSync(path.join(tempDir, '.gitignore'), Buffer.concat([header, junk]));
  5291. let files: string[] = [];
  5292. expect(() => {
  5293. files = scanDirectory(tempDir);
  5294. }).not.toThrow();
  5295. expect(files).toContain('src/real.ts');
  5296. });
  5297. it('buildDefaultIgnore survives a bad .gitignore and still applies valid rules (#682)', () => {
  5298. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'dist/\n\\\\[\n');
  5299. const ig = buildDefaultIgnore(tempDir);
  5300. expect(() => ig.ignores('src/app.ts')).not.toThrow();
  5301. expect(ig.ignores('dist/')).toBe(true); // valid rule survives
  5302. expect(ig.ignores('src/app.ts')).toBe(false);
  5303. });
  5304. });
  5305. // =============================================================================
  5306. // Scala
  5307. // =============================================================================
  5308. describe('Scala Extraction', () => {
  5309. describe('Language detection', () => {
  5310. it('should detect Scala files', () => {
  5311. expect(detectLanguage('Main.scala')).toBe('scala');
  5312. expect(detectLanguage('script.sc')).toBe('scala');
  5313. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  5314. });
  5315. it('should report Scala as supported', () => {
  5316. expect(isLanguageSupported('scala')).toBe(true);
  5317. expect(getSupportedLanguages()).toContain('scala');
  5318. });
  5319. });
  5320. describe('Class extraction', () => {
  5321. it('should extract class definitions', () => {
  5322. const code = `
  5323. class UserService(private val repo: UserRepository) {
  5324. def findUser(id: String): Option[String] = Some(id)
  5325. }
  5326. `;
  5327. const result = extractFromSource('UserService.scala', code);
  5328. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  5329. expect(cls).toBeDefined();
  5330. expect(cls?.language).toBe('scala');
  5331. });
  5332. it('should extract object definitions as class kind', () => {
  5333. const code = `
  5334. object DatabaseConfig {
  5335. val url = "jdbc:postgresql://localhost/mydb"
  5336. }
  5337. `;
  5338. const result = extractFromSource('Config.scala', code);
  5339. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  5340. expect(obj).toBeDefined();
  5341. });
  5342. it('should extract trait definitions as trait kind', () => {
  5343. const code = `
  5344. trait Repository[A] {
  5345. def findById(id: String): Option[A]
  5346. def save(entity: A): Unit
  5347. }
  5348. `;
  5349. const result = extractFromSource('Repository.scala', code);
  5350. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  5351. expect(trait_).toBeDefined();
  5352. });
  5353. });
  5354. describe('Method and function extraction', () => {
  5355. it('should extract method definitions inside a class', () => {
  5356. const code = `
  5357. class Calculator {
  5358. def add(a: Int, b: Int): Int = a + b
  5359. def divide(a: Double, b: Double): Double = a / b
  5360. }
  5361. `;
  5362. const result = extractFromSource('Calculator.scala', code);
  5363. const methods = result.nodes.filter((n) => n.kind === 'method');
  5364. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  5365. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  5366. });
  5367. it('should extract method signatures', () => {
  5368. const code = `
  5369. class Greeter {
  5370. def greet(name: String): String = s"Hello, \${name}!"
  5371. }
  5372. `;
  5373. const result = extractFromSource('Greeter.scala', code);
  5374. const method = result.nodes.find((n) => n.name === 'greet');
  5375. expect(method?.signature).toContain('name: String');
  5376. expect(method?.signature).toContain('String');
  5377. });
  5378. it('should extract top-level function definitions as functions', () => {
  5379. const code = `
  5380. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  5381. def greet(name: String): String = s"Hello, \${name}!"
  5382. `;
  5383. const result = extractFromSource('utils.scala', code);
  5384. const fns = result.nodes.filter((n) => n.kind === 'function');
  5385. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  5386. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  5387. });
  5388. });
  5389. describe('Val and var extraction', () => {
  5390. it('should extract val inside a class as field', () => {
  5391. const code = `
  5392. class Config {
  5393. val timeout: Int = 30
  5394. val host: String = "localhost"
  5395. }
  5396. `;
  5397. const result = extractFromSource('Config.scala', code);
  5398. const fields = result.nodes.filter((n) => n.kind === 'field');
  5399. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  5400. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  5401. });
  5402. it('should extract var inside a class as field', () => {
  5403. const code = `
  5404. class Counter {
  5405. var count: Int = 0
  5406. }
  5407. `;
  5408. const result = extractFromSource('Counter.scala', code);
  5409. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  5410. expect(field).toBeDefined();
  5411. });
  5412. it('should extract top-level val as constant', () => {
  5413. const code = `
  5414. val MaxConnections: Int = 100
  5415. val DefaultTimeout = 30
  5416. `;
  5417. const result = extractFromSource('constants.scala', code);
  5418. const consts = result.nodes.filter((n) => n.kind === 'constant');
  5419. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  5420. });
  5421. it('should extract top-level var as variable', () => {
  5422. const code = `
  5423. var retries: Int = 3
  5424. `;
  5425. const result = extractFromSource('state.scala', code);
  5426. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  5427. expect(v).toBeDefined();
  5428. });
  5429. it('should include type in val/var signature', () => {
  5430. const code = `
  5431. class Service {
  5432. val timeout: Int = 30
  5433. }
  5434. `;
  5435. const result = extractFromSource('Service.scala', code);
  5436. const field = result.nodes.find((n) => n.name === 'timeout');
  5437. expect(field?.signature).toContain('timeout');
  5438. expect(field?.signature).toContain('Int');
  5439. });
  5440. });
  5441. describe('Enum extraction', () => {
  5442. it('should extract enum definitions', () => {
  5443. const code = `
  5444. enum Color:
  5445. case Red
  5446. case Green
  5447. case Blue
  5448. `;
  5449. const result = extractFromSource('Color.scala', code);
  5450. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  5451. expect(enumNode).toBeDefined();
  5452. });
  5453. it('should extract enum cases as enum_member', () => {
  5454. const code = `
  5455. enum Direction:
  5456. case North
  5457. case South
  5458. case East
  5459. case West
  5460. `;
  5461. const result = extractFromSource('Direction.scala', code);
  5462. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  5463. expect(members.find((m) => m.name === 'North')).toBeDefined();
  5464. expect(members.find((m) => m.name === 'South')).toBeDefined();
  5465. expect(members.length).toBeGreaterThanOrEqual(4);
  5466. });
  5467. });
  5468. describe('Type alias extraction', () => {
  5469. it('should extract type aliases', () => {
  5470. const code = `
  5471. type UserId = String
  5472. type UserMap = Map[String, String]
  5473. `;
  5474. const result = extractFromSource('types.scala', code);
  5475. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  5476. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  5477. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  5478. });
  5479. });
  5480. describe('Import extraction', () => {
  5481. it('should extract import declarations', () => {
  5482. const code = `
  5483. import scala.collection.mutable.ListBuffer
  5484. import scala.concurrent.Future
  5485. `;
  5486. const result = extractFromSource('imports.scala', code);
  5487. const imports = result.nodes.filter((n) => n.kind === 'import');
  5488. expect(imports.length).toBeGreaterThanOrEqual(2);
  5489. });
  5490. });
  5491. describe('Visibility modifiers', () => {
  5492. it('should extract private visibility', () => {
  5493. const code = `
  5494. class Service {
  5495. private val secret: String = "abc"
  5496. private def helper(): Unit = {}
  5497. }
  5498. `;
  5499. const result = extractFromSource('Service.scala', code);
  5500. const secretField = result.nodes.find((n) => n.name === 'secret');
  5501. expect(secretField?.visibility).toBe('private');
  5502. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  5503. expect(helperMethod?.visibility).toBe('private');
  5504. });
  5505. it('should extract protected visibility', () => {
  5506. const code = `
  5507. class Base {
  5508. protected def helperMethod(): Unit = {}
  5509. }
  5510. `;
  5511. const result = extractFromSource('Base.scala', code);
  5512. const method = result.nodes.find((n) => n.name === 'helperMethod');
  5513. expect(method?.visibility).toBe('protected');
  5514. });
  5515. it('should default to public visibility', () => {
  5516. const code = `
  5517. class Greeter {
  5518. def hello(): Unit = {}
  5519. }
  5520. `;
  5521. const result = extractFromSource('Greeter.scala', code);
  5522. const method = result.nodes.find((n) => n.name === 'hello');
  5523. expect(method?.visibility).toBe('public');
  5524. });
  5525. });
  5526. describe('Inheritance', () => {
  5527. it('should extract extends relationships', () => {
  5528. const code = `
  5529. class AdminUser extends User {
  5530. def adminAction(): Unit = {}
  5531. }
  5532. `;
  5533. const result = extractFromSource('AdminUser.scala', code);
  5534. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  5535. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  5536. });
  5537. });
  5538. describe('Call extraction', () => {
  5539. it('should extract function call expressions', () => {
  5540. const code = `
  5541. def processData(): Unit = {
  5542. val result = computeResult()
  5543. println(result)
  5544. }
  5545. `;
  5546. const result = extractFromSource('processor.scala', code);
  5547. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  5548. expect(calls.length).toBeGreaterThan(0);
  5549. });
  5550. });
  5551. });
  5552. describe('Vue Extraction', () => {
  5553. it('should detect Vue files', () => {
  5554. expect(detectLanguage('App.vue')).toBe('vue');
  5555. expect(detectLanguage('components/Button.vue')).toBe('vue');
  5556. expect(isLanguageSupported('vue')).toBe(true);
  5557. });
  5558. it('should extract component node from a Vue SFC', () => {
  5559. const code = `<template>
  5560. <div>{{ message }}</div>
  5561. </template>
  5562. <script>
  5563. export default {
  5564. data() {
  5565. return { message: 'Hello' };
  5566. }
  5567. }
  5568. </script>
  5569. `;
  5570. const result = extractFromSource('HelloWorld.vue', code);
  5571. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5572. expect(componentNode).toBeDefined();
  5573. expect(componentNode?.name).toBe('HelloWorld');
  5574. expect(componentNode?.language).toBe('vue');
  5575. expect(componentNode?.isExported).toBe(true);
  5576. });
  5577. it('should extract functions from <script> block', () => {
  5578. const code = `<template>
  5579. <button @click="handleClick">Click</button>
  5580. </template>
  5581. <script>
  5582. function handleClick() {
  5583. console.log('clicked');
  5584. }
  5585. const count = 0;
  5586. </script>
  5587. `;
  5588. const result = extractFromSource('Button.vue', code);
  5589. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5590. expect(componentNode).toBeDefined();
  5591. expect(componentNode?.name).toBe('Button');
  5592. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  5593. expect(funcNode).toBeDefined();
  5594. expect(funcNode?.language).toBe('vue');
  5595. });
  5596. it('should extract from <script setup lang="ts"> block', () => {
  5597. const code = `<template>
  5598. <div>{{ count }}</div>
  5599. </template>
  5600. <script setup lang="ts">
  5601. import { ref } from 'vue';
  5602. const count = ref(0);
  5603. function increment(): void {
  5604. count.value++;
  5605. }
  5606. </script>
  5607. `;
  5608. const result = extractFromSource('Counter.vue', code);
  5609. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5610. expect(componentNode).toBeDefined();
  5611. expect(componentNode?.name).toBe('Counter');
  5612. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  5613. expect(funcNode).toBeDefined();
  5614. expect(funcNode?.language).toBe('vue');
  5615. // All nodes should be marked as vue language
  5616. for (const node of result.nodes) {
  5617. expect(node.language).toBe('vue');
  5618. }
  5619. });
  5620. it('should extract calls from top-level <script setup> initializers', () => {
  5621. const code = `<template>
  5622. <div>{{ token }}</div>
  5623. </template>
  5624. <script setup lang="ts">
  5625. import { getTokenMp } from './api/upload';
  5626. const token = getTokenMp();
  5627. </script>
  5628. `;
  5629. const result = extractFromSource('Issue425Setup.vue', code);
  5630. const call = result.unresolvedReferences.find(
  5631. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  5632. );
  5633. expect(call).toBeDefined();
  5634. });
  5635. it('should extract calls from Vue Options API object methods', () => {
  5636. const code = `<template>
  5637. <button @click="save">Save</button>
  5638. </template>
  5639. <script>
  5640. import { getTokenMp } from './api/upload';
  5641. export default {
  5642. methods: {
  5643. save() {
  5644. return getTokenMp();
  5645. }
  5646. },
  5647. setup() {
  5648. return getTokenMp();
  5649. }
  5650. }
  5651. </script>
  5652. `;
  5653. const result = extractFromSource('Issue425Options.vue', code);
  5654. const calls = result.unresolvedReferences.filter(
  5655. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  5656. );
  5657. expect(calls).toHaveLength(2);
  5658. });
  5659. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  5660. const code = `<template>
  5661. <div class="wrap">
  5662. <UserCard :user="u" />
  5663. <my-button>Click</my-button>
  5664. <Transition><span>x</span></Transition>
  5665. </div>
  5666. </template>
  5667. <script setup lang="ts">
  5668. import UserCard from './UserCard.vue';
  5669. import MyButton from './MyButton.vue';
  5670. </script>
  5671. `;
  5672. const result = extractFromSource('Host.vue', code);
  5673. const refs = result.unresolvedReferences
  5674. .filter((r) => r.referenceKind === 'references')
  5675. .map((r) => r.referenceName);
  5676. expect(refs).toContain('UserCard'); // PascalCase tag
  5677. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  5678. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  5679. expect(refs).not.toContain('Div'); // native HTML element skipped
  5680. expect(refs).not.toContain('Span');
  5681. });
  5682. it('should extract from both <script> and <script setup> blocks', () => {
  5683. const code = `<template>
  5684. <div>{{ msg }}</div>
  5685. </template>
  5686. <script>
  5687. export default {
  5688. name: 'DualScript'
  5689. }
  5690. </script>
  5691. <script setup>
  5692. const msg = 'hello';
  5693. function greet() {
  5694. return msg;
  5695. }
  5696. </script>
  5697. `;
  5698. const result = extractFromSource('DualScript.vue', code);
  5699. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5700. expect(componentNode).toBeDefined();
  5701. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  5702. expect(greetFunc).toBeDefined();
  5703. });
  5704. it('should create component node for template-only Vue file', () => {
  5705. const code = `<template>
  5706. <div>Static content</div>
  5707. </template>
  5708. `;
  5709. const result = extractFromSource('Static.vue', code);
  5710. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5711. expect(componentNode).toBeDefined();
  5712. expect(componentNode?.name).toBe('Static');
  5713. expect(componentNode?.language).toBe('vue');
  5714. // Only the component node should exist (no script nodes)
  5715. expect(result.nodes.length).toBe(1);
  5716. });
  5717. it('should create containment edges from component to script nodes', () => {
  5718. const code = `<template>
  5719. <div>{{ value }}</div>
  5720. </template>
  5721. <script setup lang="ts">
  5722. const value = 42;
  5723. </script>
  5724. `;
  5725. const result = extractFromSource('Contained.vue', code);
  5726. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5727. expect(componentNode).toBeDefined();
  5728. // Should have containment edges from component to child nodes
  5729. const containEdges = result.edges.filter(
  5730. (e) => e.source === componentNode!.id && e.kind === 'contains'
  5731. );
  5732. expect(containEdges.length).toBeGreaterThan(0);
  5733. });
  5734. });
  5735. describe('Astro Extraction', () => {
  5736. it('should detect Astro files', () => {
  5737. expect(detectLanguage('src/pages/index.astro')).toBe('astro');
  5738. expect(detectLanguage('Layout.astro')).toBe('astro');
  5739. expect(isLanguageSupported('astro')).toBe(true);
  5740. });
  5741. it('should extract component node from an .astro file', () => {
  5742. const code = `---
  5743. const title = 'Hello';
  5744. ---
  5745. <h1>{title}</h1>
  5746. `;
  5747. const result = extractFromSource('Card.astro', code);
  5748. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5749. expect(componentNode).toBeDefined();
  5750. expect(componentNode?.name).toBe('Card');
  5751. expect(componentNode?.language).toBe('astro');
  5752. expect(componentNode?.isExported).toBe(true);
  5753. });
  5754. it('should extract frontmatter symbols with correct line numbers (#768)', () => {
  5755. const code = `---
  5756. import { formatDate } from '../utils/format';
  5757. function getIconNode(name: string): string {
  5758. return name;
  5759. }
  5760. const { title } = Astro.props;
  5761. ---
  5762. <span>{title}</span>
  5763. `;
  5764. const result = extractFromSource('navs.astro', code);
  5765. // The #768 repro: a function defined in frontmatter must be found
  5766. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'getIconNode');
  5767. expect(fn).toBeDefined();
  5768. expect(fn?.language).toBe('astro');
  5769. expect(fn?.startLine).toBe(4);
  5770. const imp = result.nodes.find((n) => n.kind === 'import');
  5771. expect(imp).toBeDefined();
  5772. expect(imp?.startLine).toBe(2);
  5773. });
  5774. it('should extract exported getStaticPaths from frontmatter', () => {
  5775. const code = `---
  5776. export async function getStaticPaths() {
  5777. return [];
  5778. }
  5779. const { slug } = Astro.params;
  5780. ---
  5781. <p>{slug}</p>
  5782. `;
  5783. const result = extractFromSource('[slug].astro', code);
  5784. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'getStaticPaths');
  5785. expect(fn).toBeDefined();
  5786. expect(fn?.isExported).toBe(true);
  5787. });
  5788. it('should extract calls from template expressions', () => {
  5789. const code = `---
  5790. import { formatDate } from '../utils/format';
  5791. const date = new Date();
  5792. ---
  5793. <time>{formatDate(date)}</time>
  5794. `;
  5795. const result = extractFromSource('Stamp.astro', code);
  5796. const call = result.unresolvedReferences.find(
  5797. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'formatDate' && ref.line === 5
  5798. );
  5799. expect(call).toBeDefined();
  5800. });
  5801. it('should extract calls from a multiline expression opening line', () => {
  5802. const code = `---
  5803. const posts = [];
  5804. ---
  5805. <ul>
  5806. {posts.map((post) => (
  5807. <li>{render(post)}</li>
  5808. ))}
  5809. </ul>
  5810. `;
  5811. const result = extractFromSource('List.astro', code);
  5812. const mapCall = result.unresolvedReferences.find(
  5813. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'posts.map'
  5814. );
  5815. expect(mapCall).toBeDefined();
  5816. const innerCall = result.unresolvedReferences.find(
  5817. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'render'
  5818. );
  5819. expect(innerCall).toBeDefined();
  5820. });
  5821. it('should extract PascalCase component usages from the template', () => {
  5822. const code = `---
  5823. import Layout from '../layouts/Layout.astro';
  5824. import PostCard from '../components/PostCard.astro';
  5825. ---
  5826. <Layout title="Home">
  5827. <PostCard />
  5828. <Fragment slot="head" />
  5829. <div class="plain-html" />
  5830. </Layout>
  5831. `;
  5832. const result = extractFromSource('index.astro', code);
  5833. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  5834. const names = refs.map((r) => r.referenceName);
  5835. expect(names).toContain('Layout');
  5836. expect(names).toContain('PostCard');
  5837. // Astro built-ins and lowercase HTML are not component references
  5838. expect(names).not.toContain('Fragment');
  5839. expect(names).not.toContain('div');
  5840. });
  5841. it('should not extract template patterns from frontmatter, script, or style content', () => {
  5842. const code = `---
  5843. // <FakeComponent /> inside frontmatter comment
  5844. const x = { y: maybeCall(1) };
  5845. ---
  5846. <div>real</div>
  5847. <script>
  5848. const z = { w: scriptCall(2) };
  5849. </script>
  5850. <style>
  5851. .a { color: red; }
  5852. </style>
  5853. `;
  5854. const result = extractFromSource('Guard.astro', code);
  5855. const templateRefs = result.unresolvedReferences.filter(
  5856. (r) => r.referenceKind === 'references' && r.referenceName === 'FakeComponent'
  5857. );
  5858. expect(templateRefs).toHaveLength(0);
  5859. // maybeCall/scriptCall come from the delegated TS extraction (once),
  5860. // not double-counted by the template scanner
  5861. const maybeCalls = result.unresolvedReferences.filter(
  5862. (r) => r.referenceName === 'maybeCall' && r.referenceKind === 'calls'
  5863. );
  5864. expect(maybeCalls.length).toBeLessThanOrEqual(1);
  5865. });
  5866. it('should extract <script> block symbols with correct line numbers', () => {
  5867. const code = `---
  5868. const a = 1;
  5869. ---
  5870. <div>hi</div>
  5871. <script>
  5872. function trackView(page: string) {
  5873. console.log(page);
  5874. }
  5875. </script>
  5876. `;
  5877. const result = extractFromSource('Tracker.astro', code);
  5878. const fn = result.nodes.find((n) => n.kind === 'function' && n.name === 'trackView');
  5879. expect(fn).toBeDefined();
  5880. expect(fn?.startLine).toBe(6);
  5881. expect(fn?.language).toBe('astro');
  5882. });
  5883. it('should create component node for a frontmatter-less template-only file', () => {
  5884. const code = `<div>Static content</div>
  5885. `;
  5886. const result = extractFromSource('Static.astro', code);
  5887. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5888. expect(componentNode).toBeDefined();
  5889. expect(componentNode?.name).toBe('Static');
  5890. expect(componentNode?.language).toBe('astro');
  5891. });
  5892. it('should treat an unclosed frontmatter fence as no frontmatter', () => {
  5893. const code = `---
  5894. const broken = true;
  5895. <div>never closed</div>
  5896. `;
  5897. const result = extractFromSource('Broken.astro', code);
  5898. // No TS delegation happened (the fence never closes), but the component
  5899. // node still exists and nothing throws.
  5900. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5901. expect(componentNode).toBeDefined();
  5902. expect(result.nodes.find((n) => n.name === 'broken')).toBeUndefined();
  5903. });
  5904. it('should create containment edges from component to frontmatter nodes', () => {
  5905. const code = `---
  5906. const value = 42;
  5907. ---
  5908. <div>{value}</div>
  5909. `;
  5910. const result = extractFromSource('Contained.astro', code);
  5911. const componentNode = result.nodes.find((n) => n.kind === 'component');
  5912. expect(componentNode).toBeDefined();
  5913. const containEdges = result.edges.filter(
  5914. (e) => e.source === componentNode!.id && e.kind === 'contains'
  5915. );
  5916. expect(containEdges.length).toBeGreaterThan(0);
  5917. });
  5918. });
  5919. describe('Instantiates + Decorates edge extraction', () => {
  5920. it('emits an instantiates ref for `new Foo()`', () => {
  5921. const code = `
  5922. class Foo {}
  5923. function bootstrap() { return new Foo(); }
  5924. `;
  5925. const result = extractFromSource('app.ts', code);
  5926. const ref = result.unresolvedReferences.find(
  5927. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  5928. );
  5929. expect(ref).toBeDefined();
  5930. });
  5931. it('strips type-argument suffix from generic constructors', () => {
  5932. const code = `
  5933. class Container<T> { constructor(_: T) {} }
  5934. function go() { return new Container<string>('x'); }
  5935. `;
  5936. const result = extractFromSource('app.ts', code);
  5937. const ref = result.unresolvedReferences.find(
  5938. (r) => r.referenceKind === 'instantiates'
  5939. );
  5940. expect(ref).toBeDefined();
  5941. // Container<string> must be normalised to "Container" — otherwise
  5942. // resolution can never match the class node.
  5943. expect(ref!.referenceName).toBe('Container');
  5944. });
  5945. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  5946. const code = `
  5947. const ns = { Foo: class {} };
  5948. function go() { return new ns.Foo(); }
  5949. `;
  5950. const result = extractFromSource('app.ts', code);
  5951. const ref = result.unresolvedReferences.find(
  5952. (r) => r.referenceKind === 'instantiates'
  5953. );
  5954. // We can't always resolve which Foo, but the name should be the
  5955. // simple identifier so name-matching has a chance.
  5956. expect(ref?.referenceName).toBe('Foo');
  5957. });
  5958. it('emits a decorates ref for `@Foo class X {}`', () => {
  5959. const code = `
  5960. function Foo(_arg: string) { return (cls: any) => cls; }
  5961. @Foo('x')
  5962. class X {}
  5963. `;
  5964. const result = extractFromSource('app.ts', code);
  5965. const decorClass = result.unresolvedReferences.find(
  5966. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  5967. );
  5968. expect(decorClass).toBeDefined();
  5969. });
  5970. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  5971. // Regression: the sibling-walk must stop at the first non-
  5972. // decorator separator. `@A class Foo {} @B class Bar {}` must
  5973. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  5974. // `decorates(Bar, A)`.
  5975. const code = `
  5976. function A(cls: any) { return cls; }
  5977. function B(cls: any) { return cls; }
  5978. @A
  5979. class Foo {}
  5980. @B
  5981. class Bar {}
  5982. `;
  5983. const result = extractFromSource('app.ts', code);
  5984. const decoratesEdges = result.unresolvedReferences.filter(
  5985. (r) => r.referenceKind === 'decorates'
  5986. );
  5987. // Exactly one decorates ref per decorated class, no cross-attribution.
  5988. const fromBar = decoratesEdges.filter((r) =>
  5989. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  5990. );
  5991. expect(fromBar.length).toBe(1);
  5992. expect(fromBar[0]!.referenceName).toBe('B');
  5993. });
  5994. it('emits a decorates ref for `@Foo method() {}`', () => {
  5995. const code = `
  5996. function Get(p: string) { return (t: any, k: string) => t; }
  5997. class Svc {
  5998. @Get('/x') method() { return 1; }
  5999. }
  6000. `;
  6001. const result = extractFromSource('app.ts', code);
  6002. const decorMethod = result.unresolvedReferences.find(
  6003. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  6004. );
  6005. expect(decorMethod).toBeDefined();
  6006. // The decorated symbol must be `method`, not the constructor or class.
  6007. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  6008. expect(decoratedNode?.name).toBe('method');
  6009. });
  6010. });
  6011. // =============================================================================
  6012. // Lua
  6013. // =============================================================================
  6014. describe('Lua Extraction', () => {
  6015. describe('Language detection', () => {
  6016. it('should detect Lua files', () => {
  6017. expect(detectLanguage('init.lua')).toBe('lua');
  6018. expect(detectLanguage('src/util.lua')).toBe('lua');
  6019. });
  6020. it('should report Lua as supported', () => {
  6021. expect(isLanguageSupported('lua')).toBe(true);
  6022. expect(getSupportedLanguages()).toContain('lua');
  6023. });
  6024. });
  6025. describe('Function extraction', () => {
  6026. it('should extract global and local functions', () => {
  6027. const code = `
  6028. function configure(opts) return opts end
  6029. local function helper(x) return x * 2 end
  6030. `;
  6031. const result = extractFromSource('init.lua', code);
  6032. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  6033. expect(funcs).toContain('configure');
  6034. expect(funcs).toContain('helper');
  6035. const configure = result.nodes.find((n) => n.name === 'configure');
  6036. expect(configure?.language).toBe('lua');
  6037. expect(configure?.signature).toBe('(opts)');
  6038. });
  6039. it('should split table/method functions into a receiver and method name', () => {
  6040. const code = `
  6041. function M.connect(host, port) return host end
  6042. function M:send(data) return self end
  6043. `;
  6044. const result = extractFromSource('init.lua', code);
  6045. const methods = result.nodes.filter((n) => n.kind === 'method');
  6046. const connect = methods.find((m) => m.name === 'connect');
  6047. expect(connect?.qualifiedName).toBe('M::connect');
  6048. const send = methods.find((m) => m.name === 'send');
  6049. expect(send?.qualifiedName).toBe('M::send');
  6050. });
  6051. });
  6052. describe('Variable extraction', () => {
  6053. it('should extract local variable declarations', () => {
  6054. const code = `
  6055. local M = {}
  6056. local count = 0
  6057. `;
  6058. const result = extractFromSource('mod.lua', code);
  6059. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  6060. expect(vars).toContain('M');
  6061. expect(vars).toContain('count');
  6062. });
  6063. });
  6064. describe('Import extraction (require)', () => {
  6065. it('should extract require() in local declarations and bare calls', () => {
  6066. const code = `
  6067. local socket = require("socket")
  6068. local http = require "resty.http"
  6069. require("side.effect")
  6070. `;
  6071. const result = extractFromSource('net.lua', code);
  6072. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6073. expect(imports).toContain('socket');
  6074. expect(imports).toContain('resty.http');
  6075. expect(imports).toContain('side.effect');
  6076. const ref = result.unresolvedReferences.find(
  6077. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  6078. );
  6079. expect(ref).toBeDefined();
  6080. });
  6081. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  6082. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  6083. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  6084. // by extracting several sources in sequence and asserting the LAST still works.
  6085. it('should keep extracting require across many sequential parses', () => {
  6086. let last;
  6087. for (let i = 0; i < 8; i++) {
  6088. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  6089. }
  6090. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6091. expect(imports).toContain('module.7');
  6092. });
  6093. });
  6094. describe('Call extraction', () => {
  6095. it('should record intra-file calls as resolvable references', () => {
  6096. const code = `
  6097. local function helper(x) return x end
  6098. local function run(y) return helper(y) end
  6099. `;
  6100. const result = extractFromSource('calls.lua', code);
  6101. const call = result.unresolvedReferences.find(
  6102. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  6103. );
  6104. expect(call).toBeDefined();
  6105. });
  6106. });
  6107. });
  6108. // =============================================================================
  6109. // Luau (typed superset of Lua — https://luau.org)
  6110. // =============================================================================
  6111. describe('Luau Extraction', () => {
  6112. describe('Language detection', () => {
  6113. it('should detect Luau files', () => {
  6114. expect(detectLanguage('init.luau')).toBe('luau');
  6115. expect(detectLanguage('src/Client.luau')).toBe('luau');
  6116. });
  6117. it('should report Luau as supported', () => {
  6118. expect(isLanguageSupported('luau')).toBe(true);
  6119. expect(getSupportedLanguages()).toContain('luau');
  6120. });
  6121. });
  6122. describe('Type aliases', () => {
  6123. it('should extract `type` and `export type` definitions', () => {
  6124. const code = `
  6125. export type Vector = { x: number, y: number }
  6126. type Handler = (msg: string) -> boolean
  6127. `;
  6128. const result = extractFromSource('types.luau', code);
  6129. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  6130. const vector = aliases.find((a) => a.name === 'Vector');
  6131. expect(vector).toBeDefined();
  6132. expect(vector?.isExported).toBe(true);
  6133. const handler = aliases.find((a) => a.name === 'Handler');
  6134. expect(handler).toBeDefined();
  6135. expect(handler?.isExported).toBe(false);
  6136. });
  6137. });
  6138. describe('Typed functions and methods', () => {
  6139. it('should capture typed signatures and split methods by receiver', () => {
  6140. const code = `
  6141. function configure(opts: { debug: boolean }): boolean
  6142. return opts.debug
  6143. end
  6144. function Client:fetch(path: string): Response
  6145. return path
  6146. end
  6147. `;
  6148. const result = extractFromSource('client.luau', code);
  6149. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  6150. expect(configure?.language).toBe('luau');
  6151. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  6152. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  6153. expect(fetch?.qualifiedName).toBe('Client::fetch');
  6154. });
  6155. });
  6156. describe('Imports and variables', () => {
  6157. it('should extract string and Roblox instance-path require imports', () => {
  6158. const code = `
  6159. local http = require("http")
  6160. local Signal = require(script.Parent.Signal)
  6161. local count = 0
  6162. `;
  6163. const result = extractFromSource('mod.luau', code);
  6164. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6165. expect(imports).toContain('http'); // string require
  6166. expect(imports).toContain('Signal'); // Roblox instance-path require
  6167. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  6168. expect(vars).toContain('count');
  6169. });
  6170. });
  6171. });
  6172. // =============================================================================
  6173. // Objective-C
  6174. // =============================================================================
  6175. describe('Objective-C Extraction', () => {
  6176. const sample = `
  6177. #import <Foundation/Foundation.h>
  6178. #import "MyClass.h"
  6179. @interface MyClass : NSObject <NSCopying>
  6180. @property (nonatomic, copy) NSString *name;
  6181. - (void)greet;
  6182. - (void)doThing:(id)x with:(id)y;
  6183. + (instancetype)shared;
  6184. @end
  6185. @implementation MyClass
  6186. - (void)greet {
  6187. NSLog(@"Hello");
  6188. [self doWork];
  6189. }
  6190. - (void)doThing:(id)x with:(id)y {
  6191. [self notify:x];
  6192. }
  6193. + (instancetype)shared {
  6194. return [[MyClass alloc] init];
  6195. }
  6196. @end
  6197. void helperFunction(int count) {
  6198. MyClass *obj = [MyClass shared];
  6199. [obj greet];
  6200. }
  6201. `;
  6202. it('should extract classes, methods, functions, and imports', () => {
  6203. const result = extractFromSource('App.m', sample);
  6204. const classes = result.nodes.filter((n) => n.kind === 'class');
  6205. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  6206. const methods = result.nodes.filter((n) => n.kind === 'method');
  6207. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  6208. const shared = methods.find((m) => m.name === 'shared');
  6209. expect(shared?.isStatic).toBe(true);
  6210. const properties = result.nodes.filter((n) => n.kind === 'property');
  6211. expect(properties.some((p) => p.name === 'name')).toBe(true);
  6212. const functions = result.nodes.filter((n) => n.kind === 'function');
  6213. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  6214. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6215. expect(imports).toContain('Foundation/Foundation.h');
  6216. expect(imports).toContain('MyClass.h');
  6217. });
  6218. it('should record inheritance and protocol conformance', () => {
  6219. const result = extractFromSource('App.m', sample);
  6220. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  6221. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  6222. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  6223. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  6224. });
  6225. it('should record message sends and C calls', () => {
  6226. const result = extractFromSource('App.m', sample);
  6227. const calls = result.unresolvedReferences
  6228. .filter((r) => r.referenceKind === 'calls')
  6229. .map((r) => r.referenceName);
  6230. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  6231. });
  6232. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  6233. // Regression for the gap discovered post-#165: message_expression's
  6234. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  6235. // so calls never resolved to multi-part method definitions like
  6236. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  6237. // must match the method-definition name with full keywords + trailing colons.
  6238. const code = `
  6239. @implementation Caller
  6240. - (void)demo {
  6241. NSMutableDictionary *d = [NSMutableDictionary new];
  6242. [d setObject:@"v" forKey:@"k"];
  6243. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  6244. [self touchesBegan:nil withEvent:nil];
  6245. }
  6246. @end
  6247. `;
  6248. const result = extractFromSource('Caller.m', code);
  6249. const calls = result.unresolvedReferences
  6250. .filter((r) => r.referenceKind === 'calls')
  6251. .map((r) => r.referenceName);
  6252. expect(calls).toEqual(
  6253. expect.arrayContaining([
  6254. 'd.setObject:forKey:',
  6255. 'd.setObject:forKey:withRetry:',
  6256. 'touchesBegan:withEvent:',
  6257. ])
  6258. );
  6259. });
  6260. it('should not classify pure C headers with @end in comments as objc', () => {
  6261. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  6262. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  6263. });
  6264. it('should extract protocol declarations', () => {
  6265. const code = `
  6266. @protocol DataSource <NSObject>
  6267. - (NSInteger)numberOfItems;
  6268. @end
  6269. `;
  6270. const result = extractFromSource('DataSource.h', code);
  6271. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  6272. expect(protocol).toBeDefined();
  6273. });
  6274. it('should report Objective-C as supported', () => {
  6275. expect(isLanguageSupported('objc')).toBe(true);
  6276. expect(getSupportedLanguages()).toContain('objc');
  6277. });
  6278. });
  6279. describe('Regression: issue-specific extraction fixes', () => {
  6280. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  6281. const code = `
  6282. define(['dep'], function (dep) {
  6283. function innerHelper(x) { return x + 1; }
  6284. function compute(y) { return innerHelper(y); }
  6285. return { compute: compute };
  6286. });
  6287. `;
  6288. const result = extractFromSource('amd-module.js', code);
  6289. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  6290. expect(fns).toContain('innerHelper');
  6291. expect(fns).toContain('compute');
  6292. });
  6293. it('attaches Go methods on generic receivers to their type (#583)', () => {
  6294. const code = `
  6295. package main
  6296. type Stack[T any] struct { items []T }
  6297. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  6298. func (s Stack[T]) Len() int { return len(s.items) }
  6299. `;
  6300. const result = extractFromSource('stack.go', code);
  6301. const methods = result.nodes.filter((n) => n.kind === 'method');
  6302. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  6303. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  6304. });
  6305. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  6306. expect(isSourceFile('mod.mts')).toBe(true);
  6307. expect(isSourceFile('mod.cts')).toBe(true);
  6308. expect(isSourceFile('service.xsjs')).toBe(true);
  6309. expect(isSourceFile('lib.xsjslib')).toBe(true);
  6310. expect(detectLanguage('mod.mts')).toBe('typescript');
  6311. expect(detectLanguage('service.xsjs')).toBe('javascript');
  6312. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  6313. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  6314. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  6315. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  6316. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  6317. });
  6318. });
  6319. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  6320. // An import IS a dependency, but extraction only emits references for calls,
  6321. // instantiations, type annotations, and inheritance — so a symbol imported and
  6322. // then merely re-exported, placed in a registry array, passed as an argument,
  6323. // or used in JSX produced no cross-file edge, leaving the providing file with a
  6324. // false "0 dependents". These tests pin the import/re-export binding linking.
  6325. it('emits an imports reference per named, aliased, and default import binding', () => {
  6326. const code = `
  6327. import { widget, helper as h } from './foo';
  6328. import Thing from './thing';
  6329. import * as NS from './ns';
  6330. export const registry = [widget];
  6331. `;
  6332. const result = extractFromSource('bar.ts', code);
  6333. const names = result.unresolvedReferences
  6334. .filter((r) => r.referenceKind === 'imports')
  6335. .map((r) => r.referenceName);
  6336. expect(names).toContain('widget'); // named import → local name
  6337. expect(names).toContain('h'); // aliased import → local alias
  6338. expect(names).toContain('Thing'); // default import
  6339. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  6340. });
  6341. it('emits an imports reference per re-exported binding', () => {
  6342. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  6343. const names = result.unresolvedReferences
  6344. .filter((r) => r.referenceKind === 'imports')
  6345. .map((r) => r.referenceName);
  6346. // Re-export links the SOURCE-side name, not the local alias.
  6347. expect(names).toContain('alpha');
  6348. expect(names).toContain('beta');
  6349. });
  6350. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  6351. const dir = createTempDir();
  6352. try {
  6353. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6354. fs.writeFileSync(
  6355. path.join(dir, 'src', 'foo.ts'),
  6356. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  6357. );
  6358. // bar uses widget ONLY in an array and re-exports helper — neither is
  6359. // called/typed, so before import-linking bar had no edge to foo at all.
  6360. fs.writeFileSync(
  6361. path.join(dir, 'src', 'bar.ts'),
  6362. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  6363. );
  6364. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  6365. await cg.indexAll();
  6366. cg.resolveReferences();
  6367. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  6368. cg.destroy();
  6369. } finally {
  6370. cleanupTempDir(dir);
  6371. }
  6372. });
  6373. it('a namespace import touched only via a value-member read still links the module file', async () => {
  6374. const dir = createTempDir();
  6375. try {
  6376. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6377. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  6378. // `foo` is imported as a namespace and used ONLY via a value-member read
  6379. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  6380. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  6381. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  6382. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  6383. await cg.indexAll();
  6384. cg.resolveReferences();
  6385. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  6386. cg.destroy();
  6387. } finally {
  6388. cleanupTempDir(dir);
  6389. }
  6390. });
  6391. });
  6392. describe('Python import dependency linking (blast-radius recall)', () => {
  6393. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  6394. // name brought in with `from module import X` and then merely stored, used as
  6395. // a decorator/argument, or re-exported through an `__init__.py` produced no
  6396. // cross-file edge — the providing module showed a false "0 dependents".
  6397. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  6398. const code = [
  6399. 'from foo import helper, widget',
  6400. 'from foo import Thing as T',
  6401. 'from . import sibling',
  6402. 'from bar import *',
  6403. ].join('\n');
  6404. const names = extractFromSource('mod.py', code)
  6405. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  6406. .map((r) => r.referenceName);
  6407. expect(names).toContain('helper');
  6408. expect(names).toContain('widget'); // value import
  6409. expect(names).toContain('T'); // aliased import → local name
  6410. expect(names).toContain('sibling'); // `from . import <name>`
  6411. expect(names).not.toContain('*'); // wildcard import has no names
  6412. });
  6413. it('a Python value imported but never called still makes the importer a dependent', async () => {
  6414. const dir = createTempDir();
  6415. try {
  6416. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6417. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  6418. // bar imports widget+helper but only stores widget in a list — nothing is
  6419. // called, so before import-linking bar had no edge to foo.
  6420. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  6421. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6422. await cg.indexAll();
  6423. cg.resolveReferences();
  6424. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  6425. cg.destroy();
  6426. } finally {
  6427. cleanupTempDir(dir);
  6428. }
  6429. });
  6430. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  6431. const dir = createTempDir();
  6432. try {
  6433. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6434. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  6435. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  6436. // certs is an imported MODULE (a file), and certs.where() is a qualified
  6437. // call through it — the receiver isn't a symbol, so plain name-matching
  6438. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  6439. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  6440. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6441. await cg.indexAll();
  6442. cg.resolveReferences();
  6443. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  6444. cg.destroy();
  6445. } finally {
  6446. cleanupTempDir(dir);
  6447. }
  6448. });
  6449. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  6450. const dir = createTempDir();
  6451. try {
  6452. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  6453. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  6454. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  6455. // member resolution can't find it — the module-import backstop must still
  6456. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  6457. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  6458. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  6459. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  6460. await cg.indexAll();
  6461. cg.resolveReferences();
  6462. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  6463. cg.destroy();
  6464. } finally {
  6465. cleanupTempDir(dir);
  6466. }
  6467. });
  6468. });
  6469. describe('Go cross-package composite literals (blast-radius recall)', () => {
  6470. // Go function calls and type references across packages already resolved, but
  6471. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  6472. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  6473. // (gin's render/binding implementations) showed 0 dependents.
  6474. it('links a cross-package struct composite literal to the defining package', async () => {
  6475. const dir = createTempDir();
  6476. try {
  6477. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6478. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  6479. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  6480. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  6481. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6482. await cg.indexAll();
  6483. cg.resolveReferences();
  6484. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  6485. cg.destroy();
  6486. } finally {
  6487. cleanupTempDir(dir);
  6488. }
  6489. });
  6490. it('links a composite literal in a package-level var registry', async () => {
  6491. const dir = createTempDir();
  6492. try {
  6493. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6494. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  6495. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  6496. // The implementation is registered only in a top-level `var registry = {...}`
  6497. // map literal — the body walker doesn't cover top-level declarations, so this
  6498. // exercises the var-initializer walking added for Go.
  6499. 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`);
  6500. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6501. await cg.indexAll();
  6502. cg.resolveReferences();
  6503. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  6504. cg.destroy();
  6505. } finally {
  6506. cleanupTempDir(dir);
  6507. }
  6508. });
  6509. it('attributes a call inside a top-level closure (cobra RunE) to the var, not the file (#693)', async () => {
  6510. const dir = createTempDir();
  6511. try {
  6512. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6513. // Wire is called ONLY from the anonymous RunE closure inside a top-level
  6514. // `var rootCmd = &Cmd{...}` — previously the call leaked to the file node,
  6515. // so `callers(Wire)` surfaced a file (or read as "no caller"). It must now
  6516. // attribute to the enclosing var.
  6517. fs.writeFileSync(path.join(dir, 'factory.go'), `package main\n\nfunc Wire() error { return nil }\n`);
  6518. fs.writeFileSync(
  6519. path.join(dir, 'root.go'),
  6520. `package main\n\ntype Cmd struct{ RunE func() error }\n\nvar rootCmd = &Cmd{\n\tRunE: func() error { return Wire() },\n}\n`
  6521. );
  6522. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6523. await cg.indexAll();
  6524. cg.resolveReferences();
  6525. const wire = cg.getNodesByName('Wire').find((n) => n.kind === 'function');
  6526. expect(wire).toBeDefined();
  6527. const callers = cg.getCallers(wire!.id).map((c) => c.node);
  6528. expect(callers.some((n) => n.kind === 'variable' && n.name === 'rootCmd')).toBe(true);
  6529. expect(callers.some((n) => n.kind === 'file')).toBe(false);
  6530. cg.destroy();
  6531. } finally {
  6532. cleanupTempDir(dir);
  6533. }
  6534. });
  6535. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  6536. const dir = createTempDir();
  6537. try {
  6538. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6539. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  6540. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  6541. // `(*Wrapped)` — without normalization it dropped on the floor.
  6542. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  6543. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6544. await cg.indexAll();
  6545. cg.resolveReferences();
  6546. expect(cg.getFileDependents('types.go')).toContain('use.go');
  6547. cg.destroy();
  6548. } finally {
  6549. cleanupTempDir(dir);
  6550. }
  6551. });
  6552. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  6553. const dir = createTempDir();
  6554. try {
  6555. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  6556. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  6557. 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`);
  6558. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  6559. // reached ONLY through the interface (API.Marshal). Without implicit
  6560. // interface satisfaction + dispatch, json.go shows 0 dependents.
  6561. 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`);
  6562. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  6563. await cg.indexAll();
  6564. cg.resolveReferences();
  6565. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  6566. cg.destroy();
  6567. } finally {
  6568. cleanupTempDir(dir);
  6569. }
  6570. });
  6571. });
  6572. describe('C# records (blast-radius recall)', () => {
  6573. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  6574. // but `record` / `record struct` declarations weren't extracted as types — so
  6575. // every reference, generic-type-argument, and `new` of a record dropped on the
  6576. // floor and the defining file showed 0 dependents. (#237)
  6577. it('extracts a record as a graph node (record class + record struct)', () => {
  6578. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  6579. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  6580. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  6581. });
  6582. it('resolves references / instantiations of a record across files', async () => {
  6583. const dir = createTempDir();
  6584. try {
  6585. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  6586. // Box is used as a generic type argument and instantiated — both require
  6587. // Box to be a node to resolve.
  6588. fs.writeFileSync(
  6589. path.join(dir, 'use.cs'),
  6590. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  6591. );
  6592. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  6593. await cg.indexAll();
  6594. cg.resolveReferences();
  6595. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  6596. cg.destroy();
  6597. } finally {
  6598. cleanupTempDir(dir);
  6599. }
  6600. });
  6601. });
  6602. describe('Rust cross-module recall', () => {
  6603. function rustProject(files: Record<string, string>): string {
  6604. const dir = createTempDir();
  6605. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  6606. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  6607. for (const [rel, content] of Object.entries(files)) {
  6608. const full = path.join(dir, 'src', rel);
  6609. fs.mkdirSync(path.dirname(full), { recursive: true });
  6610. fs.writeFileSync(full, content);
  6611. }
  6612. return dir;
  6613. }
  6614. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  6615. const dir = rustProject({
  6616. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  6617. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  6618. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  6619. });
  6620. try {
  6621. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6622. await cg.indexAll();
  6623. cg.resolveReferences();
  6624. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  6625. cg.destroy();
  6626. } finally { cleanupTempDir(dir); }
  6627. });
  6628. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  6629. const dir = rustProject({
  6630. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  6631. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  6632. // Mine implements Render structurally; reached via &dyn Render dispatch.
  6633. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  6634. });
  6635. try {
  6636. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6637. await cg.indexAll();
  6638. cg.resolveReferences();
  6639. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  6640. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  6641. cg.destroy();
  6642. } finally { cleanupTempDir(dir); }
  6643. });
  6644. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  6645. const dir = rustProject({
  6646. 'lib.rs': 'pub mod api;\n',
  6647. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  6648. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  6649. });
  6650. try {
  6651. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6652. await cg.indexAll();
  6653. cg.resolveReferences();
  6654. // The re-export hub depends on the module it re-exports from.
  6655. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  6656. cg.destroy();
  6657. } finally { cleanupTempDir(dir); }
  6658. });
  6659. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  6660. const dir = rustProject({
  6661. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  6662. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  6663. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  6664. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  6665. // send this re-export to fast.rs specifically, not name-match either.
  6666. 'hub.rs': 'pub use crate::fast::read;\n',
  6667. });
  6668. try {
  6669. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  6670. await cg.indexAll();
  6671. cg.resolveReferences();
  6672. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  6673. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  6674. cg.destroy();
  6675. } finally { cleanupTempDir(dir); }
  6676. });
  6677. });
  6678. describe('Java annotations (blast-radius recall)', () => {
  6679. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  6680. const dir = createTempDir();
  6681. try {
  6682. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  6683. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  6684. // live inside a `modifiers` node on the class/field/method) must extract.
  6685. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  6686. fs.writeFileSync(
  6687. path.join(dir, 'p', 'User.java'),
  6688. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  6689. );
  6690. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  6691. await cg.indexAll();
  6692. cg.resolveReferences();
  6693. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  6694. cg.destroy();
  6695. } finally { cleanupTempDir(dir); }
  6696. });
  6697. });
  6698. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  6699. it('links a @propertyWrapper usage to the wrapper type', async () => {
  6700. const dir = createTempDir();
  6701. try {
  6702. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  6703. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  6704. // `@Argument` is a Swift attribute on a stored property — it lives in the
  6705. // property's `modifiers` and Swift doesn't extract instance properties as
  6706. // their own nodes, so without the fix the wrapper type has no users.
  6707. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  6708. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  6709. await cg.indexAll();
  6710. cg.resolveReferences();
  6711. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  6712. cg.destroy();
  6713. } finally { cleanupTempDir(dir); }
  6714. });
  6715. });
  6716. describe('R Extraction', () => {
  6717. describe('Language detection', () => {
  6718. it('should detect R files (both extension cases)', () => {
  6719. expect(detectLanguage('analysis.R')).toBe('r');
  6720. expect(detectLanguage('scripts/clean.r')).toBe('r');
  6721. });
  6722. it('should report R as supported', () => {
  6723. expect(isLanguageSupported('r')).toBe(true);
  6724. expect(getSupportedLanguages()).toContain('r');
  6725. });
  6726. });
  6727. describe('Function extraction', () => {
  6728. it('extracts every assignment form, lambdas, and nested functions', () => {
  6729. const code = `
  6730. clean_data <- function(df, threshold = 0.5) {
  6731. helper <- function(d) scale(d)
  6732. helper(df)
  6733. }
  6734. normalize = function(v) (v - mean(v)) / sd(v)
  6735. double_it <- \\(x) x * 2
  6736. `;
  6737. const result = extractFromSource('analysis.R', code);
  6738. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  6739. expect(funcs).toContain('clean_data');
  6740. expect(funcs).toContain('normalize');
  6741. expect(funcs).toContain('double_it');
  6742. expect(funcs).toContain('helper'); // nested, inside clean_data's scope
  6743. const cleanData = result.nodes.find((n) => n.name === 'clean_data');
  6744. expect(cleanData?.language).toBe('r');
  6745. expect(cleanData?.signature).toBe('(df, threshold = 0.5)');
  6746. });
  6747. it('attributes body calls to the enclosing function', () => {
  6748. const code = `
  6749. prep <- function(d) scale(d)
  6750. fit_model <- function(data) {
  6751. lm(y ~ x, data = prep(data))
  6752. }
  6753. `;
  6754. const result = extractFromSource('models.R', code);
  6755. const prepCall = result.unresolvedReferences.find(
  6756. (r) => r.referenceName === 'prep' && r.referenceKind === 'calls'
  6757. );
  6758. expect(prepCall).toBeDefined();
  6759. const fitModel = result.nodes.find((n) => n.name === 'fit_model');
  6760. expect(prepCall?.fromNodeId).toBe(fitModel?.id);
  6761. });
  6762. });
  6763. describe('Imports', () => {
  6764. it('extracts library/require/source as imports, not calls', () => {
  6765. const code = `
  6766. library(dplyr)
  6767. require(stats)
  6768. requireNamespace("jsonlite")
  6769. source("helpers.R")
  6770. `;
  6771. const result = extractFromSource('main.R', code);
  6772. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  6773. expect(imports).toContain('dplyr');
  6774. expect(imports).toContain('stats');
  6775. expect(imports).toContain('jsonlite');
  6776. expect(imports).toContain('helpers.R');
  6777. // Claimed by the hook — no call references to the import machinery.
  6778. const libCalls = result.unresolvedReferences.filter(
  6779. (r) => r.referenceKind === 'calls' && (r.referenceName === 'library' || r.referenceName === 'source')
  6780. );
  6781. expect(libCalls).toHaveLength(0);
  6782. });
  6783. });
  6784. describe('Variables and constants', () => {
  6785. it('extracts top-level assignments; ALL_CAPS as constants; right-assign too', () => {
  6786. const code = `
  6787. ALPHA <- 0.05
  6788. max_iter = 100
  6789. compute_stats(df) -> stats_result
  6790. inner <- function() {
  6791. local_var <- 1
  6792. }
  6793. `;
  6794. const result = extractFromSource('config.R', code);
  6795. const constant = result.nodes.find((n) => n.name === 'ALPHA');
  6796. expect(constant?.kind).toBe('constant');
  6797. const variable = result.nodes.find((n) => n.name === 'max_iter');
  6798. expect(variable?.kind).toBe('variable');
  6799. const rightAssigned = result.nodes.find((n) => n.name === 'stats_result');
  6800. expect(rightAssigned?.kind).toBe('variable');
  6801. // Locals inside functions are deliberately NOT extracted.
  6802. expect(result.nodes.find((n) => n.name === 'local_var')).toBeUndefined();
  6803. });
  6804. });
  6805. describe('Classes', () => {
  6806. it('extracts S4/R5/R6 class calls as classes with their list methods', () => {
  6807. const code = `
  6808. setClass("Patient", representation(id = "character"))
  6809. Account <- setRefClass("Account",
  6810. fields = list(balance = "numeric"),
  6811. methods = list(deposit = function(x) { balance <<- balance + x })
  6812. )
  6813. Stack <- R6Class("Stack",
  6814. public = list(push = function(v) invisible(v))
  6815. )
  6816. setGeneric("describe", function(obj) standardGeneric("describe"))
  6817. setMethod("describe", "Patient", function(obj) paste(obj@id))
  6818. `;
  6819. const result = extractFromSource('classes.R', code);
  6820. const classes = result.nodes.filter((n) => n.kind === 'class').map((n) => n.name);
  6821. expect(classes).toContain('Patient');
  6822. expect(classes).toContain('Account');
  6823. expect(classes).toContain('Stack');
  6824. const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => n.name);
  6825. expect(methods).toContain('deposit');
  6826. expect(methods).toContain('push');
  6827. // setGeneric/setMethod produce functions named by their string argument.
  6828. const describes = result.nodes.filter((n) => n.name === 'describe' && n.kind === 'function');
  6829. expect(describes.length).toBeGreaterThanOrEqual(2);
  6830. // The class-assignment idiom must not ALSO produce a variable node.
  6831. expect(result.nodes.find((n) => n.name === 'Account' && n.kind === 'variable')).toBeUndefined();
  6832. });
  6833. it('extracts ggproto classes with direct-arg methods and the parent as extends', () => {
  6834. // ggplot2's OO system — every Geom/Stat/Scale in the ecosystem uses it.
  6835. const code = `
  6836. GeomPoint <- ggproto("GeomPoint", Geom,
  6837. required_aes = c("x", "y"),
  6838. draw_panel = function(data, panel_params, coord) {
  6839. coords <- coord$transform(data, panel_params)
  6840. grid::pointsGrob(coords$x, coords$y)
  6841. },
  6842. draw_key = draw_key_point
  6843. )
  6844. `;
  6845. const result = extractFromSource('geom-point.R', code);
  6846. const cls = result.nodes.find((n) => n.name === 'GeomPoint' && n.kind === 'class');
  6847. expect(cls).toBeDefined();
  6848. const method = result.nodes.find((n) => n.name === 'draw_panel' && n.kind === 'method');
  6849. expect(method).toBeDefined();
  6850. const ext = result.unresolvedReferences.find(
  6851. (r) => r.referenceKind === 'extends' && r.referenceName === 'Geom'
  6852. );
  6853. expect(ext?.fromNodeId).toBe(cls?.id);
  6854. // No twin variable for the assignment.
  6855. expect(result.nodes.find((n) => n.name === 'GeomPoint' && n.kind === 'variable')).toBeUndefined();
  6856. });
  6857. });
  6858. });