extraction.test.ts 177 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311
  1. /**
  2. * Extraction Tests
  3. *
  4. * Tests for the tree-sitter extraction system.
  5. */
  6. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { extractFromSource, scanDirectory } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages, initGrammars, loadAllGrammars, isSourceFile } from '../src/extraction/grammars';
  13. import { normalizePath } from '../src/utils';
  14. beforeAll(async () => {
  15. await initGrammars();
  16. await loadAllGrammars();
  17. });
  18. // Create a temporary directory for each test
  19. function createTempDir(): string {
  20. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  21. }
  22. // Clean up temporary directory
  23. function cleanupTempDir(dir: string): void {
  24. if (fs.existsSync(dir)) {
  25. fs.rmSync(dir, { recursive: true, force: true });
  26. }
  27. }
  28. describe('Language Detection', () => {
  29. it('should detect TypeScript files', () => {
  30. expect(detectLanguage('src/index.ts')).toBe('typescript');
  31. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  32. });
  33. it('should detect JavaScript files', () => {
  34. expect(detectLanguage('index.js')).toBe('javascript');
  35. expect(detectLanguage('App.jsx')).toBe('jsx');
  36. expect(detectLanguage('config.mjs')).toBe('javascript');
  37. });
  38. it('should detect Python files', () => {
  39. expect(detectLanguage('main.py')).toBe('python');
  40. });
  41. it('should detect Go files', () => {
  42. expect(detectLanguage('main.go')).toBe('go');
  43. });
  44. it('should detect Rust files', () => {
  45. expect(detectLanguage('lib.rs')).toBe('rust');
  46. });
  47. it('should detect Java files', () => {
  48. expect(detectLanguage('Main.java')).toBe('java');
  49. });
  50. it('should detect C files', () => {
  51. expect(detectLanguage('main.c')).toBe('c');
  52. expect(detectLanguage('utils.h')).toBe('c');
  53. });
  54. it('should detect C++ files', () => {
  55. expect(detectLanguage('main.cpp')).toBe('cpp');
  56. expect(detectLanguage('class.hpp')).toBe('cpp');
  57. });
  58. it('should detect C# files', () => {
  59. expect(detectLanguage('Program.cs')).toBe('csharp');
  60. });
  61. it('should detect PHP files', () => {
  62. expect(detectLanguage('index.php')).toBe('php');
  63. });
  64. it('should detect Ruby files', () => {
  65. expect(detectLanguage('app.rb')).toBe('ruby');
  66. });
  67. it('should detect Swift files', () => {
  68. expect(detectLanguage('ViewController.swift')).toBe('swift');
  69. });
  70. it('should detect Kotlin files', () => {
  71. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  72. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  73. });
  74. it('should detect Dart files', () => {
  75. expect(detectLanguage('main.dart')).toBe('dart');
  76. });
  77. it('should detect Objective-C files', () => {
  78. expect(detectLanguage('AppDelegate.m')).toBe('objc');
  79. expect(detectLanguage('ViewController.mm')).toBe('objc');
  80. const objcHeader = '@interface Foo : NSObject\n@end\n';
  81. expect(detectLanguage('Foo.h', objcHeader)).toBe('objc');
  82. expect(detectLanguage('stdio.h', '#ifndef STDIO_H\nvoid printf();\n#endif\n')).toBe('c');
  83. });
  84. it('should return unknown for unsupported extensions', () => {
  85. expect(detectLanguage('styles.css')).toBe('unknown');
  86. expect(detectLanguage('data.json')).toBe('unknown');
  87. });
  88. });
  89. describe('Language Support', () => {
  90. it('should report supported languages', () => {
  91. expect(isLanguageSupported('typescript')).toBe(true);
  92. expect(isLanguageSupported('python')).toBe(true);
  93. expect(isLanguageSupported('go')).toBe(true);
  94. expect(isLanguageSupported('unknown')).toBe(false);
  95. });
  96. it('should list all supported languages', () => {
  97. const languages = getSupportedLanguages();
  98. expect(languages).toContain('typescript');
  99. expect(languages).toContain('javascript');
  100. expect(languages).toContain('python');
  101. expect(languages).toContain('go');
  102. expect(languages).toContain('rust');
  103. expect(languages).toContain('java');
  104. expect(languages).toContain('csharp');
  105. expect(languages).toContain('php');
  106. expect(languages).toContain('ruby');
  107. expect(languages).toContain('swift');
  108. expect(languages).toContain('kotlin');
  109. expect(languages).toContain('dart');
  110. });
  111. });
  112. describe('TypeScript Extraction', () => {
  113. it('should extract function declarations', () => {
  114. const code = `
  115. export function processPayment(amount: number): Promise<Receipt> {
  116. return stripe.charge(amount);
  117. }
  118. `;
  119. const result = extractFromSource('payment.ts', code);
  120. // File node + function node
  121. const fileNode = result.nodes.find((n) => n.kind === 'file');
  122. expect(fileNode).toBeDefined();
  123. expect(fileNode?.name).toBe('payment.ts');
  124. const funcNode = result.nodes.find((n) => n.kind === 'function');
  125. expect(funcNode).toMatchObject({
  126. kind: 'function',
  127. name: 'processPayment',
  128. language: 'typescript',
  129. isExported: true,
  130. });
  131. expect(funcNode?.signature).toContain('amount: number');
  132. });
  133. it('should extract class declarations', () => {
  134. const code = `
  135. export class PaymentService {
  136. private stripe: StripeClient;
  137. constructor(apiKey: string) {
  138. this.stripe = new StripeClient(apiKey);
  139. }
  140. async charge(amount: number): Promise<Receipt> {
  141. return this.stripe.charge(amount);
  142. }
  143. }
  144. `;
  145. const result = extractFromSource('service.ts', code);
  146. const classNode = result.nodes.find((n) => n.kind === 'class');
  147. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  148. expect(classNode).toBeDefined();
  149. expect(classNode?.name).toBe('PaymentService');
  150. expect(classNode?.isExported).toBe(true);
  151. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  152. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  153. expect(chargeMethod).toBeDefined();
  154. });
  155. it('should extract interfaces', () => {
  156. const code = `
  157. export interface User {
  158. id: string;
  159. name: string;
  160. email: string;
  161. }
  162. `;
  163. const result = extractFromSource('types.ts', code);
  164. const fileNode = result.nodes.find((n) => n.kind === 'file');
  165. expect(fileNode).toBeDefined();
  166. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  167. expect(ifaceNode).toMatchObject({
  168. kind: 'interface',
  169. name: 'User',
  170. isExported: true,
  171. });
  172. });
  173. it('should extract type references from interface property signatures', () => {
  174. const code = `
  175. import type { IPage } from '../PromoterList';
  176. import type { IOrderField } from '../types';
  177. interface Hprops {
  178. value?: Partial<IPage> & Partial<IOrderField>;
  179. }
  180. `;
  181. const result = extractFromSource('HeaderFilter.ts', code);
  182. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  183. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  184. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  185. });
  186. it('should extract type references from interface method signatures', () => {
  187. const code = `
  188. import type { IPage } from '../PromoterList';
  189. import type { IOrderField } from '../types';
  190. interface MethodForm {
  191. fetchPage(arg: IPage): IOrderField;
  192. }
  193. `;
  194. const result = extractFromSource('MethodForm.ts', code);
  195. const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
  196. expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
  197. expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
  198. });
  199. it('extracts type references from in-body local variable annotations', () => {
  200. // A function that uses a type ONLY in its body — `const items: Foo[] = []` —
  201. // still depends on Foo. The body walker used to capture calls but never type
  202. // annotations, so impact / `affected` missed the dependency. Must cover
  203. // function, class-method, and object-literal-method bodies — and must NOT
  204. // turn the locals themselves into graph nodes (that would explode the graph).
  205. const code = `
  206. import { Foo } from './types';
  207. export function build(): void {
  208. const items: Foo[] = [];
  209. void items;
  210. }
  211. export class K {
  212. run(): void {
  213. const a: Foo = { x: 1 };
  214. void a;
  215. }
  216. }
  217. export const handler = {
  218. handle(): void {
  219. const b: Foo = { x: 1 };
  220. void b;
  221. },
  222. };
  223. `;
  224. const result = extractFromSource('inbody.ts', code);
  225. const fooRefs = result.unresolvedReferences.filter(
  226. (r) => r.referenceKind === 'references' && r.referenceName === 'Foo'
  227. );
  228. // One per body scope: build(), K.run(), handler.handle().
  229. expect(fooRefs.length).toBeGreaterThanOrEqual(3);
  230. // Each reference is attributed to its enclosing function/method node — never
  231. // to a local-variable node, because locals are intentionally not extracted.
  232. const byId = new Map(result.nodes.map((n) => [n.id, n]));
  233. for (const ref of fooRefs) {
  234. const owner = byId.get(ref.fromNodeId);
  235. expect(owner).toBeDefined();
  236. expect(['function', 'method']).toContain(owner!.kind);
  237. }
  238. // The locals (items/a/b) must not leak in as symbols.
  239. expect(result.nodes.some((n) => ['items', 'a', 'b'].includes(n.name))).toBe(false);
  240. });
  241. it('should track function calls', () => {
  242. const code = `
  243. function main() {
  244. const result = processData();
  245. console.log(result);
  246. }
  247. `;
  248. const result = extractFromSource('main.ts', code);
  249. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  250. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  251. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  252. });
  253. });
  254. describe('Arrow Function Export Extraction', () => {
  255. it('should extract exported arrow functions assigned to const', () => {
  256. const code = `
  257. export const useAuth = (): AuthContextValue => {
  258. return useContext(AuthContext);
  259. };
  260. `;
  261. const result = extractFromSource('hooks.ts', code);
  262. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  263. expect(funcNode).toBeDefined();
  264. expect(funcNode).toMatchObject({
  265. kind: 'function',
  266. name: 'useAuth',
  267. isExported: true,
  268. });
  269. });
  270. it('should extract exported function expressions assigned to const', () => {
  271. const code = `
  272. export const processData = function(input: string): string {
  273. return input.trim();
  274. };
  275. `;
  276. const result = extractFromSource('utils.ts', code);
  277. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  278. expect(funcNode).toBeDefined();
  279. expect(funcNode).toMatchObject({
  280. kind: 'function',
  281. name: 'processData',
  282. isExported: true,
  283. });
  284. });
  285. it('should not extract non-exported arrow functions as exported', () => {
  286. const code = `
  287. const internalHelper = () => {
  288. return 42;
  289. };
  290. `;
  291. const result = extractFromSource('internal.ts', code);
  292. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  293. expect(helperNode).toBeDefined();
  294. expect(helperNode?.isExported).toBeFalsy();
  295. });
  296. it('should still skip truly anonymous arrow functions', () => {
  297. const code = `
  298. const items = [1, 2, 3].map((x) => x * 2);
  299. `;
  300. const result = extractFromSource('anon.ts', code);
  301. // The inline arrow function passed to .map() has no variable_declarator parent
  302. // and should remain anonymous (skipped)
  303. const anonFunctions = result.nodes.filter(
  304. (n) => n.kind === 'function' && n.name === '<anonymous>'
  305. );
  306. expect(anonFunctions).toHaveLength(0);
  307. });
  308. it('should extract multiple exported arrow functions from the same file', () => {
  309. const code = `
  310. export const add = (a: number, b: number): number => a + b;
  311. export const subtract = (a: number, b: number): number => a - b;
  312. const internal = () => 'not exported';
  313. `;
  314. const result = extractFromSource('math.ts', code);
  315. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  316. expect(exported).toHaveLength(2);
  317. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  318. const internalNode = result.nodes.find((n) => n.name === 'internal');
  319. expect(internalNode).toBeDefined();
  320. expect(internalNode?.isExported).toBeFalsy();
  321. });
  322. it('should extract arrow functions in JavaScript files', () => {
  323. const code = `
  324. export const fetchData = async () => {
  325. const response = await fetch('/api/data');
  326. return response.json();
  327. };
  328. `;
  329. const result = extractFromSource('api.js', code);
  330. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  331. expect(funcNode).toBeDefined();
  332. expect(funcNode).toMatchObject({
  333. kind: 'function',
  334. name: 'fetchData',
  335. isExported: true,
  336. });
  337. });
  338. });
  339. describe('Type Alias Extraction', () => {
  340. it('should extract exported type aliases in TypeScript', () => {
  341. const code = `
  342. export type AuthContextValue = {
  343. user: User | null;
  344. login: () => void;
  345. logout: () => void;
  346. };
  347. `;
  348. const result = extractFromSource('types.ts', code);
  349. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  350. expect(typeNode).toMatchObject({
  351. kind: 'type_alias',
  352. name: 'AuthContextValue',
  353. isExported: true,
  354. });
  355. });
  356. it('should extract non-exported type aliases', () => {
  357. const code = `
  358. type InternalState = {
  359. loading: boolean;
  360. error: string | null;
  361. };
  362. `;
  363. const result = extractFromSource('internal.ts', code);
  364. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  365. expect(typeNode).toMatchObject({
  366. kind: 'type_alias',
  367. name: 'InternalState',
  368. isExported: false,
  369. });
  370. });
  371. it('should extract multiple type aliases from the same file', () => {
  372. const code = `
  373. export type UnitSystem = 'metric' | 'imperial';
  374. export type DateFormat = 'ISO' | 'US' | 'EU';
  375. type Internal = string;
  376. `;
  377. const result = extractFromSource('config.ts', code);
  378. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  379. expect(typeAliases).toHaveLength(3);
  380. const exported = typeAliases.filter((n) => n.isExported);
  381. expect(exported).toHaveLength(2);
  382. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  383. });
  384. });
  385. describe('Exported Variable Extraction', () => {
  386. it('should extract exported const with call expression (Zustand store)', () => {
  387. const code = `
  388. export const useUIStore = create<UIState>((set) => ({
  389. isOpen: false,
  390. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  391. }));
  392. `;
  393. const result = extractFromSource('store.ts', code);
  394. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  395. expect(varNode).toBeDefined();
  396. expect(varNode?.isExported).toBe(true);
  397. });
  398. it('should extract exported const with object literal', () => {
  399. const code = `
  400. export const config = {
  401. apiUrl: 'https://api.example.com',
  402. timeout: 5000,
  403. };
  404. `;
  405. const result = extractFromSource('config.ts', code);
  406. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  407. expect(varNode).toBeDefined();
  408. expect(varNode?.isExported).toBe(true);
  409. });
  410. it('should extract exported const with array literal', () => {
  411. const code = `
  412. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  413. `;
  414. const result = extractFromSource('constants.ts', code);
  415. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  416. expect(varNode).toBeDefined();
  417. expect(varNode?.isExported).toBe(true);
  418. });
  419. it('should extract exported const with primitive value', () => {
  420. const code = `
  421. export const MAX_RETRIES = 3;
  422. export const API_VERSION = "v2";
  423. `;
  424. const result = extractFromSource('constants.ts', code);
  425. const variables = result.nodes.filter((n) => n.kind === 'constant');
  426. expect(variables).toHaveLength(2);
  427. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  428. });
  429. it('should NOT duplicate arrow functions as both function and variable', () => {
  430. const code = `
  431. export const useAuth = () => {
  432. return useContext(AuthContext);
  433. };
  434. `;
  435. const result = extractFromSource('hooks.ts', code);
  436. // Should be extracted as function (from arrow function handler), NOT as variable
  437. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  438. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  439. expect(funcNodes).toHaveLength(1);
  440. expect(varNodes).toHaveLength(0);
  441. });
  442. it('should extract non-exported const as non-exported variable', () => {
  443. const code = `
  444. const internalConfig = {
  445. debug: true,
  446. };
  447. `;
  448. const result = extractFromSource('internal.ts', code);
  449. // Non-exported const at file level should be extracted as a constant (not exported)
  450. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  451. expect(varNodes).toHaveLength(1);
  452. expect(varNodes[0]?.isExported).toBeFalsy();
  453. });
  454. it('should extract Zod schema exports', () => {
  455. const code = `
  456. export const userSchema = z.object({
  457. id: z.string(),
  458. name: z.string(),
  459. email: z.string().email(),
  460. });
  461. `;
  462. const result = extractFromSource('schemas.ts', code);
  463. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  464. expect(varNode).toBeDefined();
  465. expect(varNode?.isExported).toBe(true);
  466. });
  467. it('should extract XState machine exports', () => {
  468. const code = `
  469. export const authMachine = createMachine({
  470. id: "auth",
  471. initial: "idle",
  472. states: {
  473. idle: {},
  474. authenticated: {},
  475. },
  476. });
  477. `;
  478. const result = extractFromSource('machine.ts', code);
  479. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  480. expect(varNode).toBeDefined();
  481. expect(varNode?.isExported).toBe(true);
  482. });
  483. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  484. const code = `
  485. import { getTokenMp } from './api/upload';
  486. const token = getTokenMp();
  487. `;
  488. const result = extractFromSource('app.ts', code);
  489. const call = result.unresolvedReferences.find(
  490. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  491. );
  492. expect(call).toBeDefined();
  493. });
  494. });
  495. describe('File Node Extraction', () => {
  496. it('should create a file-kind node for each parsed file', () => {
  497. const code = `
  498. export function greet(name: string): string {
  499. return "Hello " + name;
  500. }
  501. `;
  502. const result = extractFromSource('greeter.ts', code);
  503. const fileNode = result.nodes.find((n) => n.kind === 'file');
  504. expect(fileNode).toBeDefined();
  505. expect(fileNode?.name).toBe('greeter.ts');
  506. expect(fileNode?.filePath).toBe('greeter.ts');
  507. expect(fileNode?.language).toBe('typescript');
  508. expect(fileNode?.startLine).toBe(1);
  509. });
  510. it('should create file nodes for Python files', () => {
  511. const code = `
  512. def main():
  513. pass
  514. `;
  515. const result = extractFromSource('main.py', code);
  516. const fileNode = result.nodes.find((n) => n.kind === 'file');
  517. expect(fileNode).toBeDefined();
  518. expect(fileNode?.name).toBe('main.py');
  519. expect(fileNode?.language).toBe('python');
  520. });
  521. it('should create containment edges from file node to top-level declarations', () => {
  522. const code = `
  523. export function foo() {}
  524. export function bar() {}
  525. `;
  526. const result = extractFromSource('fns.ts', code);
  527. const fileNode = result.nodes.find((n) => n.kind === 'file');
  528. expect(fileNode).toBeDefined();
  529. // There should be contains edges from the file node to each function
  530. const containsEdges = result.edges.filter(
  531. (e) => e.source === fileNode?.id && e.kind === 'contains'
  532. );
  533. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  534. });
  535. });
  536. describe('Python Extraction', () => {
  537. it('should extract function definitions', () => {
  538. const code = `
  539. def calculate_total(items: list, tax_rate: float) -> float:
  540. """Calculate total with tax."""
  541. subtotal = sum(item.price for item in items)
  542. return subtotal * (1 + tax_rate)
  543. `;
  544. const result = extractFromSource('calc.py', code);
  545. const fileNode = result.nodes.find((n) => n.kind === 'file');
  546. expect(fileNode).toBeDefined();
  547. const funcNode = result.nodes.find((n) => n.kind === 'function');
  548. expect(funcNode).toMatchObject({
  549. kind: 'function',
  550. name: 'calculate_total',
  551. language: 'python',
  552. });
  553. });
  554. it('should extract class definitions', () => {
  555. const code = `
  556. class UserService:
  557. """Service for managing users."""
  558. def __init__(self, db):
  559. self.db = db
  560. def get_user(self, user_id: str) -> User:
  561. return self.db.find_user(user_id)
  562. `;
  563. const result = extractFromSource('service.py', code);
  564. const classNode = result.nodes.find((n) => n.kind === 'class');
  565. expect(classNode).toBeDefined();
  566. expect(classNode?.name).toBe('UserService');
  567. });
  568. });
  569. describe('Go Extraction', () => {
  570. it('should extract function declarations', () => {
  571. const code = `
  572. package main
  573. func ProcessOrder(order Order) (Receipt, error) {
  574. // Process the order
  575. return Receipt{}, nil
  576. }
  577. `;
  578. const result = extractFromSource('main.go', code);
  579. const funcNode = result.nodes.find((n) => n.kind === 'function');
  580. expect(funcNode).toBeDefined();
  581. expect(funcNode?.name).toBe('ProcessOrder');
  582. });
  583. it('should extract method declarations', () => {
  584. const code = `
  585. package main
  586. type Service struct {
  587. db *Database
  588. }
  589. func (s *Service) GetUser(id string) (*User, error) {
  590. return s.db.FindUser(id)
  591. }
  592. `;
  593. const result = extractFromSource('service.go', code);
  594. const methodNode = result.nodes.find((n) => n.kind === 'method');
  595. expect(methodNode).toBeDefined();
  596. expect(methodNode?.name).toBe('GetUser');
  597. });
  598. });
  599. describe('Rust Extraction', () => {
  600. it('should extract function declarations', () => {
  601. const code = `
  602. pub fn process_data(input: &str) -> Result<Output, Error> {
  603. // Process data
  604. Ok(Output::new())
  605. }
  606. `;
  607. const result = extractFromSource('lib.rs', code);
  608. const funcNode = result.nodes.find((n) => n.kind === 'function');
  609. expect(funcNode).toBeDefined();
  610. expect(funcNode?.name).toBe('process_data');
  611. expect(funcNode?.visibility).toBe('public');
  612. });
  613. it('should extract struct declarations', () => {
  614. const code = `
  615. pub struct User {
  616. pub id: String,
  617. pub name: String,
  618. email: String,
  619. }
  620. `;
  621. const result = extractFromSource('models.rs', code);
  622. const structNode = result.nodes.find((n) => n.kind === 'struct');
  623. expect(structNode).toBeDefined();
  624. expect(structNode?.name).toBe('User');
  625. });
  626. it('should extract trait declarations', () => {
  627. const code = `
  628. pub trait Repository {
  629. fn find(&self, id: &str) -> Option<Entity>;
  630. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  631. }
  632. `;
  633. const result = extractFromSource('traits.rs', code);
  634. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  635. expect(traitNode).toBeDefined();
  636. expect(traitNode?.name).toBe('Repository');
  637. });
  638. it('should extract impl Trait for Type as implements edges', () => {
  639. const code = `
  640. pub struct MyCache {}
  641. pub trait Cache {
  642. fn get(&self, key: &str) -> Option<String>;
  643. }
  644. impl Cache for MyCache {
  645. fn get(&self, key: &str) -> Option<String> {
  646. None
  647. }
  648. }
  649. `;
  650. const result = extractFromSource('cache.rs', code);
  651. // Should have an unresolved reference for implements
  652. const implRef = result.unresolvedReferences.find(
  653. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  654. );
  655. expect(implRef).toBeDefined();
  656. // The struct MyCache should be the source
  657. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  658. expect(myCacheNode).toBeDefined();
  659. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  660. });
  661. it('should extract trait supertraits as extends references', () => {
  662. const code = `
  663. pub trait Display {}
  664. pub trait Error: Display {
  665. fn description(&self) -> &str;
  666. }
  667. `;
  668. const result = extractFromSource('error.rs', code);
  669. const extendsRef = result.unresolvedReferences.find(
  670. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  671. );
  672. expect(extendsRef).toBeDefined();
  673. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  674. expect(errorTrait).toBeDefined();
  675. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  676. });
  677. it('should not create implements edges for plain impl blocks', () => {
  678. const code = `
  679. pub struct Counter {
  680. count: u32,
  681. }
  682. impl Counter {
  683. pub fn new() -> Counter {
  684. Counter { count: 0 }
  685. }
  686. pub fn increment(&mut self) {
  687. self.count += 1;
  688. }
  689. }
  690. `;
  691. const result = extractFromSource('counter.rs', code);
  692. // Should have no implements references (no trait involved)
  693. const implRefs = result.unresolvedReferences.filter(
  694. (r) => r.referenceKind === 'implements'
  695. );
  696. expect(implRefs).toHaveLength(0);
  697. });
  698. });
  699. describe('Java Extraction', () => {
  700. it('should extract class declarations', () => {
  701. const code = `
  702. public class UserService {
  703. private final UserRepository repository;
  704. public UserService(UserRepository repository) {
  705. this.repository = repository;
  706. }
  707. public User getUser(String id) {
  708. return repository.findById(id);
  709. }
  710. }
  711. `;
  712. const result = extractFromSource('UserService.java', code);
  713. const classNode = result.nodes.find((n) => n.kind === 'class');
  714. expect(classNode).toBeDefined();
  715. expect(classNode?.name).toBe('UserService');
  716. expect(classNode?.visibility).toBe('public');
  717. });
  718. it('should extract method declarations', () => {
  719. const code = `
  720. public class Calculator {
  721. public static int add(int a, int b) {
  722. return a + b;
  723. }
  724. }
  725. `;
  726. const result = extractFromSource('Calculator.java', code);
  727. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  728. expect(methodNode).toBeDefined();
  729. expect(methodNode?.isStatic).toBe(true);
  730. });
  731. it('wraps top-level declarations in a namespace from package_declaration', () => {
  732. const code = `
  733. package com.example.foo;
  734. public class Bar {
  735. public String greet() { return "hi"; }
  736. }
  737. `;
  738. const result = extractFromSource('Bar.java', code);
  739. const ns = result.nodes.find((n) => n.kind === 'namespace');
  740. expect(ns?.name).toBe('com.example.foo');
  741. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  742. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  743. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  744. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  745. });
  746. it('does not wrap when no package is declared', () => {
  747. const code = `
  748. public class Bar {
  749. public String greet() { return "hi"; }
  750. }
  751. `;
  752. const result = extractFromSource('Bar.java', code);
  753. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  754. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  755. expect(cls?.qualifiedName).toBe('Bar');
  756. });
  757. it('extracts anonymous-class overrides from `new T() { ... }`', () => {
  758. // The pattern that breaks the trace through `strategy.foo()` in
  759. // libraries like guava's Splitter: the lambda-returned anonymous
  760. // class overrides abstract methods on the base, but without
  761. // extracting those overrides the interface→impl synthesizer has
  762. // nothing to bridge.
  763. const code = `
  764. package com.example;
  765. abstract class Base {
  766. abstract int compute(int x);
  767. }
  768. public class Factory {
  769. public Base make() {
  770. return new Base() {
  771. @Override
  772. int compute(int x) { return x + 1; }
  773. };
  774. }
  775. }
  776. `;
  777. const result = extractFromSource('Factory.java', code);
  778. const anon = result.nodes.find((n) => n.kind === 'class' && /Base\$anon@/.test(n.name));
  779. expect(anon, 'anonymous Base subclass should be extracted as a class').toBeDefined();
  780. const compute = result.nodes.find(
  781. (n) => n.kind === 'method' && n.name === 'compute' && n.qualifiedName.includes('$anon@')
  782. );
  783. expect(compute, 'override method should be a method on the anon class').toBeDefined();
  784. expect(compute!.qualifiedName).toContain('Factory::make::<Base$anon@');
  785. expect(compute!.qualifiedName.endsWith('::compute')).toBe(true);
  786. // Anon class must extend Base so Phase 5.5 (interface-impl) can bridge.
  787. const extendsRef = result.unresolvedReferences.find(
  788. (r) => r.referenceKind === 'extends' && r.referenceName === 'Base' && r.fromNodeId === anon!.id
  789. );
  790. expect(extendsRef, 'anon class should carry an `extends Base` reference').toBeDefined();
  791. // The enclosing `make` method still emits an instantiates edge to Base —
  792. // anon extraction must not swallow that signal.
  793. const instantiatesRef = result.unresolvedReferences.find(
  794. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Base'
  795. );
  796. expect(instantiatesRef, 'enclosing method should still instantiate Base').toBeDefined();
  797. });
  798. it('extracts anonymous-class overrides inside a lambda body', () => {
  799. // The exact guava pattern: a lambda is passed to a constructor, and the
  800. // lambda body returns `new T() { @Override ... }`. The anon class must
  801. // still surface even though it sits inside a lambda_expression node.
  802. const code = `
  803. package com.example;
  804. interface Strategy {
  805. java.util.Iterator<String> iterator(String s);
  806. }
  807. abstract class BaseIter implements java.util.Iterator<String> {
  808. abstract int separatorStart(int start);
  809. }
  810. public class Splitter {
  811. private final Strategy strategy;
  812. public Splitter(Strategy s) { this.strategy = s; }
  813. public static Splitter on(char c) {
  814. return new Splitter((seq) ->
  815. new BaseIter() {
  816. @Override
  817. int separatorStart(int start) { return start + 1; }
  818. @Override public boolean hasNext() { return false; }
  819. @Override public String next() { return null; }
  820. });
  821. }
  822. }
  823. `;
  824. const result = extractFromSource('Splitter.java', code);
  825. const anon = result.nodes.find((n) => n.kind === 'class' && /BaseIter\$anon@/.test(n.name));
  826. expect(anon, 'anon BaseIter inside the lambda body should be extracted').toBeDefined();
  827. const sepStart = result.nodes.find(
  828. (n) =>
  829. n.kind === 'method' &&
  830. n.name === 'separatorStart' &&
  831. n.qualifiedName.includes('$anon@')
  832. );
  833. expect(sepStart, 'override inside the lambda-returned anon class should be a method node').toBeDefined();
  834. });
  835. });
  836. describe('C# Extraction', () => {
  837. it('should extract class declarations', () => {
  838. const code = `
  839. public class OrderService
  840. {
  841. private readonly IOrderRepository _repository;
  842. public OrderService(IOrderRepository repository)
  843. {
  844. _repository = repository;
  845. }
  846. public async Task<Order> GetOrderAsync(string id)
  847. {
  848. return await _repository.FindByIdAsync(id);
  849. }
  850. }
  851. `;
  852. const result = extractFromSource('OrderService.cs', code);
  853. const classNode = result.nodes.find((n) => n.kind === 'class');
  854. expect(classNode).toBeDefined();
  855. expect(classNode?.name).toBe('OrderService');
  856. expect(classNode?.visibility).toBe('public');
  857. });
  858. });
  859. describe('PHP Extraction', () => {
  860. it('should extract class declarations', () => {
  861. const code = `<?php
  862. class UserController
  863. {
  864. private UserService $userService;
  865. public function __construct(UserService $userService)
  866. {
  867. $this->userService = $userService;
  868. }
  869. public function show(string $id): User
  870. {
  871. return $this->userService->find($id);
  872. }
  873. }
  874. `;
  875. const result = extractFromSource('UserController.php', code);
  876. const classNode = result.nodes.find((n) => n.kind === 'class');
  877. expect(classNode).toBeDefined();
  878. expect(classNode?.name).toBe('UserController');
  879. });
  880. it('should extract class inheritance (extends) and interface implementation', () => {
  881. const code = `<?php
  882. class ChildController extends BaseController implements Serializable, JsonSerializable
  883. {
  884. public function serialize(): string
  885. {
  886. return json_encode($this);
  887. }
  888. }
  889. `;
  890. const result = extractFromSource('ChildController.php', code);
  891. const classNode = result.nodes.find((n) => n.kind === 'class');
  892. expect(classNode).toBeDefined();
  893. expect(classNode?.name).toBe('ChildController');
  894. const extendsRef = result.unresolvedReferences.find(
  895. (r) => r.referenceKind === 'extends'
  896. );
  897. expect(extendsRef).toBeDefined();
  898. expect(extendsRef?.referenceName).toBe('BaseController');
  899. const implementsRefs = result.unresolvedReferences.filter(
  900. (r) => r.referenceKind === 'implements'
  901. );
  902. expect(implementsRefs.length).toBe(2);
  903. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  904. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  905. });
  906. });
  907. describe('Swift Extraction', () => {
  908. it('should extract class declarations', () => {
  909. const code = `
  910. public class NetworkManager {
  911. private let session: URLSession
  912. public init(session: URLSession = .shared) {
  913. self.session = session
  914. }
  915. public func fetchData(from url: URL) async throws -> Data {
  916. let (data, _) = try await session.data(from: url)
  917. return data
  918. }
  919. }
  920. `;
  921. const result = extractFromSource('NetworkManager.swift', code);
  922. const classNode = result.nodes.find((n) => n.kind === 'class');
  923. expect(classNode).toBeDefined();
  924. expect(classNode?.name).toBe('NetworkManager');
  925. });
  926. it('should extract function declarations', () => {
  927. const code = `
  928. func calculateSum(_ numbers: [Int]) -> Int {
  929. return numbers.reduce(0, +)
  930. }
  931. public func formatCurrency(amount: Double) -> String {
  932. return String(format: "$%.2f", amount)
  933. }
  934. `;
  935. const result = extractFromSource('utils.swift', code);
  936. const functions = result.nodes.filter((n) => n.kind === 'function');
  937. expect(functions.length).toBeGreaterThanOrEqual(1);
  938. });
  939. it('should extract struct declarations', () => {
  940. const code = `
  941. public struct User {
  942. let id: UUID
  943. var name: String
  944. var email: String
  945. func displayName() -> String {
  946. return name
  947. }
  948. }
  949. `;
  950. const result = extractFromSource('User.swift', code);
  951. const structNode = result.nodes.find((n) => n.kind === 'struct');
  952. expect(structNode).toBeDefined();
  953. expect(structNode?.name).toBe('User');
  954. });
  955. it('should extract protocol declarations', () => {
  956. const code = `
  957. public protocol Repository {
  958. associatedtype Entity
  959. func find(id: String) async throws -> Entity?
  960. func save(_ entity: Entity) async throws
  961. }
  962. `;
  963. const result = extractFromSource('Repository.swift', code);
  964. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  965. expect(protocolNode).toBeDefined();
  966. expect(protocolNode?.name).toBe('Repository');
  967. });
  968. it('should extract class inheritance and protocol conformance', () => {
  969. const code = `
  970. class DataRequest: Request {
  971. func validate() {}
  972. }
  973. class UploadRequest: DataRequest, Sendable {
  974. func upload() {}
  975. }
  976. enum AFError: Error {
  977. case invalidURL
  978. }
  979. struct HTTPMethod: RawRepresentable {
  980. let rawValue: String
  981. }
  982. protocol UploadConvertible: URLRequestConvertible {
  983. func asURLRequest() throws -> URLRequest
  984. }
  985. `;
  986. const result = extractFromSource('Inheritance.swift', code);
  987. const extendsRefs = result.unresolvedReferences.filter(
  988. (r) => r.referenceKind === 'extends'
  989. );
  990. // DataRequest extends Request
  991. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  992. // UploadRequest extends DataRequest and Sendable
  993. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  994. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  995. // AFError extends Error
  996. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  997. // HTTPMethod extends RawRepresentable
  998. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  999. // UploadConvertible extends URLRequestConvertible
  1000. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  1001. });
  1002. });
  1003. describe('Kotlin Extraction', () => {
  1004. it('should extract class declarations', () => {
  1005. const code = `
  1006. class UserRepository(private val database: Database) {
  1007. fun findById(id: String): User? {
  1008. return database.query("SELECT * FROM users WHERE id = ?", id)
  1009. }
  1010. suspend fun save(user: User) {
  1011. database.insert(user)
  1012. }
  1013. }
  1014. `;
  1015. const result = extractFromSource('UserRepository.kt', code);
  1016. const classNode = result.nodes.find((n) => n.kind === 'class');
  1017. expect(classNode).toBeDefined();
  1018. expect(classNode?.name).toBe('UserRepository');
  1019. });
  1020. it('should extract function declarations', () => {
  1021. const code = `
  1022. fun calculateTotal(items: List<Item>): Double {
  1023. return items.sumOf { it.price }
  1024. }
  1025. suspend fun fetchUserData(userId: String): User {
  1026. return api.getUser(userId)
  1027. }
  1028. `;
  1029. const result = extractFromSource('utils.kt', code);
  1030. const functions = result.nodes.filter((n) => n.kind === 'function');
  1031. expect(functions.length).toBeGreaterThanOrEqual(1);
  1032. });
  1033. it('should detect suspend functions as async', () => {
  1034. const code = `
  1035. suspend fun loadData(): List<String> {
  1036. delay(1000)
  1037. return listOf("a", "b", "c")
  1038. }
  1039. `;
  1040. const result = extractFromSource('loader.kt', code);
  1041. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1042. expect(funcNode).toBeDefined();
  1043. expect(funcNode?.isAsync).toBe(true);
  1044. });
  1045. it('should extract fun interface declarations', () => {
  1046. const code = `
  1047. fun interface OnObjectRetainedListener {
  1048. fun onObjectRetained()
  1049. }
  1050. `;
  1051. const result = extractFromSource('listener.kt', code);
  1052. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1053. expect(ifaceNode).toBeDefined();
  1054. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  1055. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1056. expect(methodNode).toBeDefined();
  1057. expect(methodNode?.name).toBe('onObjectRetained');
  1058. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  1059. });
  1060. it('should extract complex fun interface with nested classes', () => {
  1061. const code = `
  1062. fun interface EventListener {
  1063. fun onEvent(event: Event)
  1064. sealed class Event {
  1065. class DumpingHeap : Event()
  1066. }
  1067. }
  1068. `;
  1069. const result = extractFromSource('events.kt', code);
  1070. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1071. expect(ifaceNode).toBeDefined();
  1072. expect(ifaceNode?.name).toBe('EventListener');
  1073. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  1074. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  1075. expect(eventClass).toBeDefined();
  1076. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  1077. expect(dumpingHeap).toBeDefined();
  1078. });
  1079. it('should not affect regular function declarations', () => {
  1080. const code = `
  1081. fun interface MyCallback {
  1082. fun invoke(value: Int)
  1083. }
  1084. fun regularFunction(): String {
  1085. return "hello"
  1086. }
  1087. `;
  1088. const result = extractFromSource('mixed.kt', code);
  1089. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1090. expect(ifaceNode).toBeDefined();
  1091. expect(ifaceNode?.name).toBe('MyCallback');
  1092. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1093. expect(funcNode).toBeDefined();
  1094. expect(funcNode?.name).toBe('regularFunction');
  1095. });
  1096. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  1097. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  1098. // misparse: function_declaration > ERROR("interface Name {") instead of
  1099. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  1100. const code = `
  1101. import java.io.IOException
  1102. fun interface Interceptor {
  1103. @Throws(IOException::class)
  1104. fun intercept(chain: Chain): Response
  1105. }
  1106. `;
  1107. const result = extractFromSource('interceptor.kt', code);
  1108. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1109. expect(ifaceNode).toBeDefined();
  1110. expect(ifaceNode?.name).toBe('Interceptor');
  1111. });
  1112. it('should extract methods from interface with nested fun interface', () => {
  1113. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  1114. // the parent body as ERROR. Methods inside should still be extracted.
  1115. const code = `
  1116. interface WebSocket {
  1117. fun request(): Request
  1118. fun send(text: String): Boolean
  1119. fun cancel()
  1120. fun interface Factory {
  1121. fun newWebSocket(request: Request): WebSocket
  1122. }
  1123. }
  1124. `;
  1125. const result = extractFromSource('websocket.kt', code);
  1126. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  1127. expect(wsIface).toBeDefined();
  1128. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  1129. const methodNames = methods.map((m) => m.name);
  1130. expect(methodNames).toContain('request');
  1131. expect(methodNames).toContain('send');
  1132. expect(methodNames).toContain('cancel');
  1133. });
  1134. it('wraps top-level declarations in a namespace from package_header', () => {
  1135. const code = `
  1136. package com.example.foo
  1137. class Bar {
  1138. fun greet(): String = "hi"
  1139. }
  1140. fun util(): Int = 42
  1141. `;
  1142. const result = extractFromSource('Bar.kt', code);
  1143. const ns = result.nodes.find((n) => n.kind === 'namespace');
  1144. expect(ns?.name).toBe('com.example.foo');
  1145. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1146. expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
  1147. const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
  1148. expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
  1149. const util = result.nodes.find((n) => n.kind === 'function' && n.name === 'util');
  1150. expect(util?.qualifiedName).toBe('com.example.foo::util');
  1151. });
  1152. it('handles a single-segment package', () => {
  1153. const code = `
  1154. package foo
  1155. class Bar
  1156. `;
  1157. const result = extractFromSource('Bar.kt', code);
  1158. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1159. expect(cls?.qualifiedName).toBe('foo::Bar');
  1160. });
  1161. it('does not wrap when no package is declared', () => {
  1162. const code = `
  1163. class Bar {
  1164. fun greet() = "hi"
  1165. }
  1166. `;
  1167. const result = extractFromSource('Bar.kt', code);
  1168. expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
  1169. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
  1170. expect(cls?.qualifiedName).toBe('Bar');
  1171. });
  1172. });
  1173. describe('Dart Extraction', () => {
  1174. it('should extract class declarations', () => {
  1175. const code = `
  1176. class UserService {
  1177. final Database _db;
  1178. Future<User> findById(String id) async {
  1179. return await _db.query(id);
  1180. }
  1181. void _privateMethod() {}
  1182. }
  1183. `;
  1184. const result = extractFromSource('service.dart', code);
  1185. const classNode = result.nodes.find((n) => n.kind === 'class');
  1186. expect(classNode).toBeDefined();
  1187. expect(classNode?.name).toBe('UserService');
  1188. expect(classNode?.visibility).toBe('public');
  1189. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1190. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1191. const findById = methodNodes.find((m) => m.name === 'findById');
  1192. expect(findById).toBeDefined();
  1193. expect(findById?.isAsync).toBe(true);
  1194. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1195. expect(privateMethod).toBeDefined();
  1196. expect(privateMethod?.visibility).toBe('private');
  1197. // Dart models a method body as a SIBLING of the signature, so the method
  1198. // node must be extended to span its body (not just the signature line) —
  1199. // required for body-level analysis (callees, the callback synthesizer).
  1200. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1201. });
  1202. it('should extract top-level function declarations', () => {
  1203. const code = `
  1204. void topLevelFunction(String name) {
  1205. print(name);
  1206. }
  1207. `;
  1208. const result = extractFromSource('utils.dart', code);
  1209. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1210. expect(funcNode).toBeDefined();
  1211. expect(funcNode?.name).toBe('topLevelFunction');
  1212. expect(funcNode?.language).toBe('dart');
  1213. });
  1214. it('should extract enum declarations', () => {
  1215. const code = `
  1216. enum Status { active, inactive, pending }
  1217. `;
  1218. const result = extractFromSource('models.dart', code);
  1219. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1220. expect(enumNode).toBeDefined();
  1221. expect(enumNode?.name).toBe('Status');
  1222. });
  1223. it('should extract mixin declarations', () => {
  1224. const code = `
  1225. mixin LoggerMixin {
  1226. void log(String message) {}
  1227. }
  1228. `;
  1229. const result = extractFromSource('mixins.dart', code);
  1230. const classNode = result.nodes.find((n) => n.kind === 'class');
  1231. expect(classNode).toBeDefined();
  1232. expect(classNode?.name).toBe('LoggerMixin');
  1233. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1234. expect(methodNode).toBeDefined();
  1235. expect(methodNode?.name).toBe('log');
  1236. });
  1237. it('should extract extension declarations', () => {
  1238. const code = `
  1239. extension StringExt on String {
  1240. bool get isBlank => trim().isEmpty;
  1241. }
  1242. `;
  1243. const result = extractFromSource('extensions.dart', code);
  1244. const classNode = result.nodes.find((n) => n.kind === 'class');
  1245. expect(classNode).toBeDefined();
  1246. expect(classNode?.name).toBe('StringExt');
  1247. });
  1248. it('should detect static methods', () => {
  1249. const code = `
  1250. class Utils {
  1251. static void doWork() {}
  1252. }
  1253. `;
  1254. const result = extractFromSource('utils.dart', code);
  1255. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1256. expect(methodNode).toBeDefined();
  1257. expect(methodNode?.name).toBe('doWork');
  1258. expect(methodNode?.isStatic).toBe(true);
  1259. });
  1260. it('should detect async functions', () => {
  1261. const code = `
  1262. Future<String> fetchData() async {
  1263. return await http.get('/data');
  1264. }
  1265. `;
  1266. const result = extractFromSource('api.dart', code);
  1267. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1268. expect(funcNode).toBeDefined();
  1269. expect(funcNode?.name).toBe('fetchData');
  1270. expect(funcNode?.isAsync).toBe(true);
  1271. });
  1272. it('should detect private visibility via underscore convention', () => {
  1273. const code = `
  1274. void _privateHelper() {}
  1275. void publicFunction() {}
  1276. `;
  1277. const result = extractFromSource('helpers.dart', code);
  1278. const functions = result.nodes.filter((n) => n.kind === 'function');
  1279. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1280. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1281. expect(privateFunc?.visibility).toBe('private');
  1282. expect(publicFunc?.visibility).toBe('public');
  1283. });
  1284. });
  1285. describe('Import Extraction', () => {
  1286. describe('TypeScript/JavaScript imports', () => {
  1287. it('should extract default imports', () => {
  1288. const code = `import React from 'react';`;
  1289. const result = extractFromSource('app.tsx', code);
  1290. const importNode = result.nodes.find((n) => n.kind === 'import');
  1291. expect(importNode).toBeDefined();
  1292. expect(importNode?.name).toBe('react');
  1293. expect(importNode?.signature).toBe("import React from 'react';");
  1294. });
  1295. it('should extract named imports', () => {
  1296. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1297. const result = extractFromSource('icons.tsx', code);
  1298. const importNode = result.nodes.find((n) => n.kind === 'import');
  1299. expect(importNode).toBeDefined();
  1300. expect(importNode?.name).toBe('@phosphor-icons/react');
  1301. expect(importNode?.signature).toContain('Bug');
  1302. expect(importNode?.signature).toContain('Database');
  1303. });
  1304. it('should extract namespace imports', () => {
  1305. const code = `import * as Icons from '@phosphor-icons/react';`;
  1306. const result = extractFromSource('icons.tsx', code);
  1307. const importNode = result.nodes.find((n) => n.kind === 'import');
  1308. expect(importNode).toBeDefined();
  1309. expect(importNode?.name).toBe('@phosphor-icons/react');
  1310. expect(importNode?.signature).toContain('* as Icons');
  1311. });
  1312. it('should extract side-effect imports', () => {
  1313. const code = `import './styles.css';`;
  1314. const result = extractFromSource('app.tsx', code);
  1315. const importNode = result.nodes.find((n) => n.kind === 'import');
  1316. expect(importNode).toBeDefined();
  1317. expect(importNode?.name).toBe('./styles.css');
  1318. });
  1319. it('should extract mixed imports (default + named)', () => {
  1320. const code = `import React, { useState, useEffect } from 'react';`;
  1321. const result = extractFromSource('app.tsx', code);
  1322. const importNode = result.nodes.find((n) => n.kind === 'import');
  1323. expect(importNode).toBeDefined();
  1324. expect(importNode?.name).toBe('react');
  1325. expect(importNode?.signature).toContain('React');
  1326. expect(importNode?.signature).toContain('useState');
  1327. expect(importNode?.signature).toContain('useEffect');
  1328. });
  1329. it('should extract multiple import statements', () => {
  1330. const code = `
  1331. import React from 'react';
  1332. import { Button } from './components';
  1333. import './styles.css';
  1334. `;
  1335. const result = extractFromSource('app.tsx', code);
  1336. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1337. expect(importNodes.length).toBe(3);
  1338. const names = importNodes.map((n) => n.name);
  1339. expect(names).toContain('react');
  1340. expect(names).toContain('./components');
  1341. expect(names).toContain('./styles.css');
  1342. });
  1343. it('should extract type imports', () => {
  1344. const code = `import type { FC, ReactNode } from 'react';`;
  1345. const result = extractFromSource('types.ts', code);
  1346. const importNode = result.nodes.find((n) => n.kind === 'import');
  1347. expect(importNode).toBeDefined();
  1348. expect(importNode?.name).toBe('react');
  1349. expect(importNode?.signature).toContain('type');
  1350. expect(importNode?.signature).toContain('FC');
  1351. });
  1352. it('should extract aliased named imports', () => {
  1353. const code = `import { useState as useStateAlias } from 'react';`;
  1354. const result = extractFromSource('hooks.ts', code);
  1355. const importNode = result.nodes.find((n) => n.kind === 'import');
  1356. expect(importNode).toBeDefined();
  1357. expect(importNode?.name).toBe('react');
  1358. expect(importNode?.signature).toContain('useState');
  1359. expect(importNode?.signature).toContain('useStateAlias');
  1360. });
  1361. it('should extract relative path imports', () => {
  1362. const code = `import { helper } from '../utils/helper';`;
  1363. const result = extractFromSource('components/Button.tsx', code);
  1364. const importNode = result.nodes.find((n) => n.kind === 'import');
  1365. expect(importNode).toBeDefined();
  1366. expect(importNode?.name).toBe('../utils/helper');
  1367. expect(importNode?.signature).toContain('helper');
  1368. });
  1369. });
  1370. describe('Python imports', () => {
  1371. it('should extract simple import statement', () => {
  1372. const code = `import json`;
  1373. const result = extractFromSource('utils.py', code);
  1374. const importNode = result.nodes.find((n) => n.kind === 'import');
  1375. expect(importNode).toBeDefined();
  1376. expect(importNode?.name).toBe('json');
  1377. });
  1378. it('should extract from import statement', () => {
  1379. const code = `from os import path`;
  1380. const result = extractFromSource('utils.py', code);
  1381. const importNode = result.nodes.find((n) => n.kind === 'import');
  1382. expect(importNode).toBeDefined();
  1383. expect(importNode?.name).toBe('os');
  1384. expect(importNode?.signature).toContain('path');
  1385. });
  1386. it('should extract multiple imports from same module', () => {
  1387. const code = `from typing import List, Dict, Optional`;
  1388. const result = extractFromSource('types.py', code);
  1389. const importNode = result.nodes.find((n) => n.kind === 'import');
  1390. expect(importNode).toBeDefined();
  1391. expect(importNode?.name).toBe('typing');
  1392. expect(importNode?.signature).toContain('List');
  1393. expect(importNode?.signature).toContain('Dict');
  1394. });
  1395. it('should extract multiple import statements', () => {
  1396. const code = `
  1397. import os
  1398. import sys
  1399. `;
  1400. const result = extractFromSource('main.py', code);
  1401. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1402. expect(importNodes.length).toBe(2);
  1403. const names = importNodes.map((n) => n.name);
  1404. expect(names).toContain('os');
  1405. expect(names).toContain('sys');
  1406. });
  1407. it('should extract aliased import', () => {
  1408. const code = `import numpy as np`;
  1409. const result = extractFromSource('data.py', code);
  1410. const importNode = result.nodes.find((n) => n.kind === 'import');
  1411. expect(importNode).toBeDefined();
  1412. expect(importNode?.name).toBe('numpy');
  1413. expect(importNode?.signature).toContain('as np');
  1414. });
  1415. it('should extract relative import', () => {
  1416. const code = `from .utils import helper`;
  1417. const result = extractFromSource('module.py', code);
  1418. const importNode = result.nodes.find((n) => n.kind === 'import');
  1419. expect(importNode).toBeDefined();
  1420. expect(importNode?.name).toBe('.utils');
  1421. expect(importNode?.signature).toContain('helper');
  1422. });
  1423. it('should extract wildcard import', () => {
  1424. const code = `from typing import *`;
  1425. const result = extractFromSource('types.py', code);
  1426. const importNode = result.nodes.find((n) => n.kind === 'import');
  1427. expect(importNode).toBeDefined();
  1428. expect(importNode?.name).toBe('typing');
  1429. expect(importNode?.signature).toContain('*');
  1430. });
  1431. });
  1432. describe('Rust imports', () => {
  1433. it('should extract simple use declaration', () => {
  1434. const code = `use std::io;`;
  1435. const result = extractFromSource('main.rs', code);
  1436. const importNode = result.nodes.find((n) => n.kind === 'import');
  1437. expect(importNode).toBeDefined();
  1438. expect(importNode?.name).toBe('std');
  1439. expect(importNode?.signature).toBe('use std::io;');
  1440. });
  1441. it('should extract scoped use list', () => {
  1442. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1443. const result = extractFromSource('main.rs', code);
  1444. const importNode = result.nodes.find((n) => n.kind === 'import');
  1445. expect(importNode).toBeDefined();
  1446. expect(importNode?.name).toBe('std');
  1447. expect(importNode?.signature).toContain('ffi::OsStr');
  1448. expect(importNode?.signature).toContain('path::Path');
  1449. });
  1450. it('should extract crate imports', () => {
  1451. const code = `use crate::error::Error;`;
  1452. const result = extractFromSource('lib.rs', code);
  1453. const importNode = result.nodes.find((n) => n.kind === 'import');
  1454. expect(importNode).toBeDefined();
  1455. expect(importNode?.name).toBe('crate');
  1456. });
  1457. it('should extract super imports', () => {
  1458. const code = `use super::utils;`;
  1459. const result = extractFromSource('submod.rs', code);
  1460. const importNode = result.nodes.find((n) => n.kind === 'import');
  1461. expect(importNode).toBeDefined();
  1462. expect(importNode?.name).toBe('super');
  1463. });
  1464. it('should extract external crate imports', () => {
  1465. const code = `use serde::{Serialize, Deserialize};`;
  1466. const result = extractFromSource('types.rs', code);
  1467. const importNode = result.nodes.find((n) => n.kind === 'import');
  1468. expect(importNode).toBeDefined();
  1469. expect(importNode?.name).toBe('serde');
  1470. expect(importNode?.signature).toContain('Serialize');
  1471. expect(importNode?.signature).toContain('Deserialize');
  1472. });
  1473. });
  1474. describe('Go imports', () => {
  1475. it('should extract single import', () => {
  1476. const code = `
  1477. package main
  1478. import "fmt"
  1479. `;
  1480. const result = extractFromSource('main.go', code);
  1481. const importNode = result.nodes.find((n) => n.kind === 'import');
  1482. expect(importNode).toBeDefined();
  1483. expect(importNode?.name).toBe('fmt');
  1484. });
  1485. it('should extract grouped imports', () => {
  1486. const code = `
  1487. package main
  1488. import (
  1489. "fmt"
  1490. "os"
  1491. "encoding/json"
  1492. )
  1493. `;
  1494. const result = extractFromSource('main.go', code);
  1495. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1496. expect(importNodes.length).toBe(3);
  1497. const names = importNodes.map((n) => n.name);
  1498. expect(names).toContain('fmt');
  1499. expect(names).toContain('os');
  1500. expect(names).toContain('encoding/json');
  1501. });
  1502. it('should extract aliased import', () => {
  1503. const code = `
  1504. package main
  1505. import f "fmt"
  1506. `;
  1507. const result = extractFromSource('main.go', code);
  1508. const importNode = result.nodes.find((n) => n.kind === 'import');
  1509. expect(importNode).toBeDefined();
  1510. expect(importNode?.name).toBe('fmt');
  1511. expect(importNode?.signature).toContain('f');
  1512. });
  1513. it('should extract dot import', () => {
  1514. const code = `
  1515. package main
  1516. import . "math"
  1517. `;
  1518. const result = extractFromSource('main.go', code);
  1519. const importNode = result.nodes.find((n) => n.kind === 'import');
  1520. expect(importNode).toBeDefined();
  1521. expect(importNode?.name).toBe('math');
  1522. expect(importNode?.signature).toContain('.');
  1523. });
  1524. it('should extract blank import', () => {
  1525. const code = `
  1526. package main
  1527. import _ "github.com/go-sql-driver/mysql"
  1528. `;
  1529. const result = extractFromSource('main.go', code);
  1530. const importNode = result.nodes.find((n) => n.kind === 'import');
  1531. expect(importNode).toBeDefined();
  1532. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1533. expect(importNode?.signature).toContain('_');
  1534. });
  1535. });
  1536. describe('Swift imports', () => {
  1537. it('should extract simple import', () => {
  1538. const code = `import Foundation`;
  1539. const result = extractFromSource('main.swift', code);
  1540. const importNode = result.nodes.find((n) => n.kind === 'import');
  1541. expect(importNode).toBeDefined();
  1542. expect(importNode?.name).toBe('Foundation');
  1543. expect(importNode?.signature).toBe('import Foundation');
  1544. });
  1545. it('should extract @testable import', () => {
  1546. const code = `@testable import Alamofire`;
  1547. const result = extractFromSource('Tests.swift', code);
  1548. const importNode = result.nodes.find((n) => n.kind === 'import');
  1549. expect(importNode).toBeDefined();
  1550. expect(importNode?.name).toBe('Alamofire');
  1551. expect(importNode?.signature).toContain('@testable');
  1552. });
  1553. it('should extract @preconcurrency import', () => {
  1554. const code = `@preconcurrency import Security`;
  1555. const result = extractFromSource('Auth.swift', code);
  1556. const importNode = result.nodes.find((n) => n.kind === 'import');
  1557. expect(importNode).toBeDefined();
  1558. expect(importNode?.name).toBe('Security');
  1559. });
  1560. it('should extract multiple imports', () => {
  1561. const code = `
  1562. import Foundation
  1563. import UIKit
  1564. import Alamofire
  1565. `;
  1566. const result = extractFromSource('App.swift', code);
  1567. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1568. expect(importNodes.length).toBe(3);
  1569. const names = importNodes.map((n) => n.name);
  1570. expect(names).toContain('Foundation');
  1571. expect(names).toContain('UIKit');
  1572. expect(names).toContain('Alamofire');
  1573. });
  1574. });
  1575. describe('Kotlin imports', () => {
  1576. it('should extract simple import', () => {
  1577. const code = `import java.io.IOException`;
  1578. const result = extractFromSource('Main.kt', code);
  1579. const importNode = result.nodes.find((n) => n.kind === 'import');
  1580. expect(importNode).toBeDefined();
  1581. expect(importNode?.name).toBe('java.io.IOException');
  1582. expect(importNode?.signature).toBe('import java.io.IOException');
  1583. });
  1584. it('should extract aliased import', () => {
  1585. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1586. const result = extractFromSource('Utils.kt', code);
  1587. const importNode = result.nodes.find((n) => n.kind === 'import');
  1588. expect(importNode).toBeDefined();
  1589. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1590. expect(importNode?.signature).toContain('as RequestBuilder');
  1591. });
  1592. it('should extract wildcard import', () => {
  1593. const code = `import java.util.concurrent.TimeUnit.*`;
  1594. const result = extractFromSource('Time.kt', code);
  1595. const importNode = result.nodes.find((n) => n.kind === 'import');
  1596. expect(importNode).toBeDefined();
  1597. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1598. expect(importNode?.signature).toContain('.*');
  1599. });
  1600. it('should extract multiple imports', () => {
  1601. const code = `
  1602. import java.io.IOException
  1603. import kotlin.test.assertFailsWith
  1604. import okhttp3.OkHttpClient
  1605. `;
  1606. const result = extractFromSource('Test.kt', code);
  1607. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1608. expect(importNodes.length).toBe(3);
  1609. const names = importNodes.map((n) => n.name);
  1610. expect(names).toContain('java.io.IOException');
  1611. expect(names).toContain('kotlin.test.assertFailsWith');
  1612. expect(names).toContain('okhttp3.OkHttpClient');
  1613. });
  1614. });
  1615. describe('Java imports', () => {
  1616. it('should extract simple import', () => {
  1617. const code = `import java.util.List;`;
  1618. const result = extractFromSource('Main.java', code);
  1619. const importNode = result.nodes.find((n) => n.kind === 'import');
  1620. expect(importNode).toBeDefined();
  1621. expect(importNode?.name).toBe('java.util.List');
  1622. expect(importNode?.signature).toBe('import java.util.List;');
  1623. });
  1624. it('should extract static import', () => {
  1625. const code = `import static java.util.Collections.emptyList;`;
  1626. const result = extractFromSource('Utils.java', code);
  1627. const importNode = result.nodes.find((n) => n.kind === 'import');
  1628. expect(importNode).toBeDefined();
  1629. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1630. expect(importNode?.signature).toContain('static');
  1631. });
  1632. it('should extract wildcard import', () => {
  1633. const code = `import java.util.*;`;
  1634. const result = extractFromSource('App.java', code);
  1635. const importNode = result.nodes.find((n) => n.kind === 'import');
  1636. expect(importNode).toBeDefined();
  1637. expect(importNode?.name).toBe('java.util');
  1638. expect(importNode?.signature).toContain('.*');
  1639. });
  1640. it('should extract nested class import', () => {
  1641. const code = `import java.util.Map.Entry;`;
  1642. const result = extractFromSource('MapUtil.java', code);
  1643. const importNode = result.nodes.find((n) => n.kind === 'import');
  1644. expect(importNode).toBeDefined();
  1645. expect(importNode?.name).toBe('java.util.Map.Entry');
  1646. });
  1647. it('should extract multiple imports', () => {
  1648. const code = `
  1649. import java.util.List;
  1650. import java.util.Map;
  1651. import java.io.IOException;
  1652. `;
  1653. const result = extractFromSource('Service.java', code);
  1654. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1655. expect(importNodes.length).toBe(3);
  1656. const names = importNodes.map((n) => n.name);
  1657. expect(names).toContain('java.util.List');
  1658. expect(names).toContain('java.util.Map');
  1659. expect(names).toContain('java.io.IOException');
  1660. });
  1661. });
  1662. describe('C# imports', () => {
  1663. it('should extract simple using', () => {
  1664. const code = `using System;`;
  1665. const result = extractFromSource('Program.cs', code);
  1666. const importNode = result.nodes.find((n) => n.kind === 'import');
  1667. expect(importNode).toBeDefined();
  1668. expect(importNode?.name).toBe('System');
  1669. expect(importNode?.signature).toBe('using System;');
  1670. });
  1671. it('should extract qualified using', () => {
  1672. const code = `using System.Collections.Generic;`;
  1673. const result = extractFromSource('Utils.cs', code);
  1674. const importNode = result.nodes.find((n) => n.kind === 'import');
  1675. expect(importNode).toBeDefined();
  1676. expect(importNode?.name).toBe('System.Collections.Generic');
  1677. });
  1678. it('should extract static using', () => {
  1679. const code = `using static System.Console;`;
  1680. const result = extractFromSource('App.cs', code);
  1681. const importNode = result.nodes.find((n) => n.kind === 'import');
  1682. expect(importNode).toBeDefined();
  1683. expect(importNode?.name).toBe('System.Console');
  1684. expect(importNode?.signature).toContain('static');
  1685. });
  1686. it('should extract alias using', () => {
  1687. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1688. const result = extractFromSource('Types.cs', code);
  1689. const importNode = result.nodes.find((n) => n.kind === 'import');
  1690. expect(importNode).toBeDefined();
  1691. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1692. expect(importNode?.signature).toContain('MyList =');
  1693. });
  1694. it('should extract multiple usings', () => {
  1695. const code = `
  1696. using System;
  1697. using System.Threading.Tasks;
  1698. using Microsoft.Extensions.DependencyInjection;
  1699. `;
  1700. const result = extractFromSource('Service.cs', code);
  1701. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1702. expect(importNodes.length).toBe(3);
  1703. const names = importNodes.map((n) => n.name);
  1704. expect(names).toContain('System');
  1705. expect(names).toContain('System.Threading.Tasks');
  1706. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1707. });
  1708. });
  1709. describe('PHP imports', () => {
  1710. it('should extract simple use', () => {
  1711. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1712. const result = extractFromSource('Test.php', code);
  1713. const importNode = result.nodes.find((n) => n.kind === 'import');
  1714. expect(importNode).toBeDefined();
  1715. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1716. });
  1717. it('should extract aliased use', () => {
  1718. const code = `<?php use Mockery as m;`;
  1719. const result = extractFromSource('Test.php', code);
  1720. const importNode = result.nodes.find((n) => n.kind === 'import');
  1721. expect(importNode).toBeDefined();
  1722. expect(importNode?.name).toBe('Mockery');
  1723. expect(importNode?.signature).toContain('as m');
  1724. });
  1725. it('should extract function use', () => {
  1726. const code = `<?php use function Illuminate\\Support\\env;`;
  1727. const result = extractFromSource('helpers.php', code);
  1728. const importNode = result.nodes.find((n) => n.kind === 'import');
  1729. expect(importNode).toBeDefined();
  1730. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1731. expect(importNode?.signature).toContain('function');
  1732. });
  1733. it('should extract grouped use', () => {
  1734. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1735. const result = extractFromSource('Models.php', code);
  1736. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1737. expect(importNodes.length).toBe(2);
  1738. const names = importNodes.map((n) => n.name);
  1739. expect(names).toContain('Illuminate\\Database\\Model');
  1740. expect(names).toContain('Illuminate\\Database\\Builder');
  1741. });
  1742. it('should extract multiple uses', () => {
  1743. const code = `<?php
  1744. use Illuminate\\Support\\Collection;
  1745. use Illuminate\\Support\\Str;
  1746. use Closure;
  1747. `;
  1748. const result = extractFromSource('Service.php', code);
  1749. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1750. expect(importNodes.length).toBe(3);
  1751. const names = importNodes.map((n) => n.name);
  1752. expect(names).toContain('Illuminate\\Support\\Collection');
  1753. expect(names).toContain('Illuminate\\Support\\Str');
  1754. expect(names).toContain('Closure');
  1755. });
  1756. });
  1757. describe('Ruby imports', () => {
  1758. it('should extract require', () => {
  1759. const code = `require 'json'`;
  1760. const result = extractFromSource('app.rb', code);
  1761. const importNode = result.nodes.find((n) => n.kind === 'import');
  1762. expect(importNode).toBeDefined();
  1763. expect(importNode?.name).toBe('json');
  1764. expect(importNode?.signature).toBe("require 'json'");
  1765. });
  1766. it('should extract require with path', () => {
  1767. const code = `require 'active_support/core_ext/string'`;
  1768. const result = extractFromSource('config.rb', code);
  1769. const importNode = result.nodes.find((n) => n.kind === 'import');
  1770. expect(importNode).toBeDefined();
  1771. expect(importNode?.name).toBe('active_support/core_ext/string');
  1772. });
  1773. it('should extract require_relative', () => {
  1774. const code = `require_relative '../test_helper'`;
  1775. const result = extractFromSource('test/my_test.rb', code);
  1776. const importNode = result.nodes.find((n) => n.kind === 'import');
  1777. expect(importNode).toBeDefined();
  1778. expect(importNode?.name).toBe('../test_helper');
  1779. expect(importNode?.signature).toContain('require_relative');
  1780. });
  1781. it('should not extract non-require calls', () => {
  1782. const code = `puts 'hello'`;
  1783. const result = extractFromSource('app.rb', code);
  1784. const importNode = result.nodes.find((n) => n.kind === 'import');
  1785. expect(importNode).toBeUndefined();
  1786. });
  1787. it('should extract multiple requires', () => {
  1788. const code = `
  1789. require 'json'
  1790. require 'yaml'
  1791. require_relative 'helper'
  1792. `;
  1793. const result = extractFromSource('lib.rb', code);
  1794. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1795. expect(importNodes.length).toBe(3);
  1796. const names = importNodes.map((n) => n.name);
  1797. expect(names).toContain('json');
  1798. expect(names).toContain('yaml');
  1799. expect(names).toContain('helper');
  1800. });
  1801. });
  1802. describe('Ruby modules', () => {
  1803. it('should extract module as module node with containment', () => {
  1804. const code = `
  1805. module CachedCounting
  1806. def self.disable
  1807. @enabled = false
  1808. end
  1809. def perform_increment!(key, count)
  1810. write_cache!(key, count)
  1811. end
  1812. end
  1813. `;
  1814. const result = extractFromSource('concerns/cached_counting.rb', code);
  1815. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1816. expect(moduleNode).toBeDefined();
  1817. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1818. // Methods inside module should have module-qualified names
  1819. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1820. expect(disableMethod).toBeDefined();
  1821. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1822. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1823. expect(incrementMethod).toBeDefined();
  1824. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1825. // Containment edge from module to methods
  1826. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1827. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1828. });
  1829. it('should handle nested modules with classes', () => {
  1830. const code = `
  1831. module Discourse
  1832. module Auth
  1833. class AuthProvider
  1834. def authenticate(params)
  1835. validate(params)
  1836. end
  1837. end
  1838. end
  1839. end
  1840. `;
  1841. const result = extractFromSource('lib/auth.rb', code);
  1842. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1843. expect(discourseModule).toBeDefined();
  1844. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1845. expect(authModule).toBeDefined();
  1846. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1847. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1848. expect(authProvider).toBeDefined();
  1849. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1850. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1851. expect(authMethod).toBeDefined();
  1852. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1853. });
  1854. });
  1855. describe('C/C++ imports', () => {
  1856. it('should extract system include', () => {
  1857. const code = `#include <iostream>`;
  1858. const result = extractFromSource('main.cpp', code);
  1859. const importNode = result.nodes.find((n) => n.kind === 'import');
  1860. expect(importNode).toBeDefined();
  1861. expect(importNode?.name).toBe('iostream');
  1862. expect(importNode?.signature).toBe('#include <iostream>');
  1863. });
  1864. it('should extract system include with path', () => {
  1865. const code = `#include <nlohmann/json.hpp>`;
  1866. const result = extractFromSource('app.cpp', code);
  1867. const importNode = result.nodes.find((n) => n.kind === 'import');
  1868. expect(importNode).toBeDefined();
  1869. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1870. });
  1871. it('should extract local include', () => {
  1872. const code = `#include "myheader.h"`;
  1873. const result = extractFromSource('main.cpp', code);
  1874. const importNode = result.nodes.find((n) => n.kind === 'import');
  1875. expect(importNode).toBeDefined();
  1876. expect(importNode?.name).toBe('myheader.h');
  1877. });
  1878. it('should extract C header', () => {
  1879. const code = `#include <stdio.h>`;
  1880. const result = extractFromSource('main.c', code);
  1881. const importNode = result.nodes.find((n) => n.kind === 'import');
  1882. expect(importNode).toBeDefined();
  1883. expect(importNode?.name).toBe('stdio.h');
  1884. });
  1885. it('should extract multiple includes', () => {
  1886. const code = `
  1887. #include <iostream>
  1888. #include <vector>
  1889. #include "config.h"
  1890. `;
  1891. const result = extractFromSource('app.cpp', code);
  1892. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1893. expect(importNodes.length).toBe(3);
  1894. const names = importNodes.map((n) => n.name);
  1895. expect(names).toContain('iostream');
  1896. expect(names).toContain('vector');
  1897. expect(names).toContain('config.h');
  1898. });
  1899. it('should create unresolved references for local includes', () => {
  1900. const code = `#include "myheader.h"`;
  1901. const result = extractFromSource('main.cpp', code);
  1902. const importRef = result.unresolvedReferences.find(
  1903. (r) => r.referenceKind === 'imports' && r.referenceName === 'myheader.h'
  1904. );
  1905. expect(importRef).toBeDefined();
  1906. expect(importRef?.line).toBe(1);
  1907. });
  1908. it('should create unresolved references for system includes', () => {
  1909. const code = `#include <iostream>`;
  1910. const result = extractFromSource('main.cpp', code);
  1911. const importRef = result.unresolvedReferences.find(
  1912. (r) => r.referenceKind === 'imports' && r.referenceName === 'iostream'
  1913. );
  1914. expect(importRef).toBeDefined();
  1915. });
  1916. });
  1917. describe('Dart imports', () => {
  1918. it('should extract dart: import', () => {
  1919. const code = `import 'dart:async';`;
  1920. const result = extractFromSource('main.dart', code);
  1921. const importNode = result.nodes.find((n) => n.kind === 'import');
  1922. expect(importNode).toBeDefined();
  1923. expect(importNode?.name).toBe('dart:async');
  1924. expect(importNode?.signature).toBe("import 'dart:async';");
  1925. });
  1926. it('should extract package import', () => {
  1927. const code = `import 'package:flutter/material.dart';`;
  1928. const result = extractFromSource('app.dart', code);
  1929. const importNode = result.nodes.find((n) => n.kind === 'import');
  1930. expect(importNode).toBeDefined();
  1931. expect(importNode?.name).toBe('package:flutter/material.dart');
  1932. });
  1933. it('should extract aliased import', () => {
  1934. const code = `import 'package:http/http.dart' as http;`;
  1935. const result = extractFromSource('api.dart', code);
  1936. const importNode = result.nodes.find((n) => n.kind === 'import');
  1937. expect(importNode).toBeDefined();
  1938. expect(importNode?.name).toBe('package:http/http.dart');
  1939. expect(importNode?.signature).toContain('as http');
  1940. });
  1941. it('should extract multiple imports', () => {
  1942. const code = `
  1943. import 'dart:async';
  1944. import 'dart:convert';
  1945. import 'package:flutter/material.dart';
  1946. `;
  1947. const result = extractFromSource('main.dart', code);
  1948. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1949. expect(importNodes.length).toBe(3);
  1950. const names = importNodes.map((n) => n.name);
  1951. expect(names).toContain('dart:async');
  1952. expect(names).toContain('dart:convert');
  1953. expect(names).toContain('package:flutter/material.dart');
  1954. });
  1955. it('should extract relative import', () => {
  1956. const code = `import '../utils/helpers.dart';`;
  1957. const result = extractFromSource('lib/main.dart', code);
  1958. const importNode = result.nodes.find((n) => n.kind === 'import');
  1959. expect(importNode).toBeDefined();
  1960. expect(importNode?.name).toBe('../utils/helpers.dart');
  1961. });
  1962. });
  1963. describe('Liquid imports', () => {
  1964. it('should extract render tag', () => {
  1965. const code = `{% render 'loading-spinner' %}`;
  1966. const result = extractFromSource('template.liquid', code);
  1967. const importNode = result.nodes.find((n) => n.kind === 'import');
  1968. expect(importNode).toBeDefined();
  1969. expect(importNode?.name).toBe('loading-spinner');
  1970. expect(importNode?.signature).toContain('render');
  1971. });
  1972. it('should extract section tag', () => {
  1973. const code = `{% section 'header' %}`;
  1974. const result = extractFromSource('layout/theme.liquid', code);
  1975. const importNode = result.nodes.find((n) => n.kind === 'import');
  1976. expect(importNode).toBeDefined();
  1977. expect(importNode?.name).toBe('header');
  1978. expect(importNode?.signature).toContain('section');
  1979. });
  1980. it('should extract include tag', () => {
  1981. const code = `{% include 'icon-cart' %}`;
  1982. const result = extractFromSource('snippets/header.liquid', code);
  1983. const importNode = result.nodes.find((n) => n.kind === 'import');
  1984. expect(importNode).toBeDefined();
  1985. expect(importNode?.name).toBe('icon-cart');
  1986. expect(importNode?.signature).toContain('include');
  1987. });
  1988. it('should extract render with whitespace control', () => {
  1989. const code = `{%- render 'price' -%}`;
  1990. const result = extractFromSource('snippets/product.liquid', code);
  1991. const importNode = result.nodes.find((n) => n.kind === 'import');
  1992. expect(importNode).toBeDefined();
  1993. expect(importNode?.name).toBe('price');
  1994. });
  1995. it('should extract multiple imports', () => {
  1996. const code = `
  1997. {% section 'header' %}
  1998. {% render 'loading-spinner' %}
  1999. {% render 'cart-drawer' %}
  2000. `;
  2001. const result = extractFromSource('layout/theme.liquid', 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('header');
  2006. expect(names).toContain('loading-spinner');
  2007. expect(names).toContain('cart-drawer');
  2008. });
  2009. });
  2010. });
  2011. // =============================================================================
  2012. // Pascal / Delphi Extraction
  2013. // =============================================================================
  2014. describe('Pascal / Delphi Extraction', () => {
  2015. describe('Language detection', () => {
  2016. it('should detect Pascal files', () => {
  2017. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  2018. expect(detectLanguage('App.dpr')).toBe('pascal');
  2019. expect(detectLanguage('Package.dpk')).toBe('pascal');
  2020. expect(detectLanguage('App.lpr')).toBe('pascal');
  2021. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  2022. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  2023. });
  2024. it('should report Pascal as supported', () => {
  2025. expect(isLanguageSupported('pascal')).toBe(true);
  2026. expect(getSupportedLanguages()).toContain('pascal');
  2027. });
  2028. });
  2029. describe('Unit extraction', () => {
  2030. it('should extract unit as module', () => {
  2031. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  2032. const result = extractFromSource('MyUnit.pas', code);
  2033. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2034. expect(moduleNode).toBeDefined();
  2035. expect(moduleNode?.name).toBe('MyUnit');
  2036. expect(moduleNode?.language).toBe('pascal');
  2037. });
  2038. it('should extract program as module', () => {
  2039. const code = `program MyApp;\nbegin\nend.`;
  2040. const result = extractFromSource('MyApp.dpr', code);
  2041. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2042. expect(moduleNode).toBeDefined();
  2043. expect(moduleNode?.name).toBe('MyApp');
  2044. });
  2045. it('should fallback to filename when module name is empty', () => {
  2046. // Some .dpr templates use "program;" without a name
  2047. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  2048. const result = extractFromSource('Console.dpr', code);
  2049. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2050. expect(moduleNode).toBeDefined();
  2051. expect(moduleNode?.name).toBe('Console');
  2052. });
  2053. });
  2054. describe('Uses clause (imports)', () => {
  2055. it('should extract uses as individual imports', () => {
  2056. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  2057. const result = extractFromSource('Test.pas', code);
  2058. const imports = result.nodes.filter((n) => n.kind === 'import');
  2059. expect(imports.length).toBe(2);
  2060. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  2061. expect(imports.map((n) => n.name)).toContain('System.Classes');
  2062. });
  2063. it('should create unresolved references for imports', () => {
  2064. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  2065. const result = extractFromSource('Test.pas', code);
  2066. const importRef = result.unresolvedReferences.find(
  2067. (r) => r.referenceKind === 'imports'
  2068. );
  2069. expect(importRef).toBeDefined();
  2070. expect(importRef?.referenceName).toBe('UAuth');
  2071. });
  2072. });
  2073. describe('Class extraction', () => {
  2074. it('should extract class declarations', () => {
  2075. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  2076. const result = extractFromSource('Test.pas', code);
  2077. const classNode = result.nodes.find((n) => n.kind === 'class');
  2078. expect(classNode).toBeDefined();
  2079. expect(classNode?.name).toBe('TMyClass');
  2080. });
  2081. it('should extract class with inheritance', () => {
  2082. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  2083. const result = extractFromSource('Test.pas', code);
  2084. const extendsRef = result.unresolvedReferences.find(
  2085. (r) => r.referenceKind === 'extends'
  2086. );
  2087. expect(extendsRef).toBeDefined();
  2088. expect(extendsRef?.referenceName).toBe('TParent');
  2089. });
  2090. it('should extract class with interface implementation', () => {
  2091. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  2092. const result = extractFromSource('Test.pas', code);
  2093. const extendsRef = result.unresolvedReferences.find(
  2094. (r) => r.referenceKind === 'extends'
  2095. );
  2096. const implementsRef = result.unresolvedReferences.find(
  2097. (r) => r.referenceKind === 'implements'
  2098. );
  2099. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2100. expect(implementsRef?.referenceName).toBe('ILogger');
  2101. });
  2102. });
  2103. describe('Record extraction', () => {
  2104. it('should extract records as class nodes', () => {
  2105. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  2106. const result = extractFromSource('Test.pas', code);
  2107. const classNode = result.nodes.find((n) => n.kind === 'class');
  2108. expect(classNode).toBeDefined();
  2109. expect(classNode?.name).toBe('TPoint');
  2110. const fields = result.nodes.filter((n) => n.kind === 'field');
  2111. expect(fields.length).toBe(2);
  2112. expect(fields.map((f) => f.name)).toContain('X');
  2113. expect(fields.map((f) => f.name)).toContain('Y');
  2114. });
  2115. });
  2116. describe('Interface extraction', () => {
  2117. it('should extract interface declarations', () => {
  2118. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  2119. const result = extractFromSource('Test.pas', code);
  2120. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2121. expect(ifaceNode).toBeDefined();
  2122. expect(ifaceNode?.name).toBe('ILogger');
  2123. });
  2124. });
  2125. describe('Method extraction', () => {
  2126. it('should extract methods with visibility', () => {
  2127. 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.`;
  2128. const result = extractFromSource('Test.pas', code);
  2129. const methods = result.nodes.filter((n) => n.kind === 'method');
  2130. expect(methods.length).toBe(2);
  2131. const createMethod = methods.find((m) => m.name === 'Create');
  2132. expect(createMethod?.visibility).toBe('public');
  2133. const getValue = methods.find((m) => m.name === 'GetValue');
  2134. expect(getValue?.visibility).toBe('public');
  2135. const fields = result.nodes.filter((n) => n.kind === 'field');
  2136. const fValue = fields.find((f) => f.name === 'FValue');
  2137. expect(fValue?.visibility).toBe('private');
  2138. });
  2139. it('should detect static methods (class methods)', () => {
  2140. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  2141. const result = extractFromSource('Test.pas', code);
  2142. const methods = result.nodes.filter((n) => n.kind === 'method');
  2143. const staticMethod = methods.find((m) => m.name === 'Create');
  2144. expect(staticMethod?.isStatic).toBe(true);
  2145. });
  2146. });
  2147. describe('Enum extraction', () => {
  2148. it('should extract enums with members', () => {
  2149. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  2150. const result = extractFromSource('Test.pas', code);
  2151. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2152. expect(enumNode).toBeDefined();
  2153. expect(enumNode?.name).toBe('TColor');
  2154. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2155. expect(members.length).toBe(3);
  2156. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  2157. });
  2158. });
  2159. describe('Property extraction', () => {
  2160. it('should extract properties', () => {
  2161. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  2162. const result = extractFromSource('Test.pas', code);
  2163. const propNode = result.nodes.find((n) => n.kind === 'property');
  2164. expect(propNode).toBeDefined();
  2165. expect(propNode?.name).toBe('Name');
  2166. expect(propNode?.visibility).toBe('public');
  2167. });
  2168. });
  2169. describe('Constant extraction', () => {
  2170. it('should extract constants', () => {
  2171. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  2172. const result = extractFromSource('Test.pas', code);
  2173. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2174. expect(constants.length).toBe(2);
  2175. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  2176. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  2177. });
  2178. });
  2179. describe('Type alias extraction', () => {
  2180. it('should extract type aliases', () => {
  2181. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  2182. const result = extractFromSource('Test.pas', code);
  2183. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  2184. expect(aliasNode).toBeDefined();
  2185. expect(aliasNode?.name).toBe('TUserName');
  2186. });
  2187. });
  2188. describe('Call extraction', () => {
  2189. it('should extract calls from implementation bodies', () => {
  2190. 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.`;
  2191. const result = extractFromSource('Test.pas', code);
  2192. const callRef = result.unresolvedReferences.find(
  2193. (r) => r.referenceKind === 'calls'
  2194. );
  2195. expect(callRef).toBeDefined();
  2196. expect(callRef?.referenceName).toBe('WriteLn');
  2197. });
  2198. });
  2199. describe('Containment edges', () => {
  2200. it('should create contains edges for class members', () => {
  2201. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2202. const result = extractFromSource('Test.pas', code);
  2203. const classNode = result.nodes.find((n) => n.kind === 'class');
  2204. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2205. expect(classNode).toBeDefined();
  2206. expect(methodNode).toBeDefined();
  2207. const containsEdge = result.edges.find(
  2208. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2209. );
  2210. expect(containsEdge).toBeDefined();
  2211. });
  2212. });
  2213. describe('Full fixture: UAuth.pas', () => {
  2214. const code = `unit UAuth;
  2215. interface
  2216. uses
  2217. System.SysUtils,
  2218. System.Classes;
  2219. type
  2220. ITokenValidator = interface
  2221. ['{11111111-1111-1111-1111-111111111111}']
  2222. function Validate(const AToken: string): Boolean;
  2223. end;
  2224. TAuthService = class(TInterfacedObject, ITokenValidator)
  2225. private
  2226. FToken: string;
  2227. FLoginCount: Integer;
  2228. procedure IncLoginCount;
  2229. protected
  2230. function GetToken: string;
  2231. public
  2232. constructor Create;
  2233. destructor Destroy; override;
  2234. function Validate(const AToken: string): Boolean;
  2235. function Login(const AUser, APass: string): string;
  2236. property Token: string read GetToken;
  2237. property LoginCount: Integer read FLoginCount;
  2238. end;
  2239. implementation
  2240. constructor TAuthService.Create;
  2241. begin
  2242. inherited Create;
  2243. FToken := '';
  2244. FLoginCount := 0;
  2245. end;
  2246. destructor TAuthService.Destroy;
  2247. begin
  2248. FToken := '';
  2249. inherited Destroy;
  2250. end;
  2251. procedure TAuthService.IncLoginCount;
  2252. begin
  2253. Inc(FLoginCount);
  2254. end;
  2255. function TAuthService.GetToken: string;
  2256. begin
  2257. Result := FToken;
  2258. end;
  2259. function TAuthService.Validate(const AToken: string): Boolean;
  2260. begin
  2261. Result := AToken <> '';
  2262. end;
  2263. function TAuthService.Login(const AUser, APass: string): string;
  2264. begin
  2265. IncLoginCount;
  2266. if Validate(AUser + ':' + APass) then
  2267. begin
  2268. FToken := AUser;
  2269. Result := 'ok';
  2270. end
  2271. else
  2272. Result := '';
  2273. end;
  2274. end.`;
  2275. it('should extract all expected nodes', () => {
  2276. const result = extractFromSource('UAuth.pas', code);
  2277. expect(result.errors).toHaveLength(0);
  2278. // Module
  2279. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2280. expect(moduleNode?.name).toBe('UAuth');
  2281. // Imports
  2282. const imports = result.nodes.filter((n) => n.kind === 'import');
  2283. expect(imports.length).toBe(2);
  2284. // Interface
  2285. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2286. expect(ifaceNode?.name).toBe('ITokenValidator');
  2287. // Class
  2288. const classNode = result.nodes.find((n) => n.kind === 'class');
  2289. expect(classNode?.name).toBe('TAuthService');
  2290. // Methods
  2291. const methods = result.nodes.filter((n) => n.kind === 'method');
  2292. expect(methods.length).toBeGreaterThanOrEqual(6);
  2293. expect(methods.map((m) => m.name)).toContain('Create');
  2294. expect(methods.map((m) => m.name)).toContain('Destroy');
  2295. expect(methods.map((m) => m.name)).toContain('Login');
  2296. // Fields
  2297. const fields = result.nodes.filter((n) => n.kind === 'field');
  2298. expect(fields.length).toBe(2);
  2299. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2300. // Properties
  2301. const props = result.nodes.filter((n) => n.kind === 'property');
  2302. expect(props.length).toBe(2);
  2303. expect(props.map((p) => p.name)).toContain('Token');
  2304. expect(props.map((p) => p.name)).toContain('LoginCount');
  2305. });
  2306. it('should extract inheritance and interface implementation', () => {
  2307. const result = extractFromSource('UAuth.pas', code);
  2308. const extendsRef = result.unresolvedReferences.find(
  2309. (r) => r.referenceKind === 'extends'
  2310. );
  2311. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2312. const implementsRef = result.unresolvedReferences.find(
  2313. (r) => r.referenceKind === 'implements'
  2314. );
  2315. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2316. });
  2317. it('should extract calls from implementation', () => {
  2318. const result = extractFromSource('UAuth.pas', code);
  2319. const callRefs = result.unresolvedReferences.filter(
  2320. (r) => r.referenceKind === 'calls'
  2321. );
  2322. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2323. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2324. });
  2325. });
  2326. describe('Full fixture: UTypes.pas', () => {
  2327. const code = `unit UTypes;
  2328. interface
  2329. uses
  2330. System.SysUtils;
  2331. const
  2332. C_MAX_RETRIES = 3;
  2333. C_DEFAULT_NAME = 'Guest';
  2334. type
  2335. TUserRole = (urAdmin, urEditor, urViewer);
  2336. TPoint2D = record
  2337. X: Double;
  2338. Y: Double;
  2339. end;
  2340. TUserName = string;
  2341. TUserInfo = class
  2342. public
  2343. type
  2344. TAddress = record
  2345. Street: string;
  2346. City: string;
  2347. Zip: string;
  2348. end;
  2349. private
  2350. FName: TUserName;
  2351. FRole: TUserRole;
  2352. FAddress: TAddress;
  2353. public
  2354. constructor Create(const AName: TUserName; ARole: TUserRole);
  2355. function GetDisplayName: string;
  2356. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2357. property Name: TUserName read FName write FName;
  2358. property Role: TUserRole read FRole;
  2359. property Address: TAddress read FAddress write FAddress;
  2360. end;
  2361. implementation
  2362. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2363. begin
  2364. FName := AName;
  2365. FRole := ARole;
  2366. end;
  2367. function TUserInfo.GetDisplayName: string;
  2368. begin
  2369. if FRole = urAdmin then
  2370. Result := '[Admin] ' + FName
  2371. else
  2372. Result := FName;
  2373. end;
  2374. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2375. begin
  2376. Result := TUserInfo.Create(AName, urAdmin);
  2377. end;
  2378. end.`;
  2379. it('should extract enums with members', () => {
  2380. const result = extractFromSource('UTypes.pas', code);
  2381. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2382. expect(enumNode?.name).toBe('TUserRole');
  2383. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2384. expect(members.length).toBe(3);
  2385. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2386. });
  2387. it('should extract constants', () => {
  2388. const result = extractFromSource('UTypes.pas', code);
  2389. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2390. expect(constants.length).toBe(2);
  2391. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2392. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2393. });
  2394. it('should extract type aliases', () => {
  2395. const result = extractFromSource('UTypes.pas', code);
  2396. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2397. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2398. });
  2399. it('should extract records as classes with fields', () => {
  2400. const result = extractFromSource('UTypes.pas', code);
  2401. const classes = result.nodes.filter((n) => n.kind === 'class');
  2402. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2403. // TPoint2D fields
  2404. const fields = result.nodes.filter((n) => n.kind === 'field');
  2405. expect(fields.map((f) => f.name)).toContain('X');
  2406. expect(fields.map((f) => f.name)).toContain('Y');
  2407. });
  2408. it('should extract static class methods', () => {
  2409. const result = extractFromSource('UTypes.pas', code);
  2410. const methods = result.nodes.filter((n) => n.kind === 'method');
  2411. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2412. expect(staticMethod).toBeDefined();
  2413. expect(staticMethod?.isStatic).toBe(true);
  2414. });
  2415. it('should extract nested types', () => {
  2416. const result = extractFromSource('UTypes.pas', code);
  2417. const classes = result.nodes.filter((n) => n.kind === 'class');
  2418. expect(classes.map((c) => c.name)).toContain('TAddress');
  2419. });
  2420. });
  2421. });
  2422. // =============================================================================
  2423. // DFM/FMX Extraction
  2424. // =============================================================================
  2425. describe('DFM/FMX Extraction', () => {
  2426. it('should extract components from DFM', () => {
  2427. const code = `object Form1: TForm1
  2428. Left = 0
  2429. Top = 0
  2430. Caption = 'My Form'
  2431. object Button1: TButton
  2432. Left = 10
  2433. Top = 10
  2434. Caption = 'Click Me'
  2435. end
  2436. end`;
  2437. const result = extractFromSource('Form1.dfm', code);
  2438. const components = result.nodes.filter((n) => n.kind === 'component');
  2439. expect(components.length).toBe(2);
  2440. expect(components.map((c) => c.name)).toContain('Form1');
  2441. expect(components.map((c) => c.name)).toContain('Button1');
  2442. const button = components.find((c) => c.name === 'Button1');
  2443. expect(button?.signature).toBe('TButton');
  2444. });
  2445. it('should extract nested component hierarchy', () => {
  2446. const code = `object Form1: TForm1
  2447. object Panel1: TPanel
  2448. object Label1: TLabel
  2449. Caption = 'Hello'
  2450. end
  2451. end
  2452. end`;
  2453. const result = extractFromSource('Form1.dfm', code);
  2454. const components = result.nodes.filter((n) => n.kind === 'component');
  2455. expect(components.length).toBe(3);
  2456. // Check nesting: Panel1 contains Label1
  2457. const panel = components.find((c) => c.name === 'Panel1');
  2458. const label = components.find((c) => c.name === 'Label1');
  2459. const containsEdge = result.edges.find(
  2460. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2461. );
  2462. expect(containsEdge).toBeDefined();
  2463. });
  2464. it('should extract event handler references', () => {
  2465. const code = `object Form1: TForm1
  2466. OnCreate = FormCreate
  2467. OnDestroy = FormDestroy
  2468. object Button1: TButton
  2469. OnClick = Button1Click
  2470. end
  2471. end`;
  2472. const result = extractFromSource('Form1.dfm', code);
  2473. const refs = result.unresolvedReferences;
  2474. expect(refs.length).toBe(3);
  2475. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2476. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2477. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2478. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2479. });
  2480. it('should handle multi-line properties', () => {
  2481. const code = `object Form1: TForm1
  2482. SQL.Strings = (
  2483. 'SELECT * FROM users'
  2484. 'WHERE active = 1')
  2485. object Button1: TButton
  2486. OnClick = Button1Click
  2487. end
  2488. end`;
  2489. const result = extractFromSource('Form1.dfm', code);
  2490. const components = result.nodes.filter((n) => n.kind === 'component');
  2491. expect(components.length).toBe(2);
  2492. const refs = result.unresolvedReferences;
  2493. expect(refs.length).toBe(1);
  2494. expect(refs[0]?.referenceName).toBe('Button1Click');
  2495. });
  2496. it('should handle inherited keyword', () => {
  2497. const code = `inherited Form1: TForm1
  2498. Caption = 'Inherited Form'
  2499. object Button1: TButton
  2500. OnClick = Button1Click
  2501. end
  2502. end`;
  2503. const result = extractFromSource('Form1.dfm', code);
  2504. const components = result.nodes.filter((n) => n.kind === 'component');
  2505. expect(components.length).toBe(2);
  2506. expect(components.map((c) => c.name)).toContain('Form1');
  2507. });
  2508. it('should handle item collection properties', () => {
  2509. const code = `object Form1: TForm1
  2510. object StatusBar1: TStatusBar
  2511. Panels = <
  2512. item
  2513. Width = 200
  2514. end
  2515. item
  2516. Width = 200
  2517. end>
  2518. end
  2519. end`;
  2520. const result = extractFromSource('Form1.dfm', code);
  2521. const components = result.nodes.filter((n) => n.kind === 'component');
  2522. expect(components.length).toBe(2);
  2523. });
  2524. describe('Full fixture: MainForm.dfm', () => {
  2525. const code = `object frmMain: TfrmMain
  2526. Left = 0
  2527. Top = 0
  2528. Caption = 'CodeGraph DFM Fixture'
  2529. ClientHeight = 480
  2530. ClientWidth = 640
  2531. OnCreate = FormCreate
  2532. OnDestroy = FormDestroy
  2533. object pnlTop: TPanel
  2534. Left = 0
  2535. Top = 0
  2536. Width = 640
  2537. Height = 50
  2538. object lblTitle: TLabel
  2539. Left = 16
  2540. Top = 16
  2541. Caption = 'Authentication Service'
  2542. end
  2543. object btnLogin: TButton
  2544. Left = 540
  2545. Top = 12
  2546. OnClick = btnLoginClick
  2547. end
  2548. end
  2549. object pnlContent: TPanel
  2550. Left = 0
  2551. Top = 50
  2552. object edtUsername: TEdit
  2553. Left = 16
  2554. Top = 16
  2555. OnChange = edtUsernameChange
  2556. end
  2557. object edtPassword: TEdit
  2558. Left = 16
  2559. Top = 48
  2560. OnKeyPress = edtPasswordKeyPress
  2561. end
  2562. object mmoLog: TMemo
  2563. Left = 16
  2564. Top = 88
  2565. end
  2566. end
  2567. object pnlStatus: TStatusBar
  2568. Left = 0
  2569. Top = 440
  2570. Panels = <
  2571. item
  2572. Width = 200
  2573. end
  2574. item
  2575. Width = 200
  2576. end>
  2577. end
  2578. end`;
  2579. it('should extract all components', () => {
  2580. const result = extractFromSource('MainForm.dfm', code);
  2581. const components = result.nodes.filter((n) => n.kind === 'component');
  2582. expect(components.length).toBe(9);
  2583. expect(components.map((c) => c.name)).toEqual(
  2584. expect.arrayContaining([
  2585. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2586. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2587. ])
  2588. );
  2589. });
  2590. it('should extract all event handlers', () => {
  2591. const result = extractFromSource('MainForm.dfm', code);
  2592. const refs = result.unresolvedReferences;
  2593. expect(refs.length).toBe(5);
  2594. expect(refs.map((r) => r.referenceName)).toEqual(
  2595. expect.arrayContaining([
  2596. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2597. 'edtUsernameChange', 'edtPasswordKeyPress',
  2598. ])
  2599. );
  2600. });
  2601. });
  2602. });
  2603. describe('Kotlin Multiplatform expect/actual', () => {
  2604. let tempDir: string;
  2605. let cg: CodeGraph;
  2606. beforeEach(() => {
  2607. tempDir = createTempDir();
  2608. });
  2609. afterEach(() => {
  2610. if (cg) cg.close();
  2611. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2612. });
  2613. it('links expect declarations to platform actual implementations and surfaces them in impact', async () => {
  2614. const common = path.join(tempDir, 'src', 'commonMain');
  2615. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2616. fs.mkdirSync(common, { recursive: true });
  2617. fs.mkdirSync(jvm, { recursive: true });
  2618. // common source set: expect declarations + a caller that uses them
  2619. fs.writeFileSync(
  2620. path.join(common, 'SystemProps.kt'),
  2621. `package demo.internal
  2622. expect fun systemProp(name: String): String?
  2623. expect class Platform {
  2624. fun describe(): String
  2625. }
  2626. `
  2627. );
  2628. fs.writeFileSync(
  2629. path.join(common, 'Caller.kt'),
  2630. `package demo
  2631. import demo.internal.systemProp
  2632. import demo.internal.Platform
  2633. fun useIt(): String {
  2634. val v = systemProp("os.name")
  2635. return Platform().describe() + v
  2636. }
  2637. `
  2638. );
  2639. // jvm source set: actual implementations
  2640. fs.writeFileSync(
  2641. path.join(jvm, 'SystemProps.kt'),
  2642. `package demo.internal
  2643. actual fun systemProp(name: String): String? = System.getProperty(name)
  2644. actual class Platform {
  2645. actual fun describe(): String = "JVM"
  2646. }
  2647. `
  2648. );
  2649. cg = CodeGraph.initSync(tempDir);
  2650. await cg.indexAll();
  2651. cg.resolveReferences();
  2652. // The expect/actual markers are captured onto the node's decorators.
  2653. const fns = cg.getNodesByKind('function');
  2654. const actualFn = fns.find(
  2655. (n) => n.name === 'systemProp' && n.decorators?.includes('actual')
  2656. );
  2657. const expectFn = fns.find(
  2658. (n) => n.name === 'systemProp' && n.decorators?.includes('expect')
  2659. );
  2660. expect(actualFn).toBeDefined();
  2661. expect(expectFn).toBeDefined();
  2662. expect(actualFn!.filePath).not.toBe(expectFn!.filePath);
  2663. // Editing the JVM actual must surface the common expect AND its caller —
  2664. // before the expect/actual bridge the actual had zero dependents.
  2665. const impact = cg.getImpactRadius(actualFn!.id, 3);
  2666. const impacted = [...impact.nodes.values()].map((n) => n.name);
  2667. expect(impacted).toContain('systemProp'); // the common expect
  2668. expect(impacted).toContain('useIt'); // the caller, reached transitively
  2669. // The bridging edge is a heuristic `calls` edge tagged by the synthesizer.
  2670. const bridge = impact.edges.find(
  2671. (e) =>
  2672. e.target === actualFn!.id &&
  2673. e.provenance === 'heuristic' &&
  2674. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2675. 'kotlin-expect-actual'
  2676. );
  2677. expect(bridge).toBeDefined();
  2678. expect(bridge!.source).toBe(expectFn!.id);
  2679. });
  2680. it('links an expect class to an actual typealias (different node kinds)', async () => {
  2681. const common = path.join(tempDir, 'src', 'commonMain');
  2682. const jvm = path.join(tempDir, 'src', 'jvmMain');
  2683. fs.mkdirSync(common, { recursive: true });
  2684. fs.mkdirSync(jvm, { recursive: true });
  2685. fs.writeFileSync(
  2686. path.join(common, 'Lock.kt'),
  2687. `package demo
  2688. expect class Lock {
  2689. fun acquire()
  2690. }
  2691. `
  2692. );
  2693. fs.writeFileSync(
  2694. path.join(jvm, 'Lock.kt'),
  2695. `package demo
  2696. actual typealias Lock = java.util.concurrent.locks.ReentrantLock
  2697. `
  2698. );
  2699. cg = CodeGraph.initSync(tempDir);
  2700. await cg.indexAll();
  2701. cg.resolveReferences();
  2702. const aliasNode = cg
  2703. .getNodesByKind('type_alias')
  2704. .find((n) => n.name === 'Lock' && n.decorators?.includes('actual'));
  2705. expect(aliasNode).toBeDefined();
  2706. // The actual typealias is now a cross-file dependency target (linked from
  2707. // the expect class), so it participates in impact rather than being orphaned.
  2708. const impact = cg.getImpactRadius(aliasNode!.id, 3);
  2709. const bridge = impact.edges.find(
  2710. (e) =>
  2711. e.target === aliasNode!.id &&
  2712. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  2713. 'kotlin-expect-actual'
  2714. );
  2715. expect(bridge).toBeDefined();
  2716. });
  2717. });
  2718. describe('Scala cross-file dependencies', () => {
  2719. let tempDir: string;
  2720. let cg: CodeGraph;
  2721. beforeEach(() => {
  2722. tempDir = createTempDir();
  2723. });
  2724. afterEach(() => {
  2725. if (cg) cg.close();
  2726. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2727. });
  2728. it('links parameterized supertypes, type annotations, and implicit params across files', async () => {
  2729. const src = path.join(tempDir, 'src', 'main', 'scala', 'demo');
  2730. fs.mkdirSync(src, { recursive: true });
  2731. fs.writeFileSync(
  2732. path.join(src, 'Semigroup.scala'),
  2733. `package demo
  2734. trait Semigroup[A] {
  2735. def combine(x: A, y: A): A
  2736. }
  2737. `
  2738. );
  2739. fs.writeFileSync(
  2740. path.join(src, 'Monoid.scala'),
  2741. `package demo
  2742. trait Monoid[A] extends Semigroup[A] {
  2743. def empty: A
  2744. }
  2745. `
  2746. );
  2747. fs.writeFileSync(
  2748. path.join(src, 'Instances.scala'),
  2749. `package demo
  2750. object Instances {
  2751. implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
  2752. def empty: Int = 0
  2753. def combine(x: Int, y: Int): Int = x + y
  2754. }
  2755. }
  2756. `
  2757. );
  2758. fs.writeFileSync(
  2759. path.join(src, 'Folding.scala'),
  2760. `package demo
  2761. object Folding {
  2762. def fold[A](xs: List[A])(implicit M: Monoid[A]): A =
  2763. xs.foldLeft(M.empty)(M.combine)
  2764. }
  2765. `
  2766. );
  2767. cg = CodeGraph.initSync(tempDir);
  2768. await cg.indexAll();
  2769. cg.resolveReferences();
  2770. const monoid = cg.getNodesByKind('trait').find((n) => n.name === 'Monoid');
  2771. const semigroup = cg.getNodesByKind('trait').find((n) => n.name === 'Semigroup');
  2772. expect(monoid).toBeDefined();
  2773. expect(semigroup).toBeDefined();
  2774. expect(monoid!.filePath).not.toBe(semigroup!.filePath);
  2775. // Parameterized supertype `extends Semigroup[A]` must create an extends edge —
  2776. // the whole point of the fix (the `[A]` used to defeat name matching).
  2777. const semaImpact = cg.getImpactRadius(semigroup!.id, 3);
  2778. expect([...semaImpact.nodes.values()].map((n) => n.name)).toContain('Monoid');
  2779. // Editing Monoid surfaces the cross-file users: the instance val typed
  2780. // `Monoid[Int]` and the method taking it as an implicit (curried) param.
  2781. const impacted = [...cg.getImpactRadius(monoid!.id, 3).nodes.values()].map((n) => n.name);
  2782. expect(impacted).toContain('intMonoid'); // field type annotation
  2783. expect(impacted).toContain('fold'); // trailing implicit parameter list
  2784. });
  2785. });
  2786. describe('PHP namespace + import resolution', () => {
  2787. let tempDir: string;
  2788. let cg: CodeGraph;
  2789. beforeEach(() => {
  2790. tempDir = createTempDir();
  2791. });
  2792. afterEach(() => {
  2793. if (cg) cg.close();
  2794. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2795. });
  2796. it('resolves `use` imports to the namespace-qualified definition and type-hints across files', async () => {
  2797. const src = path.join(tempDir, 'src');
  2798. // Two interfaces with the SAME simple name in different namespaces — the
  2799. // exact ambiguity (Laravel has 7+ `Factory`) that bare-name matching can't
  2800. // resolve. The namespace qualifies them; the `use` import disambiguates.
  2801. fs.mkdirSync(path.join(src, 'Cache'), { recursive: true });
  2802. fs.mkdirSync(path.join(src, 'Mail'), { recursive: true });
  2803. fs.mkdirSync(path.join(src, 'App'), { recursive: true });
  2804. fs.writeFileSync(
  2805. path.join(src, 'Cache', 'Factory.php'),
  2806. `<?php
  2807. namespace Contracts\\Cache;
  2808. interface Factory {
  2809. public function store(): object;
  2810. }
  2811. `
  2812. );
  2813. fs.writeFileSync(
  2814. path.join(src, 'Mail', 'Factory.php'),
  2815. `<?php
  2816. namespace Contracts\\Mail;
  2817. interface Factory {
  2818. public function mailer(): object;
  2819. }
  2820. `
  2821. );
  2822. fs.writeFileSync(
  2823. path.join(src, 'App', 'Service.php'),
  2824. `<?php
  2825. namespace App;
  2826. use Contracts\\Cache\\Factory;
  2827. class Service {
  2828. public function make(): Factory {
  2829. return resolve(Factory::class);
  2830. }
  2831. }
  2832. `
  2833. );
  2834. cg = CodeGraph.initSync(tempDir);
  2835. await cg.indexAll();
  2836. cg.resolveReferences();
  2837. // The PHP namespace is captured into the qualified name, so the two
  2838. // same-named interfaces are distinguishable.
  2839. const cacheFactory = cg
  2840. .getNodesByKind('interface')
  2841. .find((n) => n.qualifiedName === 'Contracts\\Cache::Factory');
  2842. const mailFactory = cg
  2843. .getNodesByKind('interface')
  2844. .find((n) => n.qualifiedName === 'Contracts\\Mail::Factory');
  2845. expect(cacheFactory).toBeDefined();
  2846. expect(mailFactory).toBeDefined();
  2847. // Service `use`s Contracts\Cache\Factory, so editing THAT interface reaches
  2848. // Service.php — and editing the same-named Contracts\Mail\Factory must NOT
  2849. // (the import resolved to the right namespace, not an arbitrary `Factory`).
  2850. const serviceFile = 'src/App/Service.php';
  2851. const cacheReaches = [...cg.getImpactRadius(cacheFactory!.id, 3).nodes.values()].some(
  2852. (n) => (n.filePath ?? '').endsWith(serviceFile)
  2853. );
  2854. const mailReaches = [...cg.getImpactRadius(mailFactory!.id, 3).nodes.values()].some(
  2855. (n) => (n.filePath ?? '').endsWith(serviceFile)
  2856. );
  2857. expect(cacheReaches).toBe(true);
  2858. expect(mailReaches).toBe(false);
  2859. });
  2860. });
  2861. describe('Ruby mixins (include/extend/prepend)', () => {
  2862. let tempDir: string;
  2863. let cg: CodeGraph;
  2864. beforeEach(() => {
  2865. tempDir = createTempDir();
  2866. });
  2867. afterEach(() => {
  2868. if (cg) cg.close();
  2869. if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  2870. });
  2871. it('links include/extend/prepend to the mixed-in module across files', async () => {
  2872. const lib = path.join(tempDir, 'lib');
  2873. fs.mkdirSync(lib, { recursive: true });
  2874. fs.writeFileSync(
  2875. path.join(lib, 'concerns.rb'),
  2876. `module Trackable
  2877. def track; end
  2878. end
  2879. module Cacheable
  2880. def cache; end
  2881. end
  2882. module Loggable
  2883. def log; end
  2884. end
  2885. `
  2886. );
  2887. fs.writeFileSync(
  2888. path.join(lib, 'model.rb'),
  2889. `class Model
  2890. include Trackable
  2891. prepend Cacheable
  2892. extend Loggable
  2893. end
  2894. `
  2895. );
  2896. cg = CodeGraph.initSync(tempDir);
  2897. await cg.indexAll();
  2898. cg.resolveReferences();
  2899. const model = cg.getNodesByKind('class').find((n) => n.name === 'Model');
  2900. expect(model).toBeDefined();
  2901. // All three mixin forms create an `implements` edge Model → module, so
  2902. // editing a concern surfaces every class that mixes it in (across files).
  2903. for (const moduleName of ['Trackable', 'Cacheable', 'Loggable']) {
  2904. const mod = cg.getNodesByKind('module').find((n) => n.name === moduleName);
  2905. expect(mod, moduleName).toBeDefined();
  2906. const impacted = [...cg.getImpactRadius(mod!.id, 3).nodes.values()].map((n) => n.name);
  2907. expect(impacted, `${moduleName} should be depended on by Model`).toContain('Model');
  2908. }
  2909. });
  2910. it('resolves require / require_relative to the required file', async () => {
  2911. const lib = path.join(tempDir, 'lib');
  2912. fs.mkdirSync(path.join(lib, 'app'), { recursive: true });
  2913. // A leaf file whose class is referenced only dynamically — so without
  2914. // require resolution it would look like nothing depends on it.
  2915. fs.writeFileSync(
  2916. path.join(lib, 'app', 'fetcher.rb'),
  2917. `module App
  2918. class Fetcher
  2919. def fetch; end
  2920. end
  2921. end
  2922. `
  2923. );
  2924. // Pulled in by a load-path `require` …
  2925. fs.writeFileSync(
  2926. path.join(lib, 'app', 'worker.rb'),
  2927. `require "app/fetcher"
  2928. module App
  2929. class Worker; end
  2930. end
  2931. `
  2932. );
  2933. // … and a sibling pulled in by `require_relative`.
  2934. fs.writeFileSync(
  2935. path.join(lib, 'app', 'boot.rb'),
  2936. `require_relative "fetcher"
  2937. `
  2938. );
  2939. cg = CodeGraph.initSync(tempDir);
  2940. await cg.indexAll();
  2941. cg.resolveReferences();
  2942. // The require edges target fetcher.rb's FILE node. Editing it should reach
  2943. // BOTH the load-path requirer (worker.rb) and the require_relative one
  2944. // (boot.rb) — without require resolution its file would have no dependents.
  2945. const fetcher = cg.getNodesByKind('file').find((n) => n.filePath.endsWith('app/fetcher.rb'));
  2946. expect(fetcher, 'fetcher.rb indexed').toBeDefined();
  2947. const reached = [...cg.getImpactRadius(fetcher!.id, 2).nodes.values()].map((n) => n.filePath ?? '');
  2948. expect(reached.some((p) => p.endsWith('app/worker.rb'))).toBe(true);
  2949. expect(reached.some((p) => p.endsWith('app/boot.rb'))).toBe(true);
  2950. });
  2951. });
  2952. describe('Full Indexing', () => {
  2953. let tempDir: string;
  2954. beforeEach(() => {
  2955. tempDir = createTempDir();
  2956. });
  2957. afterEach(() => {
  2958. cleanupTempDir(tempDir);
  2959. });
  2960. it('should index a TypeScript file', async () => {
  2961. // Create test file
  2962. const srcDir = path.join(tempDir, 'src');
  2963. fs.mkdirSync(srcDir);
  2964. fs.writeFileSync(
  2965. path.join(srcDir, 'utils.ts'),
  2966. `
  2967. export function add(a: number, b: number): number {
  2968. return a + b;
  2969. }
  2970. export function multiply(a: number, b: number): number {
  2971. return a * b;
  2972. }
  2973. `
  2974. );
  2975. // Initialize and index
  2976. const cg = CodeGraph.initSync(tempDir);
  2977. const result = await cg.indexAll();
  2978. expect(result.success).toBe(true);
  2979. expect(result.filesIndexed).toBe(1);
  2980. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2981. // Check nodes were stored
  2982. const nodes = cg.getNodesInFile('src/utils.ts');
  2983. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2984. const addFunc = nodes.find((n) => n.name === 'add');
  2985. expect(addFunc).toBeDefined();
  2986. expect(addFunc?.kind).toBe('function');
  2987. cg.close();
  2988. });
  2989. it('should index multiple files', async () => {
  2990. // Create test files
  2991. const srcDir = path.join(tempDir, 'src');
  2992. fs.mkdirSync(srcDir);
  2993. fs.writeFileSync(
  2994. path.join(srcDir, 'math.ts'),
  2995. `export function add(a: number, b: number) { return a + b; }`
  2996. );
  2997. fs.writeFileSync(
  2998. path.join(srcDir, 'string.ts'),
  2999. `export function capitalize(s: string) { return s.toUpperCase(); }`
  3000. );
  3001. // Initialize and index
  3002. const cg = CodeGraph.initSync(tempDir);
  3003. const result = await cg.indexAll();
  3004. expect(result.success).toBe(true);
  3005. expect(result.filesIndexed).toBe(2);
  3006. const files = cg.getFiles();
  3007. expect(files.length).toBe(2);
  3008. cg.close();
  3009. });
  3010. it('should track file hashes for incremental updates', async () => {
  3011. // Create initial file
  3012. const srcDir = path.join(tempDir, 'src');
  3013. fs.mkdirSync(srcDir);
  3014. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  3015. // Initialize and index
  3016. const cg = CodeGraph.initSync(tempDir);
  3017. await cg.indexAll();
  3018. // Check file is tracked
  3019. const file = cg.getFile('src/main.ts');
  3020. expect(file).toBeDefined();
  3021. expect(file?.contentHash).toBeDefined();
  3022. // Modify file
  3023. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  3024. // Check for changes
  3025. const changes = cg.getChangedFiles();
  3026. expect(changes.modified).toContain('src/main.ts');
  3027. cg.close();
  3028. });
  3029. it('should sync and detect changes', async () => {
  3030. // Create initial file
  3031. const srcDir = path.join(tempDir, 'src');
  3032. fs.mkdirSync(srcDir);
  3033. fs.writeFileSync(
  3034. path.join(srcDir, 'main.ts'),
  3035. `export function original() { return 1; }`
  3036. );
  3037. // Initialize and index
  3038. const cg = CodeGraph.initSync(tempDir);
  3039. await cg.indexAll();
  3040. const initialNodes = cg.getNodesInFile('src/main.ts');
  3041. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  3042. // Modify file
  3043. fs.writeFileSync(
  3044. path.join(srcDir, 'main.ts'),
  3045. `export function updated() { return 2; }`
  3046. );
  3047. // Sync
  3048. const syncResult = await cg.sync();
  3049. expect(syncResult.filesModified).toBe(1);
  3050. // Check nodes were updated
  3051. const updatedNodes = cg.getNodesInFile('src/main.ts');
  3052. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  3053. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  3054. cg.close();
  3055. });
  3056. it('should count file-level tracked YAML files as indexed', async () => {
  3057. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3058. fs.writeFileSync(path.join(tempDir, 'routes.yml'), 'route: value\n');
  3059. const cg = CodeGraph.initSync(tempDir);
  3060. const result = await cg.indexAll();
  3061. expect(result.success).toBe(true);
  3062. expect(result.filesIndexed).toBe(2);
  3063. expect(result.filesSkipped).toBe(0);
  3064. expect(cg.getFiles().map((f) => f.path).sort()).toEqual(['app.yaml', 'routes.yml']);
  3065. cg.close();
  3066. });
  3067. it('should count file-level tracked YAML/Twig files as indexed in indexFiles()', async () => {
  3068. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3069. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  3070. const cg = CodeGraph.initSync(tempDir);
  3071. const result = await cg.indexFiles(['app.yaml', 'view.twig']);
  3072. expect(result.success).toBe(true);
  3073. expect(result.filesIndexed).toBe(2);
  3074. expect(result.filesSkipped).toBe(0);
  3075. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  3076. expect(tracked).toEqual(['app.yaml:yaml', 'view.twig:twig']);
  3077. cg.close();
  3078. });
  3079. it('should count file-level tracked .properties files as indexed', async () => {
  3080. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  3081. fs.writeFileSync(path.join(tempDir, 'log.properties'), 'log.level=INFO\n');
  3082. const cg = CodeGraph.initSync(tempDir);
  3083. const result = await cg.indexAll();
  3084. expect(result.success).toBe(true);
  3085. expect(result.filesIndexed).toBe(2);
  3086. expect(result.filesSkipped).toBe(0);
  3087. cg.close();
  3088. });
  3089. it('should count the full file-level tracked class (yaml/twig/properties) in indexFiles()', async () => {
  3090. fs.writeFileSync(path.join(tempDir, 'app.yaml'), 'name: test\n');
  3091. fs.writeFileSync(path.join(tempDir, 'view.twig'), '{{ title }}\n');
  3092. fs.writeFileSync(path.join(tempDir, 'application.properties'), 'server.port=8080\n');
  3093. const cg = CodeGraph.initSync(tempDir);
  3094. const result = await cg.indexFiles(['app.yaml', 'view.twig', 'application.properties']);
  3095. expect(result.success).toBe(true);
  3096. expect(result.filesIndexed).toBe(3);
  3097. expect(result.filesSkipped).toBe(0);
  3098. const tracked = cg.getFiles().map((f) => `${f.path}:${f.language}`).sort();
  3099. expect(tracked).toEqual(['app.yaml:yaml', 'application.properties:properties', 'view.twig:twig']);
  3100. cg.close();
  3101. });
  3102. });
  3103. describe('Path Normalization', () => {
  3104. it('should convert backslashes to forward slashes', () => {
  3105. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  3106. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  3107. });
  3108. it('should leave forward-slash paths unchanged', () => {
  3109. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  3110. });
  3111. it('should handle empty string', () => {
  3112. expect(normalizePath('')).toBe('');
  3113. });
  3114. });
  3115. describe('Directory Exclusion', () => {
  3116. let tempDir: string;
  3117. beforeEach(() => {
  3118. tempDir = createTempDir();
  3119. });
  3120. afterEach(() => {
  3121. cleanupTempDir(tempDir);
  3122. });
  3123. it('should exclude directories listed in .gitignore', () => {
  3124. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  3125. const srcDir = path.join(tempDir, 'src');
  3126. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  3127. fs.mkdirSync(srcDir, { recursive: true });
  3128. fs.mkdirSync(nmDir, { recursive: true });
  3129. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3130. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  3131. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  3132. const files = scanDirectory(tempDir);
  3133. expect(files).toContain('src/index.ts');
  3134. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  3135. });
  3136. it('should exclude nested node_modules via a root .gitignore', () => {
  3137. // A trailing-slash pattern with no leading slash matches at any depth.
  3138. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  3139. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  3140. fs.mkdirSync(srcDir, { recursive: true });
  3141. fs.mkdirSync(nmDir, { recursive: true });
  3142. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3143. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  3144. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  3145. const files = scanDirectory(tempDir);
  3146. expect(files).toContain('packages/app/src/index.ts');
  3147. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  3148. });
  3149. it('should apply a nested .gitignore only to its own subtree', () => {
  3150. const appSrc = path.join(tempDir, 'app', 'src');
  3151. fs.mkdirSync(appSrc, { recursive: true });
  3152. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  3153. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  3154. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  3155. // A sibling with the same name outside app/ must NOT be ignored.
  3156. const otherDir = path.join(tempDir, 'other', 'src');
  3157. fs.mkdirSync(otherDir, { recursive: true });
  3158. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  3159. const files = scanDirectory(tempDir);
  3160. expect(files).toContain('app/src/keep.ts');
  3161. expect(files).not.toContain('app/src/skip.ts');
  3162. expect(files).toContain('other/src/skip.ts');
  3163. });
  3164. it('should always skip .git directories', () => {
  3165. const srcDir = path.join(tempDir, 'src');
  3166. const gitDir = path.join(tempDir, '.git', 'objects');
  3167. fs.mkdirSync(srcDir, { recursive: true });
  3168. fs.mkdirSync(gitDir, { recursive: true });
  3169. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  3170. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  3171. const files = scanDirectory(tempDir);
  3172. expect(files).toContain('src/index.ts');
  3173. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  3174. });
  3175. it('should return forward-slash paths on all platforms', () => {
  3176. const srcDir = path.join(tempDir, 'src', 'components');
  3177. fs.mkdirSync(srcDir, { recursive: true });
  3178. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  3179. const files = scanDirectory(tempDir);
  3180. expect(files.length).toBe(1);
  3181. expect(files[0]).toBe('src/components/Button.tsx');
  3182. expect(files[0]).not.toContain('\\');
  3183. });
  3184. });
  3185. describe('Git Submodules', () => {
  3186. let tempDir: string;
  3187. beforeEach(() => {
  3188. tempDir = createTempDir();
  3189. });
  3190. afterEach(() => {
  3191. cleanupTempDir(tempDir);
  3192. });
  3193. it('should index files inside git submodules (issue #147)', async () => {
  3194. const { execFileSync } = await import('child_process');
  3195. const git = (cwd: string, ...args: string[]) =>
  3196. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3197. // Build a separate "library" repo to use as a submodule source.
  3198. const libDir = path.join(tempDir, '_lib');
  3199. fs.mkdirSync(libDir, { recursive: true });
  3200. git(libDir, 'init', '-q');
  3201. git(libDir, 'config', 'user.email', 'test@test.com');
  3202. git(libDir, 'config', 'user.name', 'Test');
  3203. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  3204. git(libDir, 'add', '-A');
  3205. git(libDir, 'commit', '-q', '-m', 'lib init');
  3206. // Build the main repo and add the lib repo as a submodule.
  3207. const mainDir = path.join(tempDir, 'main');
  3208. fs.mkdirSync(mainDir, { recursive: true });
  3209. git(mainDir, 'init', '-q');
  3210. git(mainDir, 'config', 'user.email', 'test@test.com');
  3211. git(mainDir, 'config', 'user.name', 'Test');
  3212. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  3213. git(mainDir, 'add', '-A');
  3214. git(mainDir, 'commit', '-q', '-m', 'app init');
  3215. // protocol.file.allow=always is required to add a local-path submodule on
  3216. // recent git versions (CVE-2022-39253 mitigation).
  3217. execFileSync(
  3218. 'git',
  3219. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  3220. { cwd: mainDir, stdio: 'pipe' }
  3221. );
  3222. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  3223. const files = scanDirectory(mainDir);
  3224. expect(files).toContain('app.ts');
  3225. expect(files).toContain('libs/lib/lib.ts');
  3226. });
  3227. });
  3228. describe('Nested non-submodule git repos', () => {
  3229. let tempDir: string;
  3230. beforeEach(() => {
  3231. tempDir = createTempDir();
  3232. });
  3233. afterEach(() => {
  3234. cleanupTempDir(tempDir);
  3235. });
  3236. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  3237. const { execFileSync } = await import('child_process');
  3238. const git = (cwd: string, ...args: string[]) =>
  3239. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3240. // Top-level workspace is itself a git repo, holding no source directly —
  3241. // the CMake "super-repo" layout from the issue.
  3242. const root = path.join(tempDir, 'root');
  3243. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  3244. git(root, 'init', '-q');
  3245. git(root, 'config', 'user.email', 'test@test.com');
  3246. git(root, 'config', 'user.name', 'Test');
  3247. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  3248. // Two independent clones living inside the workspace (NOT submodules):
  3249. // one with committed source, one with only untracked source.
  3250. const sub1 = path.join(root, 'sub_repo1', 'src');
  3251. fs.mkdirSync(sub1, { recursive: true });
  3252. git(path.join(root, 'sub_repo1'), 'init', '-q');
  3253. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  3254. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  3255. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  3256. git(path.join(root, 'sub_repo1'), 'add', '-A');
  3257. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  3258. const sub2 = path.join(root, 'sub_repo2', 'src');
  3259. fs.mkdirSync(sub2, { recursive: true });
  3260. git(path.join(root, 'sub_repo2'), 'init', '-q');
  3261. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  3262. const files = scanDirectory(root);
  3263. // Both committed and untracked source from the nested repos must be found.
  3264. expect(files).toContain('sub_repo1/src/one.ts');
  3265. expect(files).toContain('sub_repo2/src/two.ts');
  3266. });
  3267. it('should respect each embedded repo\'s own .gitignore', async () => {
  3268. const { execFileSync } = await import('child_process');
  3269. const git = (cwd: string, ...args: string[]) =>
  3270. execFileSync('git', args, { cwd, stdio: 'pipe' });
  3271. const root = path.join(tempDir, 'root');
  3272. fs.mkdirSync(root, { recursive: true });
  3273. git(root, 'init', '-q');
  3274. const sub = path.join(root, 'sub_repo', 'src');
  3275. fs.mkdirSync(sub, { recursive: true });
  3276. git(path.join(root, 'sub_repo'), 'init', '-q');
  3277. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  3278. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  3279. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  3280. const files = scanDirectory(root);
  3281. expect(files).toContain('sub_repo/src/real.ts');
  3282. expect(files).not.toContain('sub_repo/src/generated.ts');
  3283. });
  3284. });
  3285. // =============================================================================
  3286. // Scala
  3287. // =============================================================================
  3288. describe('Scala Extraction', () => {
  3289. describe('Language detection', () => {
  3290. it('should detect Scala files', () => {
  3291. expect(detectLanguage('Main.scala')).toBe('scala');
  3292. expect(detectLanguage('script.sc')).toBe('scala');
  3293. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  3294. });
  3295. it('should report Scala as supported', () => {
  3296. expect(isLanguageSupported('scala')).toBe(true);
  3297. expect(getSupportedLanguages()).toContain('scala');
  3298. });
  3299. });
  3300. describe('Class extraction', () => {
  3301. it('should extract class definitions', () => {
  3302. const code = `
  3303. class UserService(private val repo: UserRepository) {
  3304. def findUser(id: String): Option[String] = Some(id)
  3305. }
  3306. `;
  3307. const result = extractFromSource('UserService.scala', code);
  3308. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  3309. expect(cls).toBeDefined();
  3310. expect(cls?.language).toBe('scala');
  3311. });
  3312. it('should extract object definitions as class kind', () => {
  3313. const code = `
  3314. object DatabaseConfig {
  3315. val url = "jdbc:postgresql://localhost/mydb"
  3316. }
  3317. `;
  3318. const result = extractFromSource('Config.scala', code);
  3319. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  3320. expect(obj).toBeDefined();
  3321. });
  3322. it('should extract trait definitions as trait kind', () => {
  3323. const code = `
  3324. trait Repository[A] {
  3325. def findById(id: String): Option[A]
  3326. def save(entity: A): Unit
  3327. }
  3328. `;
  3329. const result = extractFromSource('Repository.scala', code);
  3330. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  3331. expect(trait_).toBeDefined();
  3332. });
  3333. });
  3334. describe('Method and function extraction', () => {
  3335. it('should extract method definitions inside a class', () => {
  3336. const code = `
  3337. class Calculator {
  3338. def add(a: Int, b: Int): Int = a + b
  3339. def divide(a: Double, b: Double): Double = a / b
  3340. }
  3341. `;
  3342. const result = extractFromSource('Calculator.scala', code);
  3343. const methods = result.nodes.filter((n) => n.kind === 'method');
  3344. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  3345. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  3346. });
  3347. it('should extract method signatures', () => {
  3348. const code = `
  3349. class Greeter {
  3350. def greet(name: String): String = s"Hello, \${name}!"
  3351. }
  3352. `;
  3353. const result = extractFromSource('Greeter.scala', code);
  3354. const method = result.nodes.find((n) => n.name === 'greet');
  3355. expect(method?.signature).toContain('name: String');
  3356. expect(method?.signature).toContain('String');
  3357. });
  3358. it('should extract top-level function definitions as functions', () => {
  3359. const code = `
  3360. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  3361. def greet(name: String): String = s"Hello, \${name}!"
  3362. `;
  3363. const result = extractFromSource('utils.scala', code);
  3364. const fns = result.nodes.filter((n) => n.kind === 'function');
  3365. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  3366. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  3367. });
  3368. });
  3369. describe('Val and var extraction', () => {
  3370. it('should extract val inside a class as field', () => {
  3371. const code = `
  3372. class Config {
  3373. val timeout: Int = 30
  3374. val host: String = "localhost"
  3375. }
  3376. `;
  3377. const result = extractFromSource('Config.scala', code);
  3378. const fields = result.nodes.filter((n) => n.kind === 'field');
  3379. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  3380. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  3381. });
  3382. it('should extract var inside a class as field', () => {
  3383. const code = `
  3384. class Counter {
  3385. var count: Int = 0
  3386. }
  3387. `;
  3388. const result = extractFromSource('Counter.scala', code);
  3389. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  3390. expect(field).toBeDefined();
  3391. });
  3392. it('should extract top-level val as constant', () => {
  3393. const code = `
  3394. val MaxConnections: Int = 100
  3395. val DefaultTimeout = 30
  3396. `;
  3397. const result = extractFromSource('constants.scala', code);
  3398. const consts = result.nodes.filter((n) => n.kind === 'constant');
  3399. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  3400. });
  3401. it('should extract top-level var as variable', () => {
  3402. const code = `
  3403. var retries: Int = 3
  3404. `;
  3405. const result = extractFromSource('state.scala', code);
  3406. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  3407. expect(v).toBeDefined();
  3408. });
  3409. it('should include type in val/var signature', () => {
  3410. const code = `
  3411. class Service {
  3412. val timeout: Int = 30
  3413. }
  3414. `;
  3415. const result = extractFromSource('Service.scala', code);
  3416. const field = result.nodes.find((n) => n.name === 'timeout');
  3417. expect(field?.signature).toContain('timeout');
  3418. expect(field?.signature).toContain('Int');
  3419. });
  3420. });
  3421. describe('Enum extraction', () => {
  3422. it('should extract enum definitions', () => {
  3423. const code = `
  3424. enum Color:
  3425. case Red
  3426. case Green
  3427. case Blue
  3428. `;
  3429. const result = extractFromSource('Color.scala', code);
  3430. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  3431. expect(enumNode).toBeDefined();
  3432. });
  3433. it('should extract enum cases as enum_member', () => {
  3434. const code = `
  3435. enum Direction:
  3436. case North
  3437. case South
  3438. case East
  3439. case West
  3440. `;
  3441. const result = extractFromSource('Direction.scala', code);
  3442. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  3443. expect(members.find((m) => m.name === 'North')).toBeDefined();
  3444. expect(members.find((m) => m.name === 'South')).toBeDefined();
  3445. expect(members.length).toBeGreaterThanOrEqual(4);
  3446. });
  3447. });
  3448. describe('Type alias extraction', () => {
  3449. it('should extract type aliases', () => {
  3450. const code = `
  3451. type UserId = String
  3452. type UserMap = Map[String, String]
  3453. `;
  3454. const result = extractFromSource('types.scala', code);
  3455. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3456. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  3457. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  3458. });
  3459. });
  3460. describe('Import extraction', () => {
  3461. it('should extract import declarations', () => {
  3462. const code = `
  3463. import scala.collection.mutable.ListBuffer
  3464. import scala.concurrent.Future
  3465. `;
  3466. const result = extractFromSource('imports.scala', code);
  3467. const imports = result.nodes.filter((n) => n.kind === 'import');
  3468. expect(imports.length).toBeGreaterThanOrEqual(2);
  3469. });
  3470. });
  3471. describe('Visibility modifiers', () => {
  3472. it('should extract private visibility', () => {
  3473. const code = `
  3474. class Service {
  3475. private val secret: String = "abc"
  3476. private def helper(): Unit = {}
  3477. }
  3478. `;
  3479. const result = extractFromSource('Service.scala', code);
  3480. const secretField = result.nodes.find((n) => n.name === 'secret');
  3481. expect(secretField?.visibility).toBe('private');
  3482. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  3483. expect(helperMethod?.visibility).toBe('private');
  3484. });
  3485. it('should extract protected visibility', () => {
  3486. const code = `
  3487. class Base {
  3488. protected def helperMethod(): Unit = {}
  3489. }
  3490. `;
  3491. const result = extractFromSource('Base.scala', code);
  3492. const method = result.nodes.find((n) => n.name === 'helperMethod');
  3493. expect(method?.visibility).toBe('protected');
  3494. });
  3495. it('should default to public visibility', () => {
  3496. const code = `
  3497. class Greeter {
  3498. def hello(): Unit = {}
  3499. }
  3500. `;
  3501. const result = extractFromSource('Greeter.scala', code);
  3502. const method = result.nodes.find((n) => n.name === 'hello');
  3503. expect(method?.visibility).toBe('public');
  3504. });
  3505. });
  3506. describe('Inheritance', () => {
  3507. it('should extract extends relationships', () => {
  3508. const code = `
  3509. class AdminUser extends User {
  3510. def adminAction(): Unit = {}
  3511. }
  3512. `;
  3513. const result = extractFromSource('AdminUser.scala', code);
  3514. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  3515. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  3516. });
  3517. });
  3518. describe('Call extraction', () => {
  3519. it('should extract function call expressions', () => {
  3520. const code = `
  3521. def processData(): Unit = {
  3522. val result = computeResult()
  3523. println(result)
  3524. }
  3525. `;
  3526. const result = extractFromSource('processor.scala', code);
  3527. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  3528. expect(calls.length).toBeGreaterThan(0);
  3529. });
  3530. });
  3531. });
  3532. describe('Vue Extraction', () => {
  3533. it('should detect Vue files', () => {
  3534. expect(detectLanguage('App.vue')).toBe('vue');
  3535. expect(detectLanguage('components/Button.vue')).toBe('vue');
  3536. expect(isLanguageSupported('vue')).toBe(true);
  3537. });
  3538. it('should extract component node from a Vue SFC', () => {
  3539. const code = `<template>
  3540. <div>{{ message }}</div>
  3541. </template>
  3542. <script>
  3543. export default {
  3544. data() {
  3545. return { message: 'Hello' };
  3546. }
  3547. }
  3548. </script>
  3549. `;
  3550. const result = extractFromSource('HelloWorld.vue', code);
  3551. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3552. expect(componentNode).toBeDefined();
  3553. expect(componentNode?.name).toBe('HelloWorld');
  3554. expect(componentNode?.language).toBe('vue');
  3555. expect(componentNode?.isExported).toBe(true);
  3556. });
  3557. it('should extract functions from <script> block', () => {
  3558. const code = `<template>
  3559. <button @click="handleClick">Click</button>
  3560. </template>
  3561. <script>
  3562. function handleClick() {
  3563. console.log('clicked');
  3564. }
  3565. const count = 0;
  3566. </script>
  3567. `;
  3568. const result = extractFromSource('Button.vue', code);
  3569. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3570. expect(componentNode).toBeDefined();
  3571. expect(componentNode?.name).toBe('Button');
  3572. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  3573. expect(funcNode).toBeDefined();
  3574. expect(funcNode?.language).toBe('vue');
  3575. });
  3576. it('should extract from <script setup lang="ts"> block', () => {
  3577. const code = `<template>
  3578. <div>{{ count }}</div>
  3579. </template>
  3580. <script setup lang="ts">
  3581. import { ref } from 'vue';
  3582. const count = ref(0);
  3583. function increment(): void {
  3584. count.value++;
  3585. }
  3586. </script>
  3587. `;
  3588. const result = extractFromSource('Counter.vue', code);
  3589. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3590. expect(componentNode).toBeDefined();
  3591. expect(componentNode?.name).toBe('Counter');
  3592. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  3593. expect(funcNode).toBeDefined();
  3594. expect(funcNode?.language).toBe('vue');
  3595. // All nodes should be marked as vue language
  3596. for (const node of result.nodes) {
  3597. expect(node.language).toBe('vue');
  3598. }
  3599. });
  3600. it('should extract calls from top-level <script setup> initializers', () => {
  3601. const code = `<template>
  3602. <div>{{ token }}</div>
  3603. </template>
  3604. <script setup lang="ts">
  3605. import { getTokenMp } from './api/upload';
  3606. const token = getTokenMp();
  3607. </script>
  3608. `;
  3609. const result = extractFromSource('Issue425Setup.vue', code);
  3610. const call = result.unresolvedReferences.find(
  3611. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3612. );
  3613. expect(call).toBeDefined();
  3614. });
  3615. it('should extract calls from Vue Options API object methods', () => {
  3616. const code = `<template>
  3617. <button @click="save">Save</button>
  3618. </template>
  3619. <script>
  3620. import { getTokenMp } from './api/upload';
  3621. export default {
  3622. methods: {
  3623. save() {
  3624. return getTokenMp();
  3625. }
  3626. },
  3627. setup() {
  3628. return getTokenMp();
  3629. }
  3630. }
  3631. </script>
  3632. `;
  3633. const result = extractFromSource('Issue425Options.vue', code);
  3634. const calls = result.unresolvedReferences.filter(
  3635. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3636. );
  3637. expect(calls).toHaveLength(2);
  3638. });
  3639. it('should extract component usages from the Vue template (PascalCase + kebab, skipping built-ins) (#629)', () => {
  3640. const code = `<template>
  3641. <div class="wrap">
  3642. <UserCard :user="u" />
  3643. <my-button>Click</my-button>
  3644. <Transition><span>x</span></Transition>
  3645. </div>
  3646. </template>
  3647. <script setup lang="ts">
  3648. import UserCard from './UserCard.vue';
  3649. import MyButton from './MyButton.vue';
  3650. </script>
  3651. `;
  3652. const result = extractFromSource('Host.vue', code);
  3653. const refs = result.unresolvedReferences
  3654. .filter((r) => r.referenceKind === 'references')
  3655. .map((r) => r.referenceName);
  3656. expect(refs).toContain('UserCard'); // PascalCase tag
  3657. expect(refs).toContain('MyButton'); // kebab <my-button> → MyButton
  3658. expect(refs).not.toContain('Transition'); // Vue built-in skipped
  3659. expect(refs).not.toContain('Div'); // native HTML element skipped
  3660. expect(refs).not.toContain('Span');
  3661. });
  3662. it('should extract from both <script> and <script setup> blocks', () => {
  3663. const code = `<template>
  3664. <div>{{ msg }}</div>
  3665. </template>
  3666. <script>
  3667. export default {
  3668. name: 'DualScript'
  3669. }
  3670. </script>
  3671. <script setup>
  3672. const msg = 'hello';
  3673. function greet() {
  3674. return msg;
  3675. }
  3676. </script>
  3677. `;
  3678. const result = extractFromSource('DualScript.vue', code);
  3679. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3680. expect(componentNode).toBeDefined();
  3681. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  3682. expect(greetFunc).toBeDefined();
  3683. });
  3684. it('should create component node for template-only Vue file', () => {
  3685. const code = `<template>
  3686. <div>Static content</div>
  3687. </template>
  3688. `;
  3689. const result = extractFromSource('Static.vue', code);
  3690. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3691. expect(componentNode).toBeDefined();
  3692. expect(componentNode?.name).toBe('Static');
  3693. expect(componentNode?.language).toBe('vue');
  3694. // Only the component node should exist (no script nodes)
  3695. expect(result.nodes.length).toBe(1);
  3696. });
  3697. it('should create containment edges from component to script nodes', () => {
  3698. const code = `<template>
  3699. <div>{{ value }}</div>
  3700. </template>
  3701. <script setup lang="ts">
  3702. const value = 42;
  3703. </script>
  3704. `;
  3705. const result = extractFromSource('Contained.vue', code);
  3706. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3707. expect(componentNode).toBeDefined();
  3708. // Should have containment edges from component to child nodes
  3709. const containEdges = result.edges.filter(
  3710. (e) => e.source === componentNode!.id && e.kind === 'contains'
  3711. );
  3712. expect(containEdges.length).toBeGreaterThan(0);
  3713. });
  3714. });
  3715. describe('Instantiates + Decorates edge extraction', () => {
  3716. it('emits an instantiates ref for `new Foo()`', () => {
  3717. const code = `
  3718. class Foo {}
  3719. function bootstrap() { return new Foo(); }
  3720. `;
  3721. const result = extractFromSource('app.ts', code);
  3722. const ref = result.unresolvedReferences.find(
  3723. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  3724. );
  3725. expect(ref).toBeDefined();
  3726. });
  3727. it('strips type-argument suffix from generic constructors', () => {
  3728. const code = `
  3729. class Container<T> { constructor(_: T) {} }
  3730. function go() { return new Container<string>('x'); }
  3731. `;
  3732. const result = extractFromSource('app.ts', code);
  3733. const ref = result.unresolvedReferences.find(
  3734. (r) => r.referenceKind === 'instantiates'
  3735. );
  3736. expect(ref).toBeDefined();
  3737. // Container<string> must be normalised to "Container" — otherwise
  3738. // resolution can never match the class node.
  3739. expect(ref!.referenceName).toBe('Container');
  3740. });
  3741. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  3742. const code = `
  3743. const ns = { Foo: class {} };
  3744. function go() { return new ns.Foo(); }
  3745. `;
  3746. const result = extractFromSource('app.ts', code);
  3747. const ref = result.unresolvedReferences.find(
  3748. (r) => r.referenceKind === 'instantiates'
  3749. );
  3750. // We can't always resolve which Foo, but the name should be the
  3751. // simple identifier so name-matching has a chance.
  3752. expect(ref?.referenceName).toBe('Foo');
  3753. });
  3754. it('emits a decorates ref for `@Foo class X {}`', () => {
  3755. const code = `
  3756. function Foo(_arg: string) { return (cls: any) => cls; }
  3757. @Foo('x')
  3758. class X {}
  3759. `;
  3760. const result = extractFromSource('app.ts', code);
  3761. const decorClass = result.unresolvedReferences.find(
  3762. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  3763. );
  3764. expect(decorClass).toBeDefined();
  3765. });
  3766. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  3767. // Regression: the sibling-walk must stop at the first non-
  3768. // decorator separator. `@A class Foo {} @B class Bar {}` must
  3769. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  3770. // `decorates(Bar, A)`.
  3771. const code = `
  3772. function A(cls: any) { return cls; }
  3773. function B(cls: any) { return cls; }
  3774. @A
  3775. class Foo {}
  3776. @B
  3777. class Bar {}
  3778. `;
  3779. const result = extractFromSource('app.ts', code);
  3780. const decoratesEdges = result.unresolvedReferences.filter(
  3781. (r) => r.referenceKind === 'decorates'
  3782. );
  3783. // Exactly one decorates ref per decorated class, no cross-attribution.
  3784. const fromBar = decoratesEdges.filter((r) =>
  3785. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  3786. );
  3787. expect(fromBar.length).toBe(1);
  3788. expect(fromBar[0]!.referenceName).toBe('B');
  3789. });
  3790. it('emits a decorates ref for `@Foo method() {}`', () => {
  3791. const code = `
  3792. function Get(p: string) { return (t: any, k: string) => t; }
  3793. class Svc {
  3794. @Get('/x') method() { return 1; }
  3795. }
  3796. `;
  3797. const result = extractFromSource('app.ts', code);
  3798. const decorMethod = result.unresolvedReferences.find(
  3799. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  3800. );
  3801. expect(decorMethod).toBeDefined();
  3802. // The decorated symbol must be `method`, not the constructor or class.
  3803. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  3804. expect(decoratedNode?.name).toBe('method');
  3805. });
  3806. });
  3807. // =============================================================================
  3808. // Lua
  3809. // =============================================================================
  3810. describe('Lua Extraction', () => {
  3811. describe('Language detection', () => {
  3812. it('should detect Lua files', () => {
  3813. expect(detectLanguage('init.lua')).toBe('lua');
  3814. expect(detectLanguage('src/util.lua')).toBe('lua');
  3815. });
  3816. it('should report Lua as supported', () => {
  3817. expect(isLanguageSupported('lua')).toBe(true);
  3818. expect(getSupportedLanguages()).toContain('lua');
  3819. });
  3820. });
  3821. describe('Function extraction', () => {
  3822. it('should extract global and local functions', () => {
  3823. const code = `
  3824. function configure(opts) return opts end
  3825. local function helper(x) return x * 2 end
  3826. `;
  3827. const result = extractFromSource('init.lua', code);
  3828. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  3829. expect(funcs).toContain('configure');
  3830. expect(funcs).toContain('helper');
  3831. const configure = result.nodes.find((n) => n.name === 'configure');
  3832. expect(configure?.language).toBe('lua');
  3833. expect(configure?.signature).toBe('(opts)');
  3834. });
  3835. it('should split table/method functions into a receiver and method name', () => {
  3836. const code = `
  3837. function M.connect(host, port) return host end
  3838. function M:send(data) return self end
  3839. `;
  3840. const result = extractFromSource('init.lua', code);
  3841. const methods = result.nodes.filter((n) => n.kind === 'method');
  3842. const connect = methods.find((m) => m.name === 'connect');
  3843. expect(connect?.qualifiedName).toBe('M::connect');
  3844. const send = methods.find((m) => m.name === 'send');
  3845. expect(send?.qualifiedName).toBe('M::send');
  3846. });
  3847. });
  3848. describe('Variable extraction', () => {
  3849. it('should extract local variable declarations', () => {
  3850. const code = `
  3851. local M = {}
  3852. local count = 0
  3853. `;
  3854. const result = extractFromSource('mod.lua', code);
  3855. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3856. expect(vars).toContain('M');
  3857. expect(vars).toContain('count');
  3858. });
  3859. });
  3860. describe('Import extraction (require)', () => {
  3861. it('should extract require() in local declarations and bare calls', () => {
  3862. const code = `
  3863. local socket = require("socket")
  3864. local http = require "resty.http"
  3865. require("side.effect")
  3866. `;
  3867. const result = extractFromSource('net.lua', code);
  3868. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3869. expect(imports).toContain('socket');
  3870. expect(imports).toContain('resty.http');
  3871. expect(imports).toContain('side.effect');
  3872. const ref = result.unresolvedReferences.find(
  3873. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  3874. );
  3875. expect(ref).toBeDefined();
  3876. });
  3877. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  3878. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  3879. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  3880. // by extracting several sources in sequence and asserting the LAST still works.
  3881. it('should keep extracting require across many sequential parses', () => {
  3882. let last;
  3883. for (let i = 0; i < 8; i++) {
  3884. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  3885. }
  3886. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3887. expect(imports).toContain('module.7');
  3888. });
  3889. });
  3890. describe('Call extraction', () => {
  3891. it('should record intra-file calls as resolvable references', () => {
  3892. const code = `
  3893. local function helper(x) return x end
  3894. local function run(y) return helper(y) end
  3895. `;
  3896. const result = extractFromSource('calls.lua', code);
  3897. const call = result.unresolvedReferences.find(
  3898. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  3899. );
  3900. expect(call).toBeDefined();
  3901. });
  3902. });
  3903. });
  3904. // =============================================================================
  3905. // Luau (typed superset of Lua — https://luau.org)
  3906. // =============================================================================
  3907. describe('Luau Extraction', () => {
  3908. describe('Language detection', () => {
  3909. it('should detect Luau files', () => {
  3910. expect(detectLanguage('init.luau')).toBe('luau');
  3911. expect(detectLanguage('src/Client.luau')).toBe('luau');
  3912. });
  3913. it('should report Luau as supported', () => {
  3914. expect(isLanguageSupported('luau')).toBe(true);
  3915. expect(getSupportedLanguages()).toContain('luau');
  3916. });
  3917. });
  3918. describe('Type aliases', () => {
  3919. it('should extract `type` and `export type` definitions', () => {
  3920. const code = `
  3921. export type Vector = { x: number, y: number }
  3922. type Handler = (msg: string) -> boolean
  3923. `;
  3924. const result = extractFromSource('types.luau', code);
  3925. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3926. const vector = aliases.find((a) => a.name === 'Vector');
  3927. expect(vector).toBeDefined();
  3928. expect(vector?.isExported).toBe(true);
  3929. const handler = aliases.find((a) => a.name === 'Handler');
  3930. expect(handler).toBeDefined();
  3931. expect(handler?.isExported).toBe(false);
  3932. });
  3933. });
  3934. describe('Typed functions and methods', () => {
  3935. it('should capture typed signatures and split methods by receiver', () => {
  3936. const code = `
  3937. function configure(opts: { debug: boolean }): boolean
  3938. return opts.debug
  3939. end
  3940. function Client:fetch(path: string): Response
  3941. return path
  3942. end
  3943. `;
  3944. const result = extractFromSource('client.luau', code);
  3945. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  3946. expect(configure?.language).toBe('luau');
  3947. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  3948. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  3949. expect(fetch?.qualifiedName).toBe('Client::fetch');
  3950. });
  3951. });
  3952. describe('Imports and variables', () => {
  3953. it('should extract string and Roblox instance-path require imports', () => {
  3954. const code = `
  3955. local http = require("http")
  3956. local Signal = require(script.Parent.Signal)
  3957. local count = 0
  3958. `;
  3959. const result = extractFromSource('mod.luau', code);
  3960. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3961. expect(imports).toContain('http'); // string require
  3962. expect(imports).toContain('Signal'); // Roblox instance-path require
  3963. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3964. expect(vars).toContain('count');
  3965. });
  3966. });
  3967. });
  3968. // =============================================================================
  3969. // Objective-C
  3970. // =============================================================================
  3971. describe('Objective-C Extraction', () => {
  3972. const sample = `
  3973. #import <Foundation/Foundation.h>
  3974. #import "MyClass.h"
  3975. @interface MyClass : NSObject <NSCopying>
  3976. @property (nonatomic, copy) NSString *name;
  3977. - (void)greet;
  3978. - (void)doThing:(id)x with:(id)y;
  3979. + (instancetype)shared;
  3980. @end
  3981. @implementation MyClass
  3982. - (void)greet {
  3983. NSLog(@"Hello");
  3984. [self doWork];
  3985. }
  3986. - (void)doThing:(id)x with:(id)y {
  3987. [self notify:x];
  3988. }
  3989. + (instancetype)shared {
  3990. return [[MyClass alloc] init];
  3991. }
  3992. @end
  3993. void helperFunction(int count) {
  3994. MyClass *obj = [MyClass shared];
  3995. [obj greet];
  3996. }
  3997. `;
  3998. it('should extract classes, methods, functions, and imports', () => {
  3999. const result = extractFromSource('App.m', sample);
  4000. const classes = result.nodes.filter((n) => n.kind === 'class');
  4001. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  4002. const methods = result.nodes.filter((n) => n.kind === 'method');
  4003. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  4004. const shared = methods.find((m) => m.name === 'shared');
  4005. expect(shared?.isStatic).toBe(true);
  4006. const properties = result.nodes.filter((n) => n.kind === 'property');
  4007. expect(properties.some((p) => p.name === 'name')).toBe(true);
  4008. const functions = result.nodes.filter((n) => n.kind === 'function');
  4009. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  4010. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  4011. expect(imports).toContain('Foundation/Foundation.h');
  4012. expect(imports).toContain('MyClass.h');
  4013. });
  4014. it('should record inheritance and protocol conformance', () => {
  4015. const result = extractFromSource('App.m', sample);
  4016. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  4017. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  4018. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  4019. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  4020. });
  4021. it('should record message sends and C calls', () => {
  4022. const result = extractFromSource('App.m', sample);
  4023. const calls = result.unresolvedReferences
  4024. .filter((r) => r.referenceKind === 'calls')
  4025. .map((r) => r.referenceName);
  4026. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  4027. });
  4028. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  4029. // Regression for the gap discovered post-#165: message_expression's
  4030. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  4031. // so calls never resolved to multi-part method definitions like
  4032. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  4033. // must match the method-definition name with full keywords + trailing colons.
  4034. const code = `
  4035. @implementation Caller
  4036. - (void)demo {
  4037. NSMutableDictionary *d = [NSMutableDictionary new];
  4038. [d setObject:@"v" forKey:@"k"];
  4039. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  4040. [self touchesBegan:nil withEvent:nil];
  4041. }
  4042. @end
  4043. `;
  4044. const result = extractFromSource('Caller.m', code);
  4045. const calls = result.unresolvedReferences
  4046. .filter((r) => r.referenceKind === 'calls')
  4047. .map((r) => r.referenceName);
  4048. expect(calls).toEqual(
  4049. expect.arrayContaining([
  4050. 'd.setObject:forKey:',
  4051. 'd.setObject:forKey:withRetry:',
  4052. 'touchesBegan:withEvent:',
  4053. ])
  4054. );
  4055. });
  4056. it('should not classify pure C headers with @end in comments as objc', () => {
  4057. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  4058. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  4059. });
  4060. it('should extract protocol declarations', () => {
  4061. const code = `
  4062. @protocol DataSource <NSObject>
  4063. - (NSInteger)numberOfItems;
  4064. @end
  4065. `;
  4066. const result = extractFromSource('DataSource.h', code);
  4067. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  4068. expect(protocol).toBeDefined();
  4069. });
  4070. it('should report Objective-C as supported', () => {
  4071. expect(isLanguageSupported('objc')).toBe(true);
  4072. expect(getSupportedLanguages()).toContain('objc');
  4073. });
  4074. });
  4075. describe('Regression: issue-specific extraction fixes', () => {
  4076. it('indexes inner functions of an anonymous AMD/CommonJS module wrapper (#528)', () => {
  4077. const code = `
  4078. define(['dep'], function (dep) {
  4079. function innerHelper(x) { return x + 1; }
  4080. function compute(y) { return innerHelper(y); }
  4081. return { compute: compute };
  4082. });
  4083. `;
  4084. const result = extractFromSource('amd-module.js', code);
  4085. const fns = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  4086. expect(fns).toContain('innerHelper');
  4087. expect(fns).toContain('compute');
  4088. });
  4089. it('attaches Go methods on generic receivers to their type (#583)', () => {
  4090. const code = `
  4091. package main
  4092. type Stack[T any] struct { items []T }
  4093. func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
  4094. func (s Stack[T]) Len() int { return len(s.items) }
  4095. `;
  4096. const result = extractFromSource('stack.go', code);
  4097. const methods = result.nodes.filter((n) => n.kind === 'method');
  4098. expect(methods.find((m) => m.name === 'Push')?.qualifiedName).toBe('Stack::Push');
  4099. expect(methods.find((m) => m.name === 'Len')?.qualifiedName).toBe('Stack::Len');
  4100. });
  4101. it('indexes new module extensions: .mts/.cts (TS) and .xsjs/.xsjslib (JS) (#366, #556)', () => {
  4102. expect(isSourceFile('mod.mts')).toBe(true);
  4103. expect(isSourceFile('mod.cts')).toBe(true);
  4104. expect(isSourceFile('service.xsjs')).toBe(true);
  4105. expect(isSourceFile('lib.xsjslib')).toBe(true);
  4106. expect(detectLanguage('mod.mts')).toBe('typescript');
  4107. expect(detectLanguage('service.xsjs')).toBe('javascript');
  4108. // End-to-end: a .mts file is parsed as TS, a .xsjs file as JS.
  4109. const ts = extractFromSource('mod.mts', 'export function hello(): number { return 1; }');
  4110. expect(ts.nodes.find((n) => n.name === 'hello' && n.kind === 'function')).toBeDefined();
  4111. const js = extractFromSource('service.xsjs', 'function handleRequest() { return 1; }');
  4112. expect(js.nodes.find((n) => n.name === 'handleRequest' && n.kind === 'function')).toBeDefined();
  4113. });
  4114. });
  4115. describe('Import / re-export dependency linking (blast-radius recall)', () => {
  4116. // An import IS a dependency, but extraction only emits references for calls,
  4117. // instantiations, type annotations, and inheritance — so a symbol imported and
  4118. // then merely re-exported, placed in a registry array, passed as an argument,
  4119. // or used in JSX produced no cross-file edge, leaving the providing file with a
  4120. // false "0 dependents". These tests pin the import/re-export binding linking.
  4121. it('emits an imports reference per named, aliased, and default import binding', () => {
  4122. const code = `
  4123. import { widget, helper as h } from './foo';
  4124. import Thing from './thing';
  4125. import * as NS from './ns';
  4126. export const registry = [widget];
  4127. `;
  4128. const result = extractFromSource('bar.ts', code);
  4129. const names = result.unresolvedReferences
  4130. .filter((r) => r.referenceKind === 'imports')
  4131. .map((r) => r.referenceName);
  4132. expect(names).toContain('widget'); // named import → local name
  4133. expect(names).toContain('h'); // aliased import → local alias
  4134. expect(names).toContain('Thing'); // default import
  4135. expect(names).toContain('NS'); // namespace import → linked to the module file as a dependency
  4136. });
  4137. it('emits an imports reference per re-exported binding', () => {
  4138. const result = extractFromSource('barrel.ts', `export { alpha, beta as b } from './source';`);
  4139. const names = result.unresolvedReferences
  4140. .filter((r) => r.referenceKind === 'imports')
  4141. .map((r) => r.referenceName);
  4142. // Re-export links the SOURCE-side name, not the local alias.
  4143. expect(names).toContain('alpha');
  4144. expect(names).toContain('beta');
  4145. });
  4146. it('a value imported/re-exported but never called still makes the importer a dependent', async () => {
  4147. const dir = createTempDir();
  4148. try {
  4149. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4150. fs.writeFileSync(
  4151. path.join(dir, 'src', 'foo.ts'),
  4152. `export const widget = { n: 1 };\nexport function helper(): void {}\n`
  4153. );
  4154. // bar uses widget ONLY in an array and re-exports helper — neither is
  4155. // called/typed, so before import-linking bar had no edge to foo at all.
  4156. fs.writeFileSync(
  4157. path.join(dir, 'src', 'bar.ts'),
  4158. `import { widget } from './foo';\nexport { helper } from './foo';\nexport const registry = [widget];\n`
  4159. );
  4160. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  4161. await cg.indexAll();
  4162. cg.resolveReferences();
  4163. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  4164. cg.destroy();
  4165. } finally {
  4166. cleanupTempDir(dir);
  4167. }
  4168. });
  4169. it('a namespace import touched only via a value-member read still links the module file', async () => {
  4170. const dir = createTempDir();
  4171. try {
  4172. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4173. fs.writeFileSync(path.join(dir, 'src', 'foo.ts'), `export const SOME_CONST = 42;\n`);
  4174. // `foo` is imported as a namespace and used ONLY via a value-member read
  4175. // (no call, no type) — `foo.helper()` would link on its own, but a bare
  4176. // `foo.SOME_CONST` would not, so the module-import backstop must link it.
  4177. fs.writeFileSync(path.join(dir, 'src', 'bar.ts'), `import * as foo from './foo';\nexport const x = foo.SOME_CONST;\n`);
  4178. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.ts'], exclude: [] } });
  4179. await cg.indexAll();
  4180. cg.resolveReferences();
  4181. expect(cg.getFileDependents('src/foo.ts')).toContain('src/bar.ts');
  4182. cg.destroy();
  4183. } finally {
  4184. cleanupTempDir(dir);
  4185. }
  4186. });
  4187. });
  4188. describe('Python import dependency linking (blast-radius recall)', () => {
  4189. // Same recall gap as TS: Python only linked called/instantiated imports, so a
  4190. // name brought in with `from module import X` and then merely stored, used as
  4191. // a decorator/argument, or re-exported through an `__init__.py` produced no
  4192. // cross-file edge — the providing module showed a false "0 dependents".
  4193. it('emits an imports reference per name in a `from module import ...` (incl. value/aliased)', () => {
  4194. const code = [
  4195. 'from foo import helper, widget',
  4196. 'from foo import Thing as T',
  4197. 'from . import sibling',
  4198. 'from bar import *',
  4199. ].join('\n');
  4200. const names = extractFromSource('mod.py', code)
  4201. .unresolvedReferences.filter((r) => r.referenceKind === 'imports')
  4202. .map((r) => r.referenceName);
  4203. expect(names).toContain('helper');
  4204. expect(names).toContain('widget'); // value import
  4205. expect(names).toContain('T'); // aliased import → local name
  4206. expect(names).toContain('sibling'); // `from . import <name>`
  4207. expect(names).not.toContain('*'); // wildcard import has no names
  4208. });
  4209. it('a Python value imported but never called still makes the importer a dependent', async () => {
  4210. const dir = createTempDir();
  4211. try {
  4212. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4213. fs.writeFileSync(path.join(dir, 'pkg', 'foo.py'), `widget = {"n": 1}\ndef helper():\n return 1\n`);
  4214. // bar imports widget+helper but only stores widget in a list — nothing is
  4215. // called, so before import-linking bar had no edge to foo.
  4216. fs.writeFileSync(path.join(dir, 'pkg', 'bar.py'), `from foo import widget, helper\nregistry = [widget]\n`);
  4217. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4218. await cg.indexAll();
  4219. cg.resolveReferences();
  4220. expect(cg.getFileDependents('pkg/foo.py')).toContain('pkg/bar.py');
  4221. cg.destroy();
  4222. } finally {
  4223. cleanupTempDir(dir);
  4224. }
  4225. });
  4226. it('resolves `from . import submodule` + `submodule.func()` to the submodule', async () => {
  4227. const dir = createTempDir();
  4228. try {
  4229. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4230. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  4231. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `def where():\n return "/ca.pem"\n`);
  4232. // certs is an imported MODULE (a file), and certs.where() is a qualified
  4233. // call through it — the receiver isn't a symbol, so plain name-matching
  4234. // can't link it. Also exercises the Python relative-dot path fix (`.certs`).
  4235. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\ndef go():\n return certs.where()\n`);
  4236. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4237. await cg.indexAll();
  4238. cg.resolveReferences();
  4239. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  4240. cg.destroy();
  4241. } finally {
  4242. cleanupTempDir(dir);
  4243. }
  4244. });
  4245. it('a module import is a dependency even when the used member is re-exported elsewhere', async () => {
  4246. const dir = createTempDir();
  4247. try {
  4248. fs.mkdirSync(path.join(dir, 'pkg'), { recursive: true });
  4249. fs.writeFileSync(path.join(dir, 'pkg', '__init__.py'), '');
  4250. // `where` is NOT defined in certs.py (re-exported from a 3rd-party pkg), so
  4251. // member resolution can't find it — the module-import backstop must still
  4252. // record utils -> certs. (Mirrors requests' real `certs.where`.)
  4253. fs.writeFileSync(path.join(dir, 'pkg', 'certs.py'), `from external_ca import where\n`);
  4254. fs.writeFileSync(path.join(dir, 'pkg', 'utils.py'), `from . import certs\nCA = certs.where()\n`);
  4255. const cg = CodeGraph.initSync(dir, { config: { include: ['pkg/**/*.py'], exclude: [] } });
  4256. await cg.indexAll();
  4257. cg.resolveReferences();
  4258. expect(cg.getFileDependents('pkg/certs.py')).toContain('pkg/utils.py');
  4259. cg.destroy();
  4260. } finally {
  4261. cleanupTempDir(dir);
  4262. }
  4263. });
  4264. });
  4265. describe('Go cross-package composite literals (blast-radius recall)', () => {
  4266. // Go function calls and type references across packages already resolved, but
  4267. // struct composite literals — `render.XML{...}` / `pkga.Widget{...}` — were not
  4268. // extracted at all, so a package whose types are only INSTANTIATED elsewhere
  4269. // (gin's render/binding implementations) showed 0 dependents.
  4270. it('links a cross-package struct composite literal to the defining package', async () => {
  4271. const dir = createTempDir();
  4272. try {
  4273. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4274. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  4275. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct { Data any }\n`);
  4276. fs.writeFileSync(path.join(dir, 'app.go'), `package main\n\nimport "example.com/proj/render"\n\nfunc handle() any { return render.XML{} }\n`);
  4277. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4278. await cg.indexAll();
  4279. cg.resolveReferences();
  4280. expect(cg.getFileDependents('render/xml.go')).toContain('app.go');
  4281. cg.destroy();
  4282. } finally {
  4283. cleanupTempDir(dir);
  4284. }
  4285. });
  4286. it('links a composite literal in a package-level var registry', async () => {
  4287. const dir = createTempDir();
  4288. try {
  4289. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4290. fs.mkdirSync(path.join(dir, 'render'), { recursive: true });
  4291. fs.writeFileSync(path.join(dir, 'render', 'xml.go'), `package render\n\ntype XML struct {}\nfunc (XML) Render() {}\n`);
  4292. // The implementation is registered only in a top-level `var registry = {...}`
  4293. // map literal — the body walker doesn't cover top-level declarations, so this
  4294. // exercises the var-initializer walking added for Go.
  4295. 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`);
  4296. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4297. await cg.indexAll();
  4298. cg.resolveReferences();
  4299. expect(cg.getFileDependents('render/xml.go')).toContain('reg.go');
  4300. cg.destroy();
  4301. } finally {
  4302. cleanupTempDir(dir);
  4303. }
  4304. });
  4305. it('links a parenthesized pointer type conversion `(*T)(x)` to the type', async () => {
  4306. const dir = createTempDir();
  4307. try {
  4308. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4309. fs.writeFileSync(path.join(dir, 'types.go'), `package main\n\ntype Wrapped struct { N int }\n`);
  4310. // `(*Wrapped)(x)` parses as a call whose callee is the parenthesized type
  4311. // `(*Wrapped)` — without normalization it dropped on the floor.
  4312. fs.writeFileSync(path.join(dir, 'use.go'), `package main\n\nfunc run(x *int) { _ = (*Wrapped)(x) }\n`);
  4313. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4314. await cg.indexAll();
  4315. cg.resolveReferences();
  4316. expect(cg.getFileDependents('types.go')).toContain('use.go');
  4317. cg.destroy();
  4318. } finally {
  4319. cleanupTempDir(dir);
  4320. }
  4321. });
  4322. it('links an implementation reached only through a Go interface (implicit satisfaction, #584)', async () => {
  4323. const dir = createTempDir();
  4324. try {
  4325. fs.writeFileSync(path.join(dir, 'go.mod'), 'module example.com/proj\n\ngo 1.21\n');
  4326. fs.mkdirSync(path.join(dir, 'codec'), { recursive: true });
  4327. 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`);
  4328. // jsonApi satisfies Core structurally (no `implements` keyword) and is
  4329. // reached ONLY through the interface (API.Marshal). Without implicit
  4330. // interface satisfaction + dispatch, json.go shows 0 dependents.
  4331. 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`);
  4332. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.go'], exclude: [] } });
  4333. await cg.indexAll();
  4334. cg.resolveReferences();
  4335. expect(cg.getFileDependents('codec/json.go')).toContain('codec/api.go');
  4336. cg.destroy();
  4337. } finally {
  4338. cleanupTempDir(dir);
  4339. }
  4340. });
  4341. });
  4342. describe('C# records (blast-radius recall)', () => {
  4343. // Records are ubiquitous in modern C# (DTOs, value objects, CQRS messages),
  4344. // but `record` / `record struct` declarations weren't extracted as types — so
  4345. // every reference, generic-type-argument, and `new` of a record dropped on the
  4346. // floor and the defining file showed 0 dependents. (#237)
  4347. it('extracts a record as a graph node (record class + record struct)', () => {
  4348. const r = extractFromSource('r.cs', `namespace P;\npublic record Box(int N);\npublic record struct Pt(int X);\n`);
  4349. expect(r.nodes.find((n) => n.name === 'Box' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  4350. expect(r.nodes.find((n) => n.name === 'Pt' && (n.kind === 'class' || n.kind === 'struct'))).toBeDefined();
  4351. });
  4352. it('resolves references / instantiations of a record across files', async () => {
  4353. const dir = createTempDir();
  4354. try {
  4355. fs.writeFileSync(path.join(dir, 'types.cs'), `namespace P;\npublic record Box(int N);\n`);
  4356. // Box is used as a generic type argument and instantiated — both require
  4357. // Box to be a node to resolve.
  4358. fs.writeFileSync(
  4359. path.join(dir, 'use.cs'),
  4360. `using System.Collections.Generic;\nnamespace P;\npublic class User {\n public IEnumerable<Box> Boxes { get; }\n public Box Make() => new Box(1);\n}\n`
  4361. );
  4362. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.cs'], exclude: [] } });
  4363. await cg.indexAll();
  4364. cg.resolveReferences();
  4365. expect(cg.getFileDependents('types.cs')).toContain('use.cs');
  4366. cg.destroy();
  4367. } finally {
  4368. cleanupTempDir(dir);
  4369. }
  4370. });
  4371. });
  4372. describe('Rust cross-module recall', () => {
  4373. function rustProject(files: Record<string, string>): string {
  4374. const dir = createTempDir();
  4375. fs.writeFileSync(path.join(dir, 'Cargo.toml'), '[package]\nname = "proj"\nversion = "0.1.0"\nedition = "2021"\n');
  4376. fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
  4377. for (const [rel, content] of Object.entries(files)) {
  4378. const full = path.join(dir, 'src', rel);
  4379. fs.mkdirSync(path.dirname(full), { recursive: true });
  4380. fs.writeFileSync(full, content);
  4381. }
  4382. return dir;
  4383. }
  4384. it('extracts a struct literal `Foo { .. }` as an instantiation across modules', async () => {
  4385. const dir = rustProject({
  4386. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  4387. 'types.rs': 'pub struct Widget { pub n: i32 }\n',
  4388. 'consumer.rs': 'use crate::types::Widget;\npub fn build() -> Widget { Widget { n: 1 } }\n',
  4389. });
  4390. try {
  4391. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4392. await cg.indexAll();
  4393. cg.resolveReferences();
  4394. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  4395. cg.destroy();
  4396. } finally { cleanupTempDir(dir); }
  4397. });
  4398. it('extracts trait method declarations and bridges trait dispatch to the impl', async () => {
  4399. const dir = rustProject({
  4400. 'lib.rs': 'pub mod types;\npub mod consumer;\n',
  4401. 'types.rs': 'pub trait Render { fn render(&self) -> i32; }\n',
  4402. // Mine implements Render structurally; reached via &dyn Render dispatch.
  4403. 'consumer.rs': 'use crate::types::Render;\npub struct Mine { pub x: i32 }\nimpl Render for Mine { fn render(&self) -> i32 { self.x } }\n',
  4404. });
  4405. try {
  4406. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4407. await cg.indexAll();
  4408. cg.resolveReferences();
  4409. // implements edge (Mine -> Render) makes types.rs a dependent of consumer.rs's struct.
  4410. expect(cg.getFileDependents('src/types.rs')).toContain('src/consumer.rs');
  4411. cg.destroy();
  4412. } finally { cleanupTempDir(dir); }
  4413. });
  4414. it('links `pub use` re-export hubs to the modules they re-export', async () => {
  4415. const dir = rustProject({
  4416. 'lib.rs': 'pub mod api;\n',
  4417. 'api/mod.rs': 'mod widget;\npub use self::widget::Widget;\n',
  4418. 'api/widget.rs': 'pub struct Widget { pub n: i32 }\n',
  4419. });
  4420. try {
  4421. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4422. await cg.indexAll();
  4423. cg.resolveReferences();
  4424. // The re-export hub depends on the module it re-exports from.
  4425. expect(cg.getFileDependents('src/api/widget.rs')).toContain('src/api/mod.rs');
  4426. cg.destroy();
  4427. } finally { cleanupTempDir(dir); }
  4428. });
  4429. it('resolves a qualified path to the correct module when the leaf name collides', async () => {
  4430. const dir = rustProject({
  4431. 'lib.rs': 'pub mod fast;\npub mod slow;\npub mod hub;\n',
  4432. 'fast.rs': 'pub fn read() -> i32 { 1 }\n',
  4433. 'slow.rs': 'pub fn read() -> i32 { 2 }\n',
  4434. // `read` exists in BOTH fast.rs and slow.rs — module-path resolution must
  4435. // send this re-export to fast.rs specifically, not name-match either.
  4436. 'hub.rs': 'pub use crate::fast::read;\n',
  4437. });
  4438. try {
  4439. const cg = CodeGraph.initSync(dir, { config: { include: ['src/**/*.rs'], exclude: [] } });
  4440. await cg.indexAll();
  4441. cg.resolveReferences();
  4442. expect(cg.getFileDependents('src/fast.rs')).toContain('src/hub.rs');
  4443. expect(cg.getFileDependents('src/slow.rs')).not.toContain('src/hub.rs');
  4444. cg.destroy();
  4445. } finally { cleanupTempDir(dir); }
  4446. });
  4447. });
  4448. describe('Java annotations (blast-radius recall)', () => {
  4449. it('indexes @interface definitions and links @Annotation usages to them', async () => {
  4450. const dir = createTempDir();
  4451. try {
  4452. fs.mkdirSync(path.join(dir, 'p'), { recursive: true });
  4453. // The annotation DEFINITION must be a node, and the @MyAnno usages (which
  4454. // live inside a `modifiers` node on the class/field/method) must extract.
  4455. fs.writeFileSync(path.join(dir, 'p', 'MyAnno.java'), `package p;\npublic @interface MyAnno { String value() default ""; }\n`);
  4456. fs.writeFileSync(
  4457. path.join(dir, 'p', 'User.java'),
  4458. `package p;\n@MyAnno("c")\npublic class User {\n @MyAnno("f") int field;\n @MyAnno("m") void go() {}\n}\n`
  4459. );
  4460. const cg = CodeGraph.initSync(dir, { config: { include: ['**/*.java'], exclude: [] } });
  4461. await cg.indexAll();
  4462. cg.resolveReferences();
  4463. expect(cg.getFileDependents('p/MyAnno.java')).toContain('p/User.java');
  4464. cg.destroy();
  4465. } finally { cleanupTempDir(dir); }
  4466. });
  4467. });
  4468. describe('Swift property wrappers / attributes (blast-radius recall)', () => {
  4469. it('links a @propertyWrapper usage to the wrapper type', async () => {
  4470. const dir = createTempDir();
  4471. try {
  4472. fs.mkdirSync(path.join(dir, 'Sources', 'M'), { recursive: true });
  4473. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Wrap.swift'), `@propertyWrapper\npublic struct Argument<T> { public var wrappedValue: T }\n`);
  4474. // `@Argument` is a Swift attribute on a stored property — it lives in the
  4475. // property's `modifiers` and Swift doesn't extract instance properties as
  4476. // their own nodes, so without the fix the wrapper type has no users.
  4477. fs.writeFileSync(path.join(dir, 'Sources', 'M', 'Cmd.swift'), `public struct MyCommand {\n @Argument var name: String\n @Argument var count: Int\n}\n`);
  4478. const cg = CodeGraph.initSync(dir, { config: { include: ['Sources/**/*.swift'], exclude: [] } });
  4479. await cg.indexAll();
  4480. cg.resolveReferences();
  4481. expect(cg.getFileDependents('Sources/M/Wrap.swift')).toContain('Sources/M/Cmd.swift');
  4482. cg.destroy();
  4483. } finally { cleanupTempDir(dir); }
  4484. });
  4485. });