extraction.test.ts 132 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132
  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 } 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('should track function calls', () => {
  200. const code = `
  201. function main() {
  202. const result = processData();
  203. console.log(result);
  204. }
  205. `;
  206. const result = extractFromSource('main.ts', code);
  207. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  208. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  209. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  210. });
  211. });
  212. describe('Arrow Function Export Extraction', () => {
  213. it('should extract exported arrow functions assigned to const', () => {
  214. const code = `
  215. export const useAuth = (): AuthContextValue => {
  216. return useContext(AuthContext);
  217. };
  218. `;
  219. const result = extractFromSource('hooks.ts', code);
  220. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  221. expect(funcNode).toBeDefined();
  222. expect(funcNode).toMatchObject({
  223. kind: 'function',
  224. name: 'useAuth',
  225. isExported: true,
  226. });
  227. });
  228. it('should extract exported function expressions assigned to const', () => {
  229. const code = `
  230. export const processData = function(input: string): string {
  231. return input.trim();
  232. };
  233. `;
  234. const result = extractFromSource('utils.ts', code);
  235. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  236. expect(funcNode).toBeDefined();
  237. expect(funcNode).toMatchObject({
  238. kind: 'function',
  239. name: 'processData',
  240. isExported: true,
  241. });
  242. });
  243. it('should not extract non-exported arrow functions as exported', () => {
  244. const code = `
  245. const internalHelper = () => {
  246. return 42;
  247. };
  248. `;
  249. const result = extractFromSource('internal.ts', code);
  250. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  251. expect(helperNode).toBeDefined();
  252. expect(helperNode?.isExported).toBeFalsy();
  253. });
  254. it('should still skip truly anonymous arrow functions', () => {
  255. const code = `
  256. const items = [1, 2, 3].map((x) => x * 2);
  257. `;
  258. const result = extractFromSource('anon.ts', code);
  259. // The inline arrow function passed to .map() has no variable_declarator parent
  260. // and should remain anonymous (skipped)
  261. const anonFunctions = result.nodes.filter(
  262. (n) => n.kind === 'function' && n.name === '<anonymous>'
  263. );
  264. expect(anonFunctions).toHaveLength(0);
  265. });
  266. it('should extract multiple exported arrow functions from the same file', () => {
  267. const code = `
  268. export const add = (a: number, b: number): number => a + b;
  269. export const subtract = (a: number, b: number): number => a - b;
  270. const internal = () => 'not exported';
  271. `;
  272. const result = extractFromSource('math.ts', code);
  273. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  274. expect(exported).toHaveLength(2);
  275. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  276. const internalNode = result.nodes.find((n) => n.name === 'internal');
  277. expect(internalNode).toBeDefined();
  278. expect(internalNode?.isExported).toBeFalsy();
  279. });
  280. it('should extract arrow functions in JavaScript files', () => {
  281. const code = `
  282. export const fetchData = async () => {
  283. const response = await fetch('/api/data');
  284. return response.json();
  285. };
  286. `;
  287. const result = extractFromSource('api.js', code);
  288. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  289. expect(funcNode).toBeDefined();
  290. expect(funcNode).toMatchObject({
  291. kind: 'function',
  292. name: 'fetchData',
  293. isExported: true,
  294. });
  295. });
  296. });
  297. describe('Type Alias Extraction', () => {
  298. it('should extract exported type aliases in TypeScript', () => {
  299. const code = `
  300. export type AuthContextValue = {
  301. user: User | null;
  302. login: () => void;
  303. logout: () => void;
  304. };
  305. `;
  306. const result = extractFromSource('types.ts', code);
  307. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  308. expect(typeNode).toMatchObject({
  309. kind: 'type_alias',
  310. name: 'AuthContextValue',
  311. isExported: true,
  312. });
  313. });
  314. it('should extract non-exported type aliases', () => {
  315. const code = `
  316. type InternalState = {
  317. loading: boolean;
  318. error: string | null;
  319. };
  320. `;
  321. const result = extractFromSource('internal.ts', code);
  322. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  323. expect(typeNode).toMatchObject({
  324. kind: 'type_alias',
  325. name: 'InternalState',
  326. isExported: false,
  327. });
  328. });
  329. it('should extract multiple type aliases from the same file', () => {
  330. const code = `
  331. export type UnitSystem = 'metric' | 'imperial';
  332. export type DateFormat = 'ISO' | 'US' | 'EU';
  333. type Internal = string;
  334. `;
  335. const result = extractFromSource('config.ts', code);
  336. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  337. expect(typeAliases).toHaveLength(3);
  338. const exported = typeAliases.filter((n) => n.isExported);
  339. expect(exported).toHaveLength(2);
  340. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  341. });
  342. });
  343. describe('Exported Variable Extraction', () => {
  344. it('should extract exported const with call expression (Zustand store)', () => {
  345. const code = `
  346. export const useUIStore = create<UIState>((set) => ({
  347. isOpen: false,
  348. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  349. }));
  350. `;
  351. const result = extractFromSource('store.ts', code);
  352. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
  353. expect(varNode).toBeDefined();
  354. expect(varNode?.isExported).toBe(true);
  355. });
  356. it('should extract exported const with object literal', () => {
  357. const code = `
  358. export const config = {
  359. apiUrl: 'https://api.example.com',
  360. timeout: 5000,
  361. };
  362. `;
  363. const result = extractFromSource('config.ts', code);
  364. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
  365. expect(varNode).toBeDefined();
  366. expect(varNode?.isExported).toBe(true);
  367. });
  368. it('should extract exported const with array literal', () => {
  369. const code = `
  370. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  371. `;
  372. const result = extractFromSource('constants.ts', code);
  373. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
  374. expect(varNode).toBeDefined();
  375. expect(varNode?.isExported).toBe(true);
  376. });
  377. it('should extract exported const with primitive value', () => {
  378. const code = `
  379. export const MAX_RETRIES = 3;
  380. export const API_VERSION = "v2";
  381. `;
  382. const result = extractFromSource('constants.ts', code);
  383. const variables = result.nodes.filter((n) => n.kind === 'constant');
  384. expect(variables).toHaveLength(2);
  385. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  386. });
  387. it('should NOT duplicate arrow functions as both function and variable', () => {
  388. const code = `
  389. export const useAuth = () => {
  390. return useContext(AuthContext);
  391. };
  392. `;
  393. const result = extractFromSource('hooks.ts', code);
  394. // Should be extracted as function (from arrow function handler), NOT as variable
  395. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  396. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  397. expect(funcNodes).toHaveLength(1);
  398. expect(varNodes).toHaveLength(0);
  399. });
  400. it('should extract non-exported const as non-exported variable', () => {
  401. const code = `
  402. const internalConfig = {
  403. debug: true,
  404. };
  405. `;
  406. const result = extractFromSource('internal.ts', code);
  407. // Non-exported const at file level should be extracted as a constant (not exported)
  408. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  409. expect(varNodes).toHaveLength(1);
  410. expect(varNodes[0]?.isExported).toBeFalsy();
  411. });
  412. it('should extract Zod schema exports', () => {
  413. const code = `
  414. export const userSchema = z.object({
  415. id: z.string(),
  416. name: z.string(),
  417. email: z.string().email(),
  418. });
  419. `;
  420. const result = extractFromSource('schemas.ts', code);
  421. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
  422. expect(varNode).toBeDefined();
  423. expect(varNode?.isExported).toBe(true);
  424. });
  425. it('should extract XState machine exports', () => {
  426. const code = `
  427. export const authMachine = createMachine({
  428. id: "auth",
  429. initial: "idle",
  430. states: {
  431. idle: {},
  432. authenticated: {},
  433. },
  434. });
  435. `;
  436. const result = extractFromSource('machine.ts', code);
  437. const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
  438. expect(varNode).toBeDefined();
  439. expect(varNode?.isExported).toBe(true);
  440. });
  441. it('should extract calls from a top-level variable initializer (issue #425)', () => {
  442. const code = `
  443. import { getTokenMp } from './api/upload';
  444. const token = getTokenMp();
  445. `;
  446. const result = extractFromSource('app.ts', code);
  447. const call = result.unresolvedReferences.find(
  448. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  449. );
  450. expect(call).toBeDefined();
  451. });
  452. });
  453. describe('File Node Extraction', () => {
  454. it('should create a file-kind node for each parsed file', () => {
  455. const code = `
  456. export function greet(name: string): string {
  457. return "Hello " + name;
  458. }
  459. `;
  460. const result = extractFromSource('greeter.ts', code);
  461. const fileNode = result.nodes.find((n) => n.kind === 'file');
  462. expect(fileNode).toBeDefined();
  463. expect(fileNode?.name).toBe('greeter.ts');
  464. expect(fileNode?.filePath).toBe('greeter.ts');
  465. expect(fileNode?.language).toBe('typescript');
  466. expect(fileNode?.startLine).toBe(1);
  467. });
  468. it('should create file nodes for Python files', () => {
  469. const code = `
  470. def main():
  471. pass
  472. `;
  473. const result = extractFromSource('main.py', code);
  474. const fileNode = result.nodes.find((n) => n.kind === 'file');
  475. expect(fileNode).toBeDefined();
  476. expect(fileNode?.name).toBe('main.py');
  477. expect(fileNode?.language).toBe('python');
  478. });
  479. it('should create containment edges from file node to top-level declarations', () => {
  480. const code = `
  481. export function foo() {}
  482. export function bar() {}
  483. `;
  484. const result = extractFromSource('fns.ts', code);
  485. const fileNode = result.nodes.find((n) => n.kind === 'file');
  486. expect(fileNode).toBeDefined();
  487. // There should be contains edges from the file node to each function
  488. const containsEdges = result.edges.filter(
  489. (e) => e.source === fileNode?.id && e.kind === 'contains'
  490. );
  491. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  492. });
  493. });
  494. describe('Python Extraction', () => {
  495. it('should extract function definitions', () => {
  496. const code = `
  497. def calculate_total(items: list, tax_rate: float) -> float:
  498. """Calculate total with tax."""
  499. subtotal = sum(item.price for item in items)
  500. return subtotal * (1 + tax_rate)
  501. `;
  502. const result = extractFromSource('calc.py', code);
  503. const fileNode = result.nodes.find((n) => n.kind === 'file');
  504. expect(fileNode).toBeDefined();
  505. const funcNode = result.nodes.find((n) => n.kind === 'function');
  506. expect(funcNode).toMatchObject({
  507. kind: 'function',
  508. name: 'calculate_total',
  509. language: 'python',
  510. });
  511. });
  512. it('should extract class definitions', () => {
  513. const code = `
  514. class UserService:
  515. """Service for managing users."""
  516. def __init__(self, db):
  517. self.db = db
  518. def get_user(self, user_id: str) -> User:
  519. return self.db.find_user(user_id)
  520. `;
  521. const result = extractFromSource('service.py', code);
  522. const classNode = result.nodes.find((n) => n.kind === 'class');
  523. expect(classNode).toBeDefined();
  524. expect(classNode?.name).toBe('UserService');
  525. });
  526. });
  527. describe('Go Extraction', () => {
  528. it('should extract function declarations', () => {
  529. const code = `
  530. package main
  531. func ProcessOrder(order Order) (Receipt, error) {
  532. // Process the order
  533. return Receipt{}, nil
  534. }
  535. `;
  536. const result = extractFromSource('main.go', code);
  537. const funcNode = result.nodes.find((n) => n.kind === 'function');
  538. expect(funcNode).toBeDefined();
  539. expect(funcNode?.name).toBe('ProcessOrder');
  540. });
  541. it('should extract method declarations', () => {
  542. const code = `
  543. package main
  544. type Service struct {
  545. db *Database
  546. }
  547. func (s *Service) GetUser(id string) (*User, error) {
  548. return s.db.FindUser(id)
  549. }
  550. `;
  551. const result = extractFromSource('service.go', code);
  552. const methodNode = result.nodes.find((n) => n.kind === 'method');
  553. expect(methodNode).toBeDefined();
  554. expect(methodNode?.name).toBe('GetUser');
  555. });
  556. });
  557. describe('Rust Extraction', () => {
  558. it('should extract function declarations', () => {
  559. const code = `
  560. pub fn process_data(input: &str) -> Result<Output, Error> {
  561. // Process data
  562. Ok(Output::new())
  563. }
  564. `;
  565. const result = extractFromSource('lib.rs', code);
  566. const funcNode = result.nodes.find((n) => n.kind === 'function');
  567. expect(funcNode).toBeDefined();
  568. expect(funcNode?.name).toBe('process_data');
  569. expect(funcNode?.visibility).toBe('public');
  570. });
  571. it('should extract struct declarations', () => {
  572. const code = `
  573. pub struct User {
  574. pub id: String,
  575. pub name: String,
  576. email: String,
  577. }
  578. `;
  579. const result = extractFromSource('models.rs', code);
  580. const structNode = result.nodes.find((n) => n.kind === 'struct');
  581. expect(structNode).toBeDefined();
  582. expect(structNode?.name).toBe('User');
  583. });
  584. it('should extract trait declarations', () => {
  585. const code = `
  586. pub trait Repository {
  587. fn find(&self, id: &str) -> Option<Entity>;
  588. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  589. }
  590. `;
  591. const result = extractFromSource('traits.rs', code);
  592. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  593. expect(traitNode).toBeDefined();
  594. expect(traitNode?.name).toBe('Repository');
  595. });
  596. it('should extract impl Trait for Type as implements edges', () => {
  597. const code = `
  598. pub struct MyCache {}
  599. pub trait Cache {
  600. fn get(&self, key: &str) -> Option<String>;
  601. }
  602. impl Cache for MyCache {
  603. fn get(&self, key: &str) -> Option<String> {
  604. None
  605. }
  606. }
  607. `;
  608. const result = extractFromSource('cache.rs', code);
  609. // Should have an unresolved reference for implements
  610. const implRef = result.unresolvedReferences.find(
  611. (r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
  612. );
  613. expect(implRef).toBeDefined();
  614. // The struct MyCache should be the source
  615. const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
  616. expect(myCacheNode).toBeDefined();
  617. expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
  618. });
  619. it('should extract trait supertraits as extends references', () => {
  620. const code = `
  621. pub trait Display {}
  622. pub trait Error: Display {
  623. fn description(&self) -> &str;
  624. }
  625. `;
  626. const result = extractFromSource('error.rs', code);
  627. const extendsRef = result.unresolvedReferences.find(
  628. (r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
  629. );
  630. expect(extendsRef).toBeDefined();
  631. const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
  632. expect(errorTrait).toBeDefined();
  633. expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
  634. });
  635. it('should not create implements edges for plain impl blocks', () => {
  636. const code = `
  637. pub struct Counter {
  638. count: u32,
  639. }
  640. impl Counter {
  641. pub fn new() -> Counter {
  642. Counter { count: 0 }
  643. }
  644. pub fn increment(&mut self) {
  645. self.count += 1;
  646. }
  647. }
  648. `;
  649. const result = extractFromSource('counter.rs', code);
  650. // Should have no implements references (no trait involved)
  651. const implRefs = result.unresolvedReferences.filter(
  652. (r) => r.referenceKind === 'implements'
  653. );
  654. expect(implRefs).toHaveLength(0);
  655. });
  656. });
  657. describe('Java Extraction', () => {
  658. it('should extract class declarations', () => {
  659. const code = `
  660. public class UserService {
  661. private final UserRepository repository;
  662. public UserService(UserRepository repository) {
  663. this.repository = repository;
  664. }
  665. public User getUser(String id) {
  666. return repository.findById(id);
  667. }
  668. }
  669. `;
  670. const result = extractFromSource('UserService.java', code);
  671. const classNode = result.nodes.find((n) => n.kind === 'class');
  672. expect(classNode).toBeDefined();
  673. expect(classNode?.name).toBe('UserService');
  674. expect(classNode?.visibility).toBe('public');
  675. });
  676. it('should extract method declarations', () => {
  677. const code = `
  678. public class Calculator {
  679. public static int add(int a, int b) {
  680. return a + b;
  681. }
  682. }
  683. `;
  684. const result = extractFromSource('Calculator.java', code);
  685. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  686. expect(methodNode).toBeDefined();
  687. expect(methodNode?.isStatic).toBe(true);
  688. });
  689. });
  690. describe('C# Extraction', () => {
  691. it('should extract class declarations', () => {
  692. const code = `
  693. public class OrderService
  694. {
  695. private readonly IOrderRepository _repository;
  696. public OrderService(IOrderRepository repository)
  697. {
  698. _repository = repository;
  699. }
  700. public async Task<Order> GetOrderAsync(string id)
  701. {
  702. return await _repository.FindByIdAsync(id);
  703. }
  704. }
  705. `;
  706. const result = extractFromSource('OrderService.cs', code);
  707. const classNode = result.nodes.find((n) => n.kind === 'class');
  708. expect(classNode).toBeDefined();
  709. expect(classNode?.name).toBe('OrderService');
  710. expect(classNode?.visibility).toBe('public');
  711. });
  712. });
  713. describe('PHP Extraction', () => {
  714. it('should extract class declarations', () => {
  715. const code = `<?php
  716. class UserController
  717. {
  718. private UserService $userService;
  719. public function __construct(UserService $userService)
  720. {
  721. $this->userService = $userService;
  722. }
  723. public function show(string $id): User
  724. {
  725. return $this->userService->find($id);
  726. }
  727. }
  728. `;
  729. const result = extractFromSource('UserController.php', code);
  730. const classNode = result.nodes.find((n) => n.kind === 'class');
  731. expect(classNode).toBeDefined();
  732. expect(classNode?.name).toBe('UserController');
  733. });
  734. it('should extract class inheritance (extends) and interface implementation', () => {
  735. const code = `<?php
  736. class ChildController extends BaseController implements Serializable, JsonSerializable
  737. {
  738. public function serialize(): string
  739. {
  740. return json_encode($this);
  741. }
  742. }
  743. `;
  744. const result = extractFromSource('ChildController.php', code);
  745. const classNode = result.nodes.find((n) => n.kind === 'class');
  746. expect(classNode).toBeDefined();
  747. expect(classNode?.name).toBe('ChildController');
  748. const extendsRef = result.unresolvedReferences.find(
  749. (r) => r.referenceKind === 'extends'
  750. );
  751. expect(extendsRef).toBeDefined();
  752. expect(extendsRef?.referenceName).toBe('BaseController');
  753. const implementsRefs = result.unresolvedReferences.filter(
  754. (r) => r.referenceKind === 'implements'
  755. );
  756. expect(implementsRefs.length).toBe(2);
  757. expect(implementsRefs.map((r) => r.referenceName)).toContain('Serializable');
  758. expect(implementsRefs.map((r) => r.referenceName)).toContain('JsonSerializable');
  759. });
  760. });
  761. describe('Swift Extraction', () => {
  762. it('should extract class declarations', () => {
  763. const code = `
  764. public class NetworkManager {
  765. private let session: URLSession
  766. public init(session: URLSession = .shared) {
  767. self.session = session
  768. }
  769. public func fetchData(from url: URL) async throws -> Data {
  770. let (data, _) = try await session.data(from: url)
  771. return data
  772. }
  773. }
  774. `;
  775. const result = extractFromSource('NetworkManager.swift', code);
  776. const classNode = result.nodes.find((n) => n.kind === 'class');
  777. expect(classNode).toBeDefined();
  778. expect(classNode?.name).toBe('NetworkManager');
  779. });
  780. it('should extract function declarations', () => {
  781. const code = `
  782. func calculateSum(_ numbers: [Int]) -> Int {
  783. return numbers.reduce(0, +)
  784. }
  785. public func formatCurrency(amount: Double) -> String {
  786. return String(format: "$%.2f", amount)
  787. }
  788. `;
  789. const result = extractFromSource('utils.swift', code);
  790. const functions = result.nodes.filter((n) => n.kind === 'function');
  791. expect(functions.length).toBeGreaterThanOrEqual(1);
  792. });
  793. it('should extract struct declarations', () => {
  794. const code = `
  795. public struct User {
  796. let id: UUID
  797. var name: String
  798. var email: String
  799. func displayName() -> String {
  800. return name
  801. }
  802. }
  803. `;
  804. const result = extractFromSource('User.swift', code);
  805. const structNode = result.nodes.find((n) => n.kind === 'struct');
  806. expect(structNode).toBeDefined();
  807. expect(structNode?.name).toBe('User');
  808. });
  809. it('should extract protocol declarations', () => {
  810. const code = `
  811. public protocol Repository {
  812. associatedtype Entity
  813. func find(id: String) async throws -> Entity?
  814. func save(_ entity: Entity) async throws
  815. }
  816. `;
  817. const result = extractFromSource('Repository.swift', code);
  818. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  819. expect(protocolNode).toBeDefined();
  820. expect(protocolNode?.name).toBe('Repository');
  821. });
  822. it('should extract class inheritance and protocol conformance', () => {
  823. const code = `
  824. class DataRequest: Request {
  825. func validate() {}
  826. }
  827. class UploadRequest: DataRequest, Sendable {
  828. func upload() {}
  829. }
  830. enum AFError: Error {
  831. case invalidURL
  832. }
  833. struct HTTPMethod: RawRepresentable {
  834. let rawValue: String
  835. }
  836. protocol UploadConvertible: URLRequestConvertible {
  837. func asURLRequest() throws -> URLRequest
  838. }
  839. `;
  840. const result = extractFromSource('Inheritance.swift', code);
  841. const extendsRefs = result.unresolvedReferences.filter(
  842. (r) => r.referenceKind === 'extends'
  843. );
  844. // DataRequest extends Request
  845. expect(extendsRefs.find((r) => r.referenceName === 'Request')).toBeDefined();
  846. // UploadRequest extends DataRequest and Sendable
  847. expect(extendsRefs.find((r) => r.referenceName === 'DataRequest')).toBeDefined();
  848. expect(extendsRefs.find((r) => r.referenceName === 'Sendable')).toBeDefined();
  849. // AFError extends Error
  850. expect(extendsRefs.find((r) => r.referenceName === 'Error')).toBeDefined();
  851. // HTTPMethod extends RawRepresentable
  852. expect(extendsRefs.find((r) => r.referenceName === 'RawRepresentable')).toBeDefined();
  853. // UploadConvertible extends URLRequestConvertible
  854. expect(extendsRefs.find((r) => r.referenceName === 'URLRequestConvertible')).toBeDefined();
  855. });
  856. });
  857. describe('Kotlin Extraction', () => {
  858. it('should extract class declarations', () => {
  859. const code = `
  860. class UserRepository(private val database: Database) {
  861. fun findById(id: String): User? {
  862. return database.query("SELECT * FROM users WHERE id = ?", id)
  863. }
  864. suspend fun save(user: User) {
  865. database.insert(user)
  866. }
  867. }
  868. `;
  869. const result = extractFromSource('UserRepository.kt', code);
  870. const classNode = result.nodes.find((n) => n.kind === 'class');
  871. expect(classNode).toBeDefined();
  872. expect(classNode?.name).toBe('UserRepository');
  873. });
  874. it('should extract function declarations', () => {
  875. const code = `
  876. fun calculateTotal(items: List<Item>): Double {
  877. return items.sumOf { it.price }
  878. }
  879. suspend fun fetchUserData(userId: String): User {
  880. return api.getUser(userId)
  881. }
  882. `;
  883. const result = extractFromSource('utils.kt', code);
  884. const functions = result.nodes.filter((n) => n.kind === 'function');
  885. expect(functions.length).toBeGreaterThanOrEqual(1);
  886. });
  887. it('should detect suspend functions as async', () => {
  888. const code = `
  889. suspend fun loadData(): List<String> {
  890. delay(1000)
  891. return listOf("a", "b", "c")
  892. }
  893. `;
  894. const result = extractFromSource('loader.kt', code);
  895. const funcNode = result.nodes.find((n) => n.kind === 'function');
  896. expect(funcNode).toBeDefined();
  897. expect(funcNode?.isAsync).toBe(true);
  898. });
  899. it('should extract fun interface declarations', () => {
  900. const code = `
  901. fun interface OnObjectRetainedListener {
  902. fun onObjectRetained()
  903. }
  904. `;
  905. const result = extractFromSource('listener.kt', code);
  906. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  907. expect(ifaceNode).toBeDefined();
  908. expect(ifaceNode?.name).toBe('OnObjectRetainedListener');
  909. const methodNode = result.nodes.find((n) => n.kind === 'method');
  910. expect(methodNode).toBeDefined();
  911. expect(methodNode?.name).toBe('onObjectRetained');
  912. expect(methodNode?.qualifiedName).toBe('OnObjectRetainedListener::onObjectRetained');
  913. });
  914. it('should extract complex fun interface with nested classes', () => {
  915. const code = `
  916. fun interface EventListener {
  917. fun onEvent(event: Event)
  918. sealed class Event {
  919. class DumpingHeap : Event()
  920. }
  921. }
  922. `;
  923. const result = extractFromSource('events.kt', code);
  924. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  925. expect(ifaceNode).toBeDefined();
  926. expect(ifaceNode?.name).toBe('EventListener');
  927. // Nested sealed class should still be extracted (as sibling due to grammar limitations)
  928. const eventClass = result.nodes.find((n) => n.kind === 'class' && n.name === 'Event');
  929. expect(eventClass).toBeDefined();
  930. const dumpingHeap = result.nodes.find((n) => n.kind === 'class' && n.name === 'DumpingHeap');
  931. expect(dumpingHeap).toBeDefined();
  932. });
  933. it('should not affect regular function declarations', () => {
  934. const code = `
  935. fun interface MyCallback {
  936. fun invoke(value: Int)
  937. }
  938. fun regularFunction(): String {
  939. return "hello"
  940. }
  941. `;
  942. const result = extractFromSource('mixed.kt', code);
  943. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  944. expect(ifaceNode).toBeDefined();
  945. expect(ifaceNode?.name).toBe('MyCallback');
  946. const funcNode = result.nodes.find((n) => n.kind === 'function');
  947. expect(funcNode).toBeDefined();
  948. expect(funcNode?.name).toBe('regularFunction');
  949. });
  950. it('should extract fun interface with annotation on method (Pattern 2b)', () => {
  951. // When the SAM method has annotations like @Throws, tree-sitter produces a different
  952. // misparse: function_declaration > ERROR("interface Name {") instead of
  953. // function_declaration > user_type("interface"). This is the OkHttp Interceptor pattern.
  954. const code = `
  955. import java.io.IOException
  956. fun interface Interceptor {
  957. @Throws(IOException::class)
  958. fun intercept(chain: Chain): Response
  959. }
  960. `;
  961. const result = extractFromSource('interceptor.kt', code);
  962. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  963. expect(ifaceNode).toBeDefined();
  964. expect(ifaceNode?.name).toBe('Interceptor');
  965. });
  966. it('should extract methods from interface with nested fun interface', () => {
  967. // When an interface contains a nested `fun interface`, tree-sitter misparsed
  968. // the parent body as ERROR. Methods inside should still be extracted.
  969. const code = `
  970. interface WebSocket {
  971. fun request(): Request
  972. fun send(text: String): Boolean
  973. fun cancel()
  974. fun interface Factory {
  975. fun newWebSocket(request: Request): WebSocket
  976. }
  977. }
  978. `;
  979. const result = extractFromSource('websocket.kt', code);
  980. const wsIface = result.nodes.find((n) => n.kind === 'interface' && n.name === 'WebSocket');
  981. expect(wsIface).toBeDefined();
  982. const methods = result.nodes.filter((n) => n.kind === 'method' && n.qualifiedName?.startsWith('WebSocket::'));
  983. const methodNames = methods.map((m) => m.name);
  984. expect(methodNames).toContain('request');
  985. expect(methodNames).toContain('send');
  986. expect(methodNames).toContain('cancel');
  987. });
  988. });
  989. describe('Dart Extraction', () => {
  990. it('should extract class declarations', () => {
  991. const code = `
  992. class UserService {
  993. final Database _db;
  994. Future<User> findById(String id) async {
  995. return await _db.query(id);
  996. }
  997. void _privateMethod() {}
  998. }
  999. `;
  1000. const result = extractFromSource('service.dart', code);
  1001. const classNode = result.nodes.find((n) => n.kind === 'class');
  1002. expect(classNode).toBeDefined();
  1003. expect(classNode?.name).toBe('UserService');
  1004. expect(classNode?.visibility).toBe('public');
  1005. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  1006. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  1007. const findById = methodNodes.find((m) => m.name === 'findById');
  1008. expect(findById).toBeDefined();
  1009. expect(findById?.isAsync).toBe(true);
  1010. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  1011. expect(privateMethod).toBeDefined();
  1012. expect(privateMethod?.visibility).toBe('private');
  1013. // Dart models a method body as a SIBLING of the signature, so the method
  1014. // node must be extended to span its body (not just the signature line) —
  1015. // required for body-level analysis (callees, the callback synthesizer).
  1016. expect(findById!.endLine).toBeGreaterThan(findById!.startLine);
  1017. });
  1018. it('should extract top-level function declarations', () => {
  1019. const code = `
  1020. void topLevelFunction(String name) {
  1021. print(name);
  1022. }
  1023. `;
  1024. const result = extractFromSource('utils.dart', code);
  1025. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1026. expect(funcNode).toBeDefined();
  1027. expect(funcNode?.name).toBe('topLevelFunction');
  1028. expect(funcNode?.language).toBe('dart');
  1029. });
  1030. it('should extract enum declarations', () => {
  1031. const code = `
  1032. enum Status { active, inactive, pending }
  1033. `;
  1034. const result = extractFromSource('models.dart', code);
  1035. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1036. expect(enumNode).toBeDefined();
  1037. expect(enumNode?.name).toBe('Status');
  1038. });
  1039. it('should extract mixin declarations', () => {
  1040. const code = `
  1041. mixin LoggerMixin {
  1042. void log(String message) {}
  1043. }
  1044. `;
  1045. const result = extractFromSource('mixins.dart', code);
  1046. const classNode = result.nodes.find((n) => n.kind === 'class');
  1047. expect(classNode).toBeDefined();
  1048. expect(classNode?.name).toBe('LoggerMixin');
  1049. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1050. expect(methodNode).toBeDefined();
  1051. expect(methodNode?.name).toBe('log');
  1052. });
  1053. it('should extract extension declarations', () => {
  1054. const code = `
  1055. extension StringExt on String {
  1056. bool get isBlank => trim().isEmpty;
  1057. }
  1058. `;
  1059. const result = extractFromSource('extensions.dart', code);
  1060. const classNode = result.nodes.find((n) => n.kind === 'class');
  1061. expect(classNode).toBeDefined();
  1062. expect(classNode?.name).toBe('StringExt');
  1063. });
  1064. it('should detect static methods', () => {
  1065. const code = `
  1066. class Utils {
  1067. static void doWork() {}
  1068. }
  1069. `;
  1070. const result = extractFromSource('utils.dart', code);
  1071. const methodNode = result.nodes.find((n) => n.kind === 'method');
  1072. expect(methodNode).toBeDefined();
  1073. expect(methodNode?.name).toBe('doWork');
  1074. expect(methodNode?.isStatic).toBe(true);
  1075. });
  1076. it('should detect async functions', () => {
  1077. const code = `
  1078. Future<String> fetchData() async {
  1079. return await http.get('/data');
  1080. }
  1081. `;
  1082. const result = extractFromSource('api.dart', code);
  1083. const funcNode = result.nodes.find((n) => n.kind === 'function');
  1084. expect(funcNode).toBeDefined();
  1085. expect(funcNode?.name).toBe('fetchData');
  1086. expect(funcNode?.isAsync).toBe(true);
  1087. });
  1088. it('should detect private visibility via underscore convention', () => {
  1089. const code = `
  1090. void _privateHelper() {}
  1091. void publicFunction() {}
  1092. `;
  1093. const result = extractFromSource('helpers.dart', code);
  1094. const functions = result.nodes.filter((n) => n.kind === 'function');
  1095. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  1096. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  1097. expect(privateFunc?.visibility).toBe('private');
  1098. expect(publicFunc?.visibility).toBe('public');
  1099. });
  1100. });
  1101. describe('Import Extraction', () => {
  1102. describe('TypeScript/JavaScript imports', () => {
  1103. it('should extract default imports', () => {
  1104. const code = `import React from 'react';`;
  1105. const result = extractFromSource('app.tsx', code);
  1106. const importNode = result.nodes.find((n) => n.kind === 'import');
  1107. expect(importNode).toBeDefined();
  1108. expect(importNode?.name).toBe('react');
  1109. expect(importNode?.signature).toBe("import React from 'react';");
  1110. });
  1111. it('should extract named imports', () => {
  1112. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  1113. const result = extractFromSource('icons.tsx', code);
  1114. const importNode = result.nodes.find((n) => n.kind === 'import');
  1115. expect(importNode).toBeDefined();
  1116. expect(importNode?.name).toBe('@phosphor-icons/react');
  1117. expect(importNode?.signature).toContain('Bug');
  1118. expect(importNode?.signature).toContain('Database');
  1119. });
  1120. it('should extract namespace imports', () => {
  1121. const code = `import * as Icons from '@phosphor-icons/react';`;
  1122. const result = extractFromSource('icons.tsx', code);
  1123. const importNode = result.nodes.find((n) => n.kind === 'import');
  1124. expect(importNode).toBeDefined();
  1125. expect(importNode?.name).toBe('@phosphor-icons/react');
  1126. expect(importNode?.signature).toContain('* as Icons');
  1127. });
  1128. it('should extract side-effect imports', () => {
  1129. const code = `import './styles.css';`;
  1130. const result = extractFromSource('app.tsx', code);
  1131. const importNode = result.nodes.find((n) => n.kind === 'import');
  1132. expect(importNode).toBeDefined();
  1133. expect(importNode?.name).toBe('./styles.css');
  1134. });
  1135. it('should extract mixed imports (default + named)', () => {
  1136. const code = `import React, { useState, useEffect } from 'react';`;
  1137. const result = extractFromSource('app.tsx', code);
  1138. const importNode = result.nodes.find((n) => n.kind === 'import');
  1139. expect(importNode).toBeDefined();
  1140. expect(importNode?.name).toBe('react');
  1141. expect(importNode?.signature).toContain('React');
  1142. expect(importNode?.signature).toContain('useState');
  1143. expect(importNode?.signature).toContain('useEffect');
  1144. });
  1145. it('should extract multiple import statements', () => {
  1146. const code = `
  1147. import React from 'react';
  1148. import { Button } from './components';
  1149. import './styles.css';
  1150. `;
  1151. const result = extractFromSource('app.tsx', code);
  1152. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1153. expect(importNodes.length).toBe(3);
  1154. const names = importNodes.map((n) => n.name);
  1155. expect(names).toContain('react');
  1156. expect(names).toContain('./components');
  1157. expect(names).toContain('./styles.css');
  1158. });
  1159. it('should extract type imports', () => {
  1160. const code = `import type { FC, ReactNode } from 'react';`;
  1161. const result = extractFromSource('types.ts', code);
  1162. const importNode = result.nodes.find((n) => n.kind === 'import');
  1163. expect(importNode).toBeDefined();
  1164. expect(importNode?.name).toBe('react');
  1165. expect(importNode?.signature).toContain('type');
  1166. expect(importNode?.signature).toContain('FC');
  1167. });
  1168. it('should extract aliased named imports', () => {
  1169. const code = `import { useState as useStateAlias } from 'react';`;
  1170. const result = extractFromSource('hooks.ts', code);
  1171. const importNode = result.nodes.find((n) => n.kind === 'import');
  1172. expect(importNode).toBeDefined();
  1173. expect(importNode?.name).toBe('react');
  1174. expect(importNode?.signature).toContain('useState');
  1175. expect(importNode?.signature).toContain('useStateAlias');
  1176. });
  1177. it('should extract relative path imports', () => {
  1178. const code = `import { helper } from '../utils/helper';`;
  1179. const result = extractFromSource('components/Button.tsx', code);
  1180. const importNode = result.nodes.find((n) => n.kind === 'import');
  1181. expect(importNode).toBeDefined();
  1182. expect(importNode?.name).toBe('../utils/helper');
  1183. expect(importNode?.signature).toContain('helper');
  1184. });
  1185. });
  1186. describe('Python imports', () => {
  1187. it('should extract simple import statement', () => {
  1188. const code = `import json`;
  1189. const result = extractFromSource('utils.py', code);
  1190. const importNode = result.nodes.find((n) => n.kind === 'import');
  1191. expect(importNode).toBeDefined();
  1192. expect(importNode?.name).toBe('json');
  1193. });
  1194. it('should extract from import statement', () => {
  1195. const code = `from os import path`;
  1196. const result = extractFromSource('utils.py', code);
  1197. const importNode = result.nodes.find((n) => n.kind === 'import');
  1198. expect(importNode).toBeDefined();
  1199. expect(importNode?.name).toBe('os');
  1200. expect(importNode?.signature).toContain('path');
  1201. });
  1202. it('should extract multiple imports from same module', () => {
  1203. const code = `from typing import List, Dict, Optional`;
  1204. const result = extractFromSource('types.py', code);
  1205. const importNode = result.nodes.find((n) => n.kind === 'import');
  1206. expect(importNode).toBeDefined();
  1207. expect(importNode?.name).toBe('typing');
  1208. expect(importNode?.signature).toContain('List');
  1209. expect(importNode?.signature).toContain('Dict');
  1210. });
  1211. it('should extract multiple import statements', () => {
  1212. const code = `
  1213. import os
  1214. import sys
  1215. `;
  1216. const result = extractFromSource('main.py', code);
  1217. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1218. expect(importNodes.length).toBe(2);
  1219. const names = importNodes.map((n) => n.name);
  1220. expect(names).toContain('os');
  1221. expect(names).toContain('sys');
  1222. });
  1223. it('should extract aliased import', () => {
  1224. const code = `import numpy as np`;
  1225. const result = extractFromSource('data.py', code);
  1226. const importNode = result.nodes.find((n) => n.kind === 'import');
  1227. expect(importNode).toBeDefined();
  1228. expect(importNode?.name).toBe('numpy');
  1229. expect(importNode?.signature).toContain('as np');
  1230. });
  1231. it('should extract relative import', () => {
  1232. const code = `from .utils import helper`;
  1233. const result = extractFromSource('module.py', code);
  1234. const importNode = result.nodes.find((n) => n.kind === 'import');
  1235. expect(importNode).toBeDefined();
  1236. expect(importNode?.name).toBe('.utils');
  1237. expect(importNode?.signature).toContain('helper');
  1238. });
  1239. it('should extract wildcard import', () => {
  1240. const code = `from typing import *`;
  1241. const result = extractFromSource('types.py', code);
  1242. const importNode = result.nodes.find((n) => n.kind === 'import');
  1243. expect(importNode).toBeDefined();
  1244. expect(importNode?.name).toBe('typing');
  1245. expect(importNode?.signature).toContain('*');
  1246. });
  1247. });
  1248. describe('Rust imports', () => {
  1249. it('should extract simple use declaration', () => {
  1250. const code = `use std::io;`;
  1251. const result = extractFromSource('main.rs', code);
  1252. const importNode = result.nodes.find((n) => n.kind === 'import');
  1253. expect(importNode).toBeDefined();
  1254. expect(importNode?.name).toBe('std');
  1255. expect(importNode?.signature).toBe('use std::io;');
  1256. });
  1257. it('should extract scoped use list', () => {
  1258. const code = `use std::{ffi::OsStr, io, path::Path};`;
  1259. const result = extractFromSource('main.rs', code);
  1260. const importNode = result.nodes.find((n) => n.kind === 'import');
  1261. expect(importNode).toBeDefined();
  1262. expect(importNode?.name).toBe('std');
  1263. expect(importNode?.signature).toContain('ffi::OsStr');
  1264. expect(importNode?.signature).toContain('path::Path');
  1265. });
  1266. it('should extract crate imports', () => {
  1267. const code = `use crate::error::Error;`;
  1268. const result = extractFromSource('lib.rs', code);
  1269. const importNode = result.nodes.find((n) => n.kind === 'import');
  1270. expect(importNode).toBeDefined();
  1271. expect(importNode?.name).toBe('crate');
  1272. });
  1273. it('should extract super imports', () => {
  1274. const code = `use super::utils;`;
  1275. const result = extractFromSource('submod.rs', code);
  1276. const importNode = result.nodes.find((n) => n.kind === 'import');
  1277. expect(importNode).toBeDefined();
  1278. expect(importNode?.name).toBe('super');
  1279. });
  1280. it('should extract external crate imports', () => {
  1281. const code = `use serde::{Serialize, Deserialize};`;
  1282. const result = extractFromSource('types.rs', code);
  1283. const importNode = result.nodes.find((n) => n.kind === 'import');
  1284. expect(importNode).toBeDefined();
  1285. expect(importNode?.name).toBe('serde');
  1286. expect(importNode?.signature).toContain('Serialize');
  1287. expect(importNode?.signature).toContain('Deserialize');
  1288. });
  1289. });
  1290. describe('Go imports', () => {
  1291. it('should extract single import', () => {
  1292. const code = `
  1293. package main
  1294. import "fmt"
  1295. `;
  1296. const result = extractFromSource('main.go', code);
  1297. const importNode = result.nodes.find((n) => n.kind === 'import');
  1298. expect(importNode).toBeDefined();
  1299. expect(importNode?.name).toBe('fmt');
  1300. });
  1301. it('should extract grouped imports', () => {
  1302. const code = `
  1303. package main
  1304. import (
  1305. "fmt"
  1306. "os"
  1307. "encoding/json"
  1308. )
  1309. `;
  1310. const result = extractFromSource('main.go', code);
  1311. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1312. expect(importNodes.length).toBe(3);
  1313. const names = importNodes.map((n) => n.name);
  1314. expect(names).toContain('fmt');
  1315. expect(names).toContain('os');
  1316. expect(names).toContain('encoding/json');
  1317. });
  1318. it('should extract aliased import', () => {
  1319. const code = `
  1320. package main
  1321. import f "fmt"
  1322. `;
  1323. const result = extractFromSource('main.go', code);
  1324. const importNode = result.nodes.find((n) => n.kind === 'import');
  1325. expect(importNode).toBeDefined();
  1326. expect(importNode?.name).toBe('fmt');
  1327. expect(importNode?.signature).toContain('f');
  1328. });
  1329. it('should extract dot import', () => {
  1330. const code = `
  1331. package main
  1332. import . "math"
  1333. `;
  1334. const result = extractFromSource('main.go', code);
  1335. const importNode = result.nodes.find((n) => n.kind === 'import');
  1336. expect(importNode).toBeDefined();
  1337. expect(importNode?.name).toBe('math');
  1338. expect(importNode?.signature).toContain('.');
  1339. });
  1340. it('should extract blank import', () => {
  1341. const code = `
  1342. package main
  1343. import _ "github.com/go-sql-driver/mysql"
  1344. `;
  1345. const result = extractFromSource('main.go', code);
  1346. const importNode = result.nodes.find((n) => n.kind === 'import');
  1347. expect(importNode).toBeDefined();
  1348. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1349. expect(importNode?.signature).toContain('_');
  1350. });
  1351. });
  1352. describe('Swift imports', () => {
  1353. it('should extract simple import', () => {
  1354. const code = `import Foundation`;
  1355. const result = extractFromSource('main.swift', code);
  1356. const importNode = result.nodes.find((n) => n.kind === 'import');
  1357. expect(importNode).toBeDefined();
  1358. expect(importNode?.name).toBe('Foundation');
  1359. expect(importNode?.signature).toBe('import Foundation');
  1360. });
  1361. it('should extract @testable import', () => {
  1362. const code = `@testable import Alamofire`;
  1363. const result = extractFromSource('Tests.swift', code);
  1364. const importNode = result.nodes.find((n) => n.kind === 'import');
  1365. expect(importNode).toBeDefined();
  1366. expect(importNode?.name).toBe('Alamofire');
  1367. expect(importNode?.signature).toContain('@testable');
  1368. });
  1369. it('should extract @preconcurrency import', () => {
  1370. const code = `@preconcurrency import Security`;
  1371. const result = extractFromSource('Auth.swift', code);
  1372. const importNode = result.nodes.find((n) => n.kind === 'import');
  1373. expect(importNode).toBeDefined();
  1374. expect(importNode?.name).toBe('Security');
  1375. });
  1376. it('should extract multiple imports', () => {
  1377. const code = `
  1378. import Foundation
  1379. import UIKit
  1380. import Alamofire
  1381. `;
  1382. const result = extractFromSource('App.swift', code);
  1383. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1384. expect(importNodes.length).toBe(3);
  1385. const names = importNodes.map((n) => n.name);
  1386. expect(names).toContain('Foundation');
  1387. expect(names).toContain('UIKit');
  1388. expect(names).toContain('Alamofire');
  1389. });
  1390. });
  1391. describe('Kotlin imports', () => {
  1392. it('should extract simple import', () => {
  1393. const code = `import java.io.IOException`;
  1394. const result = extractFromSource('Main.kt', code);
  1395. const importNode = result.nodes.find((n) => n.kind === 'import');
  1396. expect(importNode).toBeDefined();
  1397. expect(importNode?.name).toBe('java.io.IOException');
  1398. expect(importNode?.signature).toBe('import java.io.IOException');
  1399. });
  1400. it('should extract aliased import', () => {
  1401. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1402. const result = extractFromSource('Utils.kt', code);
  1403. const importNode = result.nodes.find((n) => n.kind === 'import');
  1404. expect(importNode).toBeDefined();
  1405. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1406. expect(importNode?.signature).toContain('as RequestBuilder');
  1407. });
  1408. it('should extract wildcard import', () => {
  1409. const code = `import java.util.concurrent.TimeUnit.*`;
  1410. const result = extractFromSource('Time.kt', code);
  1411. const importNode = result.nodes.find((n) => n.kind === 'import');
  1412. expect(importNode).toBeDefined();
  1413. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1414. expect(importNode?.signature).toContain('.*');
  1415. });
  1416. it('should extract multiple imports', () => {
  1417. const code = `
  1418. import java.io.IOException
  1419. import kotlin.test.assertFailsWith
  1420. import okhttp3.OkHttpClient
  1421. `;
  1422. const result = extractFromSource('Test.kt', code);
  1423. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1424. expect(importNodes.length).toBe(3);
  1425. const names = importNodes.map((n) => n.name);
  1426. expect(names).toContain('java.io.IOException');
  1427. expect(names).toContain('kotlin.test.assertFailsWith');
  1428. expect(names).toContain('okhttp3.OkHttpClient');
  1429. });
  1430. });
  1431. describe('Java imports', () => {
  1432. it('should extract simple import', () => {
  1433. const code = `import java.util.List;`;
  1434. const result = extractFromSource('Main.java', code);
  1435. const importNode = result.nodes.find((n) => n.kind === 'import');
  1436. expect(importNode).toBeDefined();
  1437. expect(importNode?.name).toBe('java.util.List');
  1438. expect(importNode?.signature).toBe('import java.util.List;');
  1439. });
  1440. it('should extract static import', () => {
  1441. const code = `import static java.util.Collections.emptyList;`;
  1442. const result = extractFromSource('Utils.java', code);
  1443. const importNode = result.nodes.find((n) => n.kind === 'import');
  1444. expect(importNode).toBeDefined();
  1445. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1446. expect(importNode?.signature).toContain('static');
  1447. });
  1448. it('should extract wildcard import', () => {
  1449. const code = `import java.util.*;`;
  1450. const result = extractFromSource('App.java', code);
  1451. const importNode = result.nodes.find((n) => n.kind === 'import');
  1452. expect(importNode).toBeDefined();
  1453. expect(importNode?.name).toBe('java.util');
  1454. expect(importNode?.signature).toContain('.*');
  1455. });
  1456. it('should extract nested class import', () => {
  1457. const code = `import java.util.Map.Entry;`;
  1458. const result = extractFromSource('MapUtil.java', code);
  1459. const importNode = result.nodes.find((n) => n.kind === 'import');
  1460. expect(importNode).toBeDefined();
  1461. expect(importNode?.name).toBe('java.util.Map.Entry');
  1462. });
  1463. it('should extract multiple imports', () => {
  1464. const code = `
  1465. import java.util.List;
  1466. import java.util.Map;
  1467. import java.io.IOException;
  1468. `;
  1469. const result = extractFromSource('Service.java', code);
  1470. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1471. expect(importNodes.length).toBe(3);
  1472. const names = importNodes.map((n) => n.name);
  1473. expect(names).toContain('java.util.List');
  1474. expect(names).toContain('java.util.Map');
  1475. expect(names).toContain('java.io.IOException');
  1476. });
  1477. });
  1478. describe('C# imports', () => {
  1479. it('should extract simple using', () => {
  1480. const code = `using System;`;
  1481. const result = extractFromSource('Program.cs', code);
  1482. const importNode = result.nodes.find((n) => n.kind === 'import');
  1483. expect(importNode).toBeDefined();
  1484. expect(importNode?.name).toBe('System');
  1485. expect(importNode?.signature).toBe('using System;');
  1486. });
  1487. it('should extract qualified using', () => {
  1488. const code = `using System.Collections.Generic;`;
  1489. const result = extractFromSource('Utils.cs', code);
  1490. const importNode = result.nodes.find((n) => n.kind === 'import');
  1491. expect(importNode).toBeDefined();
  1492. expect(importNode?.name).toBe('System.Collections.Generic');
  1493. });
  1494. it('should extract static using', () => {
  1495. const code = `using static System.Console;`;
  1496. const result = extractFromSource('App.cs', code);
  1497. const importNode = result.nodes.find((n) => n.kind === 'import');
  1498. expect(importNode).toBeDefined();
  1499. expect(importNode?.name).toBe('System.Console');
  1500. expect(importNode?.signature).toContain('static');
  1501. });
  1502. it('should extract alias using', () => {
  1503. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1504. const result = extractFromSource('Types.cs', code);
  1505. const importNode = result.nodes.find((n) => n.kind === 'import');
  1506. expect(importNode).toBeDefined();
  1507. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1508. expect(importNode?.signature).toContain('MyList =');
  1509. });
  1510. it('should extract multiple usings', () => {
  1511. const code = `
  1512. using System;
  1513. using System.Threading.Tasks;
  1514. using Microsoft.Extensions.DependencyInjection;
  1515. `;
  1516. const result = extractFromSource('Service.cs', code);
  1517. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1518. expect(importNodes.length).toBe(3);
  1519. const names = importNodes.map((n) => n.name);
  1520. expect(names).toContain('System');
  1521. expect(names).toContain('System.Threading.Tasks');
  1522. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1523. });
  1524. });
  1525. describe('PHP imports', () => {
  1526. it('should extract simple use', () => {
  1527. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1528. const result = extractFromSource('Test.php', code);
  1529. const importNode = result.nodes.find((n) => n.kind === 'import');
  1530. expect(importNode).toBeDefined();
  1531. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1532. });
  1533. it('should extract aliased use', () => {
  1534. const code = `<?php use Mockery as m;`;
  1535. const result = extractFromSource('Test.php', code);
  1536. const importNode = result.nodes.find((n) => n.kind === 'import');
  1537. expect(importNode).toBeDefined();
  1538. expect(importNode?.name).toBe('Mockery');
  1539. expect(importNode?.signature).toContain('as m');
  1540. });
  1541. it('should extract function use', () => {
  1542. const code = `<?php use function Illuminate\\Support\\env;`;
  1543. const result = extractFromSource('helpers.php', code);
  1544. const importNode = result.nodes.find((n) => n.kind === 'import');
  1545. expect(importNode).toBeDefined();
  1546. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1547. expect(importNode?.signature).toContain('function');
  1548. });
  1549. it('should extract grouped use', () => {
  1550. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1551. const result = extractFromSource('Models.php', code);
  1552. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1553. expect(importNodes.length).toBe(2);
  1554. const names = importNodes.map((n) => n.name);
  1555. expect(names).toContain('Illuminate\\Database\\Model');
  1556. expect(names).toContain('Illuminate\\Database\\Builder');
  1557. });
  1558. it('should extract multiple uses', () => {
  1559. const code = `<?php
  1560. use Illuminate\\Support\\Collection;
  1561. use Illuminate\\Support\\Str;
  1562. use Closure;
  1563. `;
  1564. const result = extractFromSource('Service.php', code);
  1565. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1566. expect(importNodes.length).toBe(3);
  1567. const names = importNodes.map((n) => n.name);
  1568. expect(names).toContain('Illuminate\\Support\\Collection');
  1569. expect(names).toContain('Illuminate\\Support\\Str');
  1570. expect(names).toContain('Closure');
  1571. });
  1572. });
  1573. describe('Ruby imports', () => {
  1574. it('should extract require', () => {
  1575. const code = `require 'json'`;
  1576. const result = extractFromSource('app.rb', code);
  1577. const importNode = result.nodes.find((n) => n.kind === 'import');
  1578. expect(importNode).toBeDefined();
  1579. expect(importNode?.name).toBe('json');
  1580. expect(importNode?.signature).toBe("require 'json'");
  1581. });
  1582. it('should extract require with path', () => {
  1583. const code = `require 'active_support/core_ext/string'`;
  1584. const result = extractFromSource('config.rb', code);
  1585. const importNode = result.nodes.find((n) => n.kind === 'import');
  1586. expect(importNode).toBeDefined();
  1587. expect(importNode?.name).toBe('active_support/core_ext/string');
  1588. });
  1589. it('should extract require_relative', () => {
  1590. const code = `require_relative '../test_helper'`;
  1591. const result = extractFromSource('test/my_test.rb', code);
  1592. const importNode = result.nodes.find((n) => n.kind === 'import');
  1593. expect(importNode).toBeDefined();
  1594. expect(importNode?.name).toBe('../test_helper');
  1595. expect(importNode?.signature).toContain('require_relative');
  1596. });
  1597. it('should not extract non-require calls', () => {
  1598. const code = `puts 'hello'`;
  1599. const result = extractFromSource('app.rb', code);
  1600. const importNode = result.nodes.find((n) => n.kind === 'import');
  1601. expect(importNode).toBeUndefined();
  1602. });
  1603. it('should extract multiple requires', () => {
  1604. const code = `
  1605. require 'json'
  1606. require 'yaml'
  1607. require_relative 'helper'
  1608. `;
  1609. const result = extractFromSource('lib.rb', code);
  1610. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1611. expect(importNodes.length).toBe(3);
  1612. const names = importNodes.map((n) => n.name);
  1613. expect(names).toContain('json');
  1614. expect(names).toContain('yaml');
  1615. expect(names).toContain('helper');
  1616. });
  1617. });
  1618. describe('Ruby modules', () => {
  1619. it('should extract module as module node with containment', () => {
  1620. const code = `
  1621. module CachedCounting
  1622. def self.disable
  1623. @enabled = false
  1624. end
  1625. def perform_increment!(key, count)
  1626. write_cache!(key, count)
  1627. end
  1628. end
  1629. `;
  1630. const result = extractFromSource('concerns/cached_counting.rb', code);
  1631. const moduleNode = result.nodes.find((n) => n.kind === 'module' && n.name === 'CachedCounting');
  1632. expect(moduleNode).toBeDefined();
  1633. expect(moduleNode?.qualifiedName).toBe('CachedCounting');
  1634. // Methods inside module should have module-qualified names
  1635. const disableMethod = result.nodes.find((n) => n.name === 'disable' && n.kind === 'method');
  1636. expect(disableMethod).toBeDefined();
  1637. expect(disableMethod?.qualifiedName).toBe('CachedCounting::disable');
  1638. const incrementMethod = result.nodes.find((n) => n.name === 'perform_increment!' && n.kind === 'method');
  1639. expect(incrementMethod).toBeDefined();
  1640. expect(incrementMethod?.qualifiedName).toBe('CachedCounting::perform_increment!');
  1641. // Containment edge from module to methods
  1642. const containsEdges = result.edges.filter((e) => e.source === moduleNode?.id && e.kind === 'contains');
  1643. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  1644. });
  1645. it('should handle nested modules with classes', () => {
  1646. const code = `
  1647. module Discourse
  1648. module Auth
  1649. class AuthProvider
  1650. def authenticate(params)
  1651. validate(params)
  1652. end
  1653. end
  1654. end
  1655. end
  1656. `;
  1657. const result = extractFromSource('lib/auth.rb', code);
  1658. const discourseModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Discourse');
  1659. expect(discourseModule).toBeDefined();
  1660. const authModule = result.nodes.find((n) => n.kind === 'module' && n.name === 'Auth');
  1661. expect(authModule).toBeDefined();
  1662. expect(authModule?.qualifiedName).toBe('Discourse::Auth');
  1663. const authProvider = result.nodes.find((n) => n.kind === 'class' && n.name === 'AuthProvider');
  1664. expect(authProvider).toBeDefined();
  1665. expect(authProvider?.qualifiedName).toBe('Discourse::Auth::AuthProvider');
  1666. const authMethod = result.nodes.find((n) => n.name === 'authenticate');
  1667. expect(authMethod).toBeDefined();
  1668. expect(authMethod?.qualifiedName).toBe('Discourse::Auth::AuthProvider::authenticate');
  1669. });
  1670. });
  1671. describe('C/C++ imports', () => {
  1672. it('should extract system include', () => {
  1673. const code = `#include <iostream>`;
  1674. const result = extractFromSource('main.cpp', code);
  1675. const importNode = result.nodes.find((n) => n.kind === 'import');
  1676. expect(importNode).toBeDefined();
  1677. expect(importNode?.name).toBe('iostream');
  1678. expect(importNode?.signature).toBe('#include <iostream>');
  1679. });
  1680. it('should extract system include with path', () => {
  1681. const code = `#include <nlohmann/json.hpp>`;
  1682. const result = extractFromSource('app.cpp', code);
  1683. const importNode = result.nodes.find((n) => n.kind === 'import');
  1684. expect(importNode).toBeDefined();
  1685. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1686. });
  1687. it('should extract local include', () => {
  1688. const code = `#include "myheader.h"`;
  1689. const result = extractFromSource('main.cpp', code);
  1690. const importNode = result.nodes.find((n) => n.kind === 'import');
  1691. expect(importNode).toBeDefined();
  1692. expect(importNode?.name).toBe('myheader.h');
  1693. });
  1694. it('should extract C header', () => {
  1695. const code = `#include <stdio.h>`;
  1696. const result = extractFromSource('main.c', code);
  1697. const importNode = result.nodes.find((n) => n.kind === 'import');
  1698. expect(importNode).toBeDefined();
  1699. expect(importNode?.name).toBe('stdio.h');
  1700. });
  1701. it('should extract multiple includes', () => {
  1702. const code = `
  1703. #include <iostream>
  1704. #include <vector>
  1705. #include "config.h"
  1706. `;
  1707. const result = extractFromSource('app.cpp', code);
  1708. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1709. expect(importNodes.length).toBe(3);
  1710. const names = importNodes.map((n) => n.name);
  1711. expect(names).toContain('iostream');
  1712. expect(names).toContain('vector');
  1713. expect(names).toContain('config.h');
  1714. });
  1715. });
  1716. describe('Dart imports', () => {
  1717. it('should extract dart: import', () => {
  1718. const code = `import 'dart:async';`;
  1719. const result = extractFromSource('main.dart', code);
  1720. const importNode = result.nodes.find((n) => n.kind === 'import');
  1721. expect(importNode).toBeDefined();
  1722. expect(importNode?.name).toBe('dart:async');
  1723. expect(importNode?.signature).toBe("import 'dart:async';");
  1724. });
  1725. it('should extract package import', () => {
  1726. const code = `import 'package:flutter/material.dart';`;
  1727. const result = extractFromSource('app.dart', code);
  1728. const importNode = result.nodes.find((n) => n.kind === 'import');
  1729. expect(importNode).toBeDefined();
  1730. expect(importNode?.name).toBe('package:flutter/material.dart');
  1731. });
  1732. it('should extract aliased import', () => {
  1733. const code = `import 'package:http/http.dart' as http;`;
  1734. const result = extractFromSource('api.dart', code);
  1735. const importNode = result.nodes.find((n) => n.kind === 'import');
  1736. expect(importNode).toBeDefined();
  1737. expect(importNode?.name).toBe('package:http/http.dart');
  1738. expect(importNode?.signature).toContain('as http');
  1739. });
  1740. it('should extract multiple imports', () => {
  1741. const code = `
  1742. import 'dart:async';
  1743. import 'dart:convert';
  1744. import 'package:flutter/material.dart';
  1745. `;
  1746. const result = extractFromSource('main.dart', code);
  1747. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1748. expect(importNodes.length).toBe(3);
  1749. const names = importNodes.map((n) => n.name);
  1750. expect(names).toContain('dart:async');
  1751. expect(names).toContain('dart:convert');
  1752. expect(names).toContain('package:flutter/material.dart');
  1753. });
  1754. it('should extract relative import', () => {
  1755. const code = `import '../utils/helpers.dart';`;
  1756. const result = extractFromSource('lib/main.dart', code);
  1757. const importNode = result.nodes.find((n) => n.kind === 'import');
  1758. expect(importNode).toBeDefined();
  1759. expect(importNode?.name).toBe('../utils/helpers.dart');
  1760. });
  1761. });
  1762. describe('Liquid imports', () => {
  1763. it('should extract render tag', () => {
  1764. const code = `{% render 'loading-spinner' %}`;
  1765. const result = extractFromSource('template.liquid', code);
  1766. const importNode = result.nodes.find((n) => n.kind === 'import');
  1767. expect(importNode).toBeDefined();
  1768. expect(importNode?.name).toBe('loading-spinner');
  1769. expect(importNode?.signature).toContain('render');
  1770. });
  1771. it('should extract section tag', () => {
  1772. const code = `{% section 'header' %}`;
  1773. const result = extractFromSource('layout/theme.liquid', code);
  1774. const importNode = result.nodes.find((n) => n.kind === 'import');
  1775. expect(importNode).toBeDefined();
  1776. expect(importNode?.name).toBe('header');
  1777. expect(importNode?.signature).toContain('section');
  1778. });
  1779. it('should extract include tag', () => {
  1780. const code = `{% include 'icon-cart' %}`;
  1781. const result = extractFromSource('snippets/header.liquid', code);
  1782. const importNode = result.nodes.find((n) => n.kind === 'import');
  1783. expect(importNode).toBeDefined();
  1784. expect(importNode?.name).toBe('icon-cart');
  1785. expect(importNode?.signature).toContain('include');
  1786. });
  1787. it('should extract render with whitespace control', () => {
  1788. const code = `{%- render 'price' -%}`;
  1789. const result = extractFromSource('snippets/product.liquid', code);
  1790. const importNode = result.nodes.find((n) => n.kind === 'import');
  1791. expect(importNode).toBeDefined();
  1792. expect(importNode?.name).toBe('price');
  1793. });
  1794. it('should extract multiple imports', () => {
  1795. const code = `
  1796. {% section 'header' %}
  1797. {% render 'loading-spinner' %}
  1798. {% render 'cart-drawer' %}
  1799. `;
  1800. const result = extractFromSource('layout/theme.liquid', code);
  1801. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1802. expect(importNodes.length).toBe(3);
  1803. const names = importNodes.map((n) => n.name);
  1804. expect(names).toContain('header');
  1805. expect(names).toContain('loading-spinner');
  1806. expect(names).toContain('cart-drawer');
  1807. });
  1808. });
  1809. });
  1810. // =============================================================================
  1811. // Pascal / Delphi Extraction
  1812. // =============================================================================
  1813. describe('Pascal / Delphi Extraction', () => {
  1814. describe('Language detection', () => {
  1815. it('should detect Pascal files', () => {
  1816. expect(detectLanguage('UAuth.pas')).toBe('pascal');
  1817. expect(detectLanguage('App.dpr')).toBe('pascal');
  1818. expect(detectLanguage('Package.dpk')).toBe('pascal');
  1819. expect(detectLanguage('App.lpr')).toBe('pascal');
  1820. expect(detectLanguage('MainForm.dfm')).toBe('pascal');
  1821. expect(detectLanguage('MainForm.fmx')).toBe('pascal');
  1822. });
  1823. it('should report Pascal as supported', () => {
  1824. expect(isLanguageSupported('pascal')).toBe(true);
  1825. expect(getSupportedLanguages()).toContain('pascal');
  1826. });
  1827. });
  1828. describe('Unit extraction', () => {
  1829. it('should extract unit as module', () => {
  1830. const code = `unit MyUnit;\ninterface\nimplementation\nend.`;
  1831. const result = extractFromSource('MyUnit.pas', code);
  1832. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1833. expect(moduleNode).toBeDefined();
  1834. expect(moduleNode?.name).toBe('MyUnit');
  1835. expect(moduleNode?.language).toBe('pascal');
  1836. });
  1837. it('should extract program as module', () => {
  1838. const code = `program MyApp;\nbegin\nend.`;
  1839. const result = extractFromSource('MyApp.dpr', code);
  1840. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1841. expect(moduleNode).toBeDefined();
  1842. expect(moduleNode?.name).toBe('MyApp');
  1843. });
  1844. it('should fallback to filename when module name is empty', () => {
  1845. // Some .dpr templates use "program;" without a name
  1846. const code = `program;\nuses SysUtils;\nbegin\nend.`;
  1847. const result = extractFromSource('Console.dpr', code);
  1848. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  1849. expect(moduleNode).toBeDefined();
  1850. expect(moduleNode?.name).toBe('Console');
  1851. });
  1852. });
  1853. describe('Uses clause (imports)', () => {
  1854. it('should extract uses as individual imports', () => {
  1855. const code = `unit Test;\ninterface\nuses\n System.SysUtils,\n System.Classes;\nimplementation\nend.`;
  1856. const result = extractFromSource('Test.pas', code);
  1857. const imports = result.nodes.filter((n) => n.kind === 'import');
  1858. expect(imports.length).toBe(2);
  1859. expect(imports.map((n) => n.name)).toContain('System.SysUtils');
  1860. expect(imports.map((n) => n.name)).toContain('System.Classes');
  1861. });
  1862. it('should create unresolved references for imports', () => {
  1863. const code = `unit Test;\ninterface\nuses\n UAuth;\nimplementation\nend.`;
  1864. const result = extractFromSource('Test.pas', code);
  1865. const importRef = result.unresolvedReferences.find(
  1866. (r) => r.referenceKind === 'imports'
  1867. );
  1868. expect(importRef).toBeDefined();
  1869. expect(importRef?.referenceName).toBe('UAuth');
  1870. });
  1871. });
  1872. describe('Class extraction', () => {
  1873. it('should extract class declarations', () => {
  1874. const code = `unit Test;\ninterface\ntype\n TMyClass = class\n public\n procedure DoSomething;\n end;\nimplementation\nend.`;
  1875. const result = extractFromSource('Test.pas', code);
  1876. const classNode = result.nodes.find((n) => n.kind === 'class');
  1877. expect(classNode).toBeDefined();
  1878. expect(classNode?.name).toBe('TMyClass');
  1879. });
  1880. it('should extract class with inheritance', () => {
  1881. const code = `unit Test;\ninterface\ntype\n TChild = class(TParent)\n end;\nimplementation\nend.`;
  1882. const result = extractFromSource('Test.pas', code);
  1883. const extendsRef = result.unresolvedReferences.find(
  1884. (r) => r.referenceKind === 'extends'
  1885. );
  1886. expect(extendsRef).toBeDefined();
  1887. expect(extendsRef?.referenceName).toBe('TParent');
  1888. });
  1889. it('should extract class with interface implementation', () => {
  1890. const code = `unit Test;\ninterface\ntype\n TService = class(TInterfacedObject, ILogger)\n end;\nimplementation\nend.`;
  1891. const result = extractFromSource('Test.pas', code);
  1892. const extendsRef = result.unresolvedReferences.find(
  1893. (r) => r.referenceKind === 'extends'
  1894. );
  1895. const implementsRef = result.unresolvedReferences.find(
  1896. (r) => r.referenceKind === 'implements'
  1897. );
  1898. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  1899. expect(implementsRef?.referenceName).toBe('ILogger');
  1900. });
  1901. });
  1902. describe('Record extraction', () => {
  1903. it('should extract records as class nodes', () => {
  1904. const code = `unit Test;\ninterface\ntype\n TPoint = record\n X: Double;\n Y: Double;\n end;\nimplementation\nend.`;
  1905. const result = extractFromSource('Test.pas', code);
  1906. const classNode = result.nodes.find((n) => n.kind === 'class');
  1907. expect(classNode).toBeDefined();
  1908. expect(classNode?.name).toBe('TPoint');
  1909. const fields = result.nodes.filter((n) => n.kind === 'field');
  1910. expect(fields.length).toBe(2);
  1911. expect(fields.map((f) => f.name)).toContain('X');
  1912. expect(fields.map((f) => f.name)).toContain('Y');
  1913. });
  1914. });
  1915. describe('Interface extraction', () => {
  1916. it('should extract interface declarations', () => {
  1917. const code = `unit Test;\ninterface\ntype\n ILogger = interface\n procedure Log(const AMsg: string);\n end;\nimplementation\nend.`;
  1918. const result = extractFromSource('Test.pas', code);
  1919. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  1920. expect(ifaceNode).toBeDefined();
  1921. expect(ifaceNode?.name).toBe('ILogger');
  1922. });
  1923. });
  1924. describe('Method extraction', () => {
  1925. it('should extract methods with visibility', () => {
  1926. 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.`;
  1927. const result = extractFromSource('Test.pas', code);
  1928. const methods = result.nodes.filter((n) => n.kind === 'method');
  1929. expect(methods.length).toBe(2);
  1930. const createMethod = methods.find((m) => m.name === 'Create');
  1931. expect(createMethod?.visibility).toBe('public');
  1932. const getValue = methods.find((m) => m.name === 'GetValue');
  1933. expect(getValue?.visibility).toBe('public');
  1934. const fields = result.nodes.filter((n) => n.kind === 'field');
  1935. const fValue = fields.find((f) => f.name === 'FValue');
  1936. expect(fValue?.visibility).toBe('private');
  1937. });
  1938. it('should detect static methods (class methods)', () => {
  1939. const code = `unit Test;\ninterface\ntype\n THelper = class\n public\n class function Create: THelper; static;\n end;\nimplementation\nend.`;
  1940. const result = extractFromSource('Test.pas', code);
  1941. const methods = result.nodes.filter((n) => n.kind === 'method');
  1942. const staticMethod = methods.find((m) => m.name === 'Create');
  1943. expect(staticMethod?.isStatic).toBe(true);
  1944. });
  1945. });
  1946. describe('Enum extraction', () => {
  1947. it('should extract enums with members', () => {
  1948. const code = `unit Test;\ninterface\ntype\n TColor = (clRed, clGreen, clBlue);\nimplementation\nend.`;
  1949. const result = extractFromSource('Test.pas', code);
  1950. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  1951. expect(enumNode).toBeDefined();
  1952. expect(enumNode?.name).toBe('TColor');
  1953. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  1954. expect(members.length).toBe(3);
  1955. expect(members.map((m) => m.name)).toEqual(['clRed', 'clGreen', 'clBlue']);
  1956. });
  1957. });
  1958. describe('Property extraction', () => {
  1959. it('should extract properties', () => {
  1960. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n property Name: string read FName write FName;\n end;\nimplementation\nend.`;
  1961. const result = extractFromSource('Test.pas', code);
  1962. const propNode = result.nodes.find((n) => n.kind === 'property');
  1963. expect(propNode).toBeDefined();
  1964. expect(propNode?.name).toBe('Name');
  1965. expect(propNode?.visibility).toBe('public');
  1966. });
  1967. });
  1968. describe('Constant extraction', () => {
  1969. it('should extract constants', () => {
  1970. const code = `unit Test;\ninterface\nconst\n MAX_RETRIES = 3;\n APP_NAME = 'MyApp';\nimplementation\nend.`;
  1971. const result = extractFromSource('Test.pas', code);
  1972. const constants = result.nodes.filter((n) => n.kind === 'constant');
  1973. expect(constants.length).toBe(2);
  1974. expect(constants.map((c) => c.name)).toContain('MAX_RETRIES');
  1975. expect(constants.map((c) => c.name)).toContain('APP_NAME');
  1976. });
  1977. });
  1978. describe('Type alias extraction', () => {
  1979. it('should extract type aliases', () => {
  1980. const code = `unit Test;\ninterface\ntype\n TUserName = string;\nimplementation\nend.`;
  1981. const result = extractFromSource('Test.pas', code);
  1982. const aliasNode = result.nodes.find((n) => n.kind === 'type_alias');
  1983. expect(aliasNode).toBeDefined();
  1984. expect(aliasNode?.name).toBe('TUserName');
  1985. });
  1986. });
  1987. describe('Call extraction', () => {
  1988. it('should extract calls from implementation bodies', () => {
  1989. 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.`;
  1990. const result = extractFromSource('Test.pas', code);
  1991. const callRef = result.unresolvedReferences.find(
  1992. (r) => r.referenceKind === 'calls'
  1993. );
  1994. expect(callRef).toBeDefined();
  1995. expect(callRef?.referenceName).toBe('WriteLn');
  1996. });
  1997. });
  1998. describe('Containment edges', () => {
  1999. it('should create contains edges for class members', () => {
  2000. const code = `unit Test;\ninterface\ntype\n TObj = class\n public\n procedure Foo;\n end;\nimplementation\nend.`;
  2001. const result = extractFromSource('Test.pas', code);
  2002. const classNode = result.nodes.find((n) => n.kind === 'class');
  2003. const methodNode = result.nodes.find((n) => n.kind === 'method');
  2004. expect(classNode).toBeDefined();
  2005. expect(methodNode).toBeDefined();
  2006. const containsEdge = result.edges.find(
  2007. (e) => e.source === classNode?.id && e.target === methodNode?.id && e.kind === 'contains'
  2008. );
  2009. expect(containsEdge).toBeDefined();
  2010. });
  2011. });
  2012. describe('Full fixture: UAuth.pas', () => {
  2013. const code = `unit UAuth;
  2014. interface
  2015. uses
  2016. System.SysUtils,
  2017. System.Classes;
  2018. type
  2019. ITokenValidator = interface
  2020. ['{11111111-1111-1111-1111-111111111111}']
  2021. function Validate(const AToken: string): Boolean;
  2022. end;
  2023. TAuthService = class(TInterfacedObject, ITokenValidator)
  2024. private
  2025. FToken: string;
  2026. FLoginCount: Integer;
  2027. procedure IncLoginCount;
  2028. protected
  2029. function GetToken: string;
  2030. public
  2031. constructor Create;
  2032. destructor Destroy; override;
  2033. function Validate(const AToken: string): Boolean;
  2034. function Login(const AUser, APass: string): string;
  2035. property Token: string read GetToken;
  2036. property LoginCount: Integer read FLoginCount;
  2037. end;
  2038. implementation
  2039. constructor TAuthService.Create;
  2040. begin
  2041. inherited Create;
  2042. FToken := '';
  2043. FLoginCount := 0;
  2044. end;
  2045. destructor TAuthService.Destroy;
  2046. begin
  2047. FToken := '';
  2048. inherited Destroy;
  2049. end;
  2050. procedure TAuthService.IncLoginCount;
  2051. begin
  2052. Inc(FLoginCount);
  2053. end;
  2054. function TAuthService.GetToken: string;
  2055. begin
  2056. Result := FToken;
  2057. end;
  2058. function TAuthService.Validate(const AToken: string): Boolean;
  2059. begin
  2060. Result := AToken <> '';
  2061. end;
  2062. function TAuthService.Login(const AUser, APass: string): string;
  2063. begin
  2064. IncLoginCount;
  2065. if Validate(AUser + ':' + APass) then
  2066. begin
  2067. FToken := AUser;
  2068. Result := 'ok';
  2069. end
  2070. else
  2071. Result := '';
  2072. end;
  2073. end.`;
  2074. it('should extract all expected nodes', () => {
  2075. const result = extractFromSource('UAuth.pas', code);
  2076. expect(result.errors).toHaveLength(0);
  2077. // Module
  2078. const moduleNode = result.nodes.find((n) => n.kind === 'module');
  2079. expect(moduleNode?.name).toBe('UAuth');
  2080. // Imports
  2081. const imports = result.nodes.filter((n) => n.kind === 'import');
  2082. expect(imports.length).toBe(2);
  2083. // Interface
  2084. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  2085. expect(ifaceNode?.name).toBe('ITokenValidator');
  2086. // Class
  2087. const classNode = result.nodes.find((n) => n.kind === 'class');
  2088. expect(classNode?.name).toBe('TAuthService');
  2089. // Methods
  2090. const methods = result.nodes.filter((n) => n.kind === 'method');
  2091. expect(methods.length).toBeGreaterThanOrEqual(6);
  2092. expect(methods.map((m) => m.name)).toContain('Create');
  2093. expect(methods.map((m) => m.name)).toContain('Destroy');
  2094. expect(methods.map((m) => m.name)).toContain('Login');
  2095. // Fields
  2096. const fields = result.nodes.filter((n) => n.kind === 'field');
  2097. expect(fields.length).toBe(2);
  2098. expect(fields.every((f) => f.visibility === 'private')).toBe(true);
  2099. // Properties
  2100. const props = result.nodes.filter((n) => n.kind === 'property');
  2101. expect(props.length).toBe(2);
  2102. expect(props.map((p) => p.name)).toContain('Token');
  2103. expect(props.map((p) => p.name)).toContain('LoginCount');
  2104. });
  2105. it('should extract inheritance and interface implementation', () => {
  2106. const result = extractFromSource('UAuth.pas', code);
  2107. const extendsRef = result.unresolvedReferences.find(
  2108. (r) => r.referenceKind === 'extends'
  2109. );
  2110. expect(extendsRef?.referenceName).toBe('TInterfacedObject');
  2111. const implementsRef = result.unresolvedReferences.find(
  2112. (r) => r.referenceKind === 'implements'
  2113. );
  2114. expect(implementsRef?.referenceName).toBe('ITokenValidator');
  2115. });
  2116. it('should extract calls from implementation', () => {
  2117. const result = extractFromSource('UAuth.pas', code);
  2118. const callRefs = result.unresolvedReferences.filter(
  2119. (r) => r.referenceKind === 'calls'
  2120. );
  2121. expect(callRefs.map((r) => r.referenceName)).toContain('Inc');
  2122. expect(callRefs.map((r) => r.referenceName)).toContain('Validate');
  2123. });
  2124. });
  2125. describe('Full fixture: UTypes.pas', () => {
  2126. const code = `unit UTypes;
  2127. interface
  2128. uses
  2129. System.SysUtils;
  2130. const
  2131. C_MAX_RETRIES = 3;
  2132. C_DEFAULT_NAME = 'Guest';
  2133. type
  2134. TUserRole = (urAdmin, urEditor, urViewer);
  2135. TPoint2D = record
  2136. X: Double;
  2137. Y: Double;
  2138. end;
  2139. TUserName = string;
  2140. TUserInfo = class
  2141. public
  2142. type
  2143. TAddress = record
  2144. Street: string;
  2145. City: string;
  2146. Zip: string;
  2147. end;
  2148. private
  2149. FName: TUserName;
  2150. FRole: TUserRole;
  2151. FAddress: TAddress;
  2152. public
  2153. constructor Create(const AName: TUserName; ARole: TUserRole);
  2154. function GetDisplayName: string;
  2155. class function CreateAdmin(const AName: TUserName): TUserInfo; static;
  2156. property Name: TUserName read FName write FName;
  2157. property Role: TUserRole read FRole;
  2158. property Address: TAddress read FAddress write FAddress;
  2159. end;
  2160. implementation
  2161. constructor TUserInfo.Create(const AName: TUserName; ARole: TUserRole);
  2162. begin
  2163. FName := AName;
  2164. FRole := ARole;
  2165. end;
  2166. function TUserInfo.GetDisplayName: string;
  2167. begin
  2168. if FRole = urAdmin then
  2169. Result := '[Admin] ' + FName
  2170. else
  2171. Result := FName;
  2172. end;
  2173. class function TUserInfo.CreateAdmin(const AName: TUserName): TUserInfo;
  2174. begin
  2175. Result := TUserInfo.Create(AName, urAdmin);
  2176. end;
  2177. end.`;
  2178. it('should extract enums with members', () => {
  2179. const result = extractFromSource('UTypes.pas', code);
  2180. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  2181. expect(enumNode?.name).toBe('TUserRole');
  2182. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2183. expect(members.length).toBe(3);
  2184. expect(members.map((m) => m.name)).toEqual(['urAdmin', 'urEditor', 'urViewer']);
  2185. });
  2186. it('should extract constants', () => {
  2187. const result = extractFromSource('UTypes.pas', code);
  2188. const constants = result.nodes.filter((n) => n.kind === 'constant');
  2189. expect(constants.length).toBe(2);
  2190. expect(constants.map((c) => c.name)).toContain('C_MAX_RETRIES');
  2191. expect(constants.map((c) => c.name)).toContain('C_DEFAULT_NAME');
  2192. });
  2193. it('should extract type aliases', () => {
  2194. const result = extractFromSource('UTypes.pas', code);
  2195. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2196. expect(aliases.map((a) => a.name)).toContain('TUserName');
  2197. });
  2198. it('should extract records as classes with fields', () => {
  2199. const result = extractFromSource('UTypes.pas', code);
  2200. const classes = result.nodes.filter((n) => n.kind === 'class');
  2201. expect(classes.map((c) => c.name)).toContain('TPoint2D');
  2202. // TPoint2D fields
  2203. const fields = result.nodes.filter((n) => n.kind === 'field');
  2204. expect(fields.map((f) => f.name)).toContain('X');
  2205. expect(fields.map((f) => f.name)).toContain('Y');
  2206. });
  2207. it('should extract static class methods', () => {
  2208. const result = extractFromSource('UTypes.pas', code);
  2209. const methods = result.nodes.filter((n) => n.kind === 'method');
  2210. const staticMethod = methods.find((m) => m.name === 'CreateAdmin');
  2211. expect(staticMethod).toBeDefined();
  2212. expect(staticMethod?.isStatic).toBe(true);
  2213. });
  2214. it('should extract nested types', () => {
  2215. const result = extractFromSource('UTypes.pas', code);
  2216. const classes = result.nodes.filter((n) => n.kind === 'class');
  2217. expect(classes.map((c) => c.name)).toContain('TAddress');
  2218. });
  2219. });
  2220. });
  2221. // =============================================================================
  2222. // DFM/FMX Extraction
  2223. // =============================================================================
  2224. describe('DFM/FMX Extraction', () => {
  2225. it('should extract components from DFM', () => {
  2226. const code = `object Form1: TForm1
  2227. Left = 0
  2228. Top = 0
  2229. Caption = 'My Form'
  2230. object Button1: TButton
  2231. Left = 10
  2232. Top = 10
  2233. Caption = 'Click Me'
  2234. end
  2235. end`;
  2236. const result = extractFromSource('Form1.dfm', code);
  2237. const components = result.nodes.filter((n) => n.kind === 'component');
  2238. expect(components.length).toBe(2);
  2239. expect(components.map((c) => c.name)).toContain('Form1');
  2240. expect(components.map((c) => c.name)).toContain('Button1');
  2241. const button = components.find((c) => c.name === 'Button1');
  2242. expect(button?.signature).toBe('TButton');
  2243. });
  2244. it('should extract nested component hierarchy', () => {
  2245. const code = `object Form1: TForm1
  2246. object Panel1: TPanel
  2247. object Label1: TLabel
  2248. Caption = 'Hello'
  2249. end
  2250. end
  2251. end`;
  2252. const result = extractFromSource('Form1.dfm', code);
  2253. const components = result.nodes.filter((n) => n.kind === 'component');
  2254. expect(components.length).toBe(3);
  2255. // Check nesting: Panel1 contains Label1
  2256. const panel = components.find((c) => c.name === 'Panel1');
  2257. const label = components.find((c) => c.name === 'Label1');
  2258. const containsEdge = result.edges.find(
  2259. (e) => e.source === panel?.id && e.target === label?.id && e.kind === 'contains'
  2260. );
  2261. expect(containsEdge).toBeDefined();
  2262. });
  2263. it('should extract event handler references', () => {
  2264. const code = `object Form1: TForm1
  2265. OnCreate = FormCreate
  2266. OnDestroy = FormDestroy
  2267. object Button1: TButton
  2268. OnClick = Button1Click
  2269. end
  2270. end`;
  2271. const result = extractFromSource('Form1.dfm', code);
  2272. const refs = result.unresolvedReferences;
  2273. expect(refs.length).toBe(3);
  2274. expect(refs.map((r) => r.referenceName)).toContain('FormCreate');
  2275. expect(refs.map((r) => r.referenceName)).toContain('FormDestroy');
  2276. expect(refs.map((r) => r.referenceName)).toContain('Button1Click');
  2277. expect(refs.every((r) => r.referenceKind === 'references')).toBe(true);
  2278. });
  2279. it('should handle multi-line properties', () => {
  2280. const code = `object Form1: TForm1
  2281. SQL.Strings = (
  2282. 'SELECT * FROM users'
  2283. 'WHERE active = 1')
  2284. object Button1: TButton
  2285. OnClick = Button1Click
  2286. end
  2287. end`;
  2288. const result = extractFromSource('Form1.dfm', code);
  2289. const components = result.nodes.filter((n) => n.kind === 'component');
  2290. expect(components.length).toBe(2);
  2291. const refs = result.unresolvedReferences;
  2292. expect(refs.length).toBe(1);
  2293. expect(refs[0]?.referenceName).toBe('Button1Click');
  2294. });
  2295. it('should handle inherited keyword', () => {
  2296. const code = `inherited Form1: TForm1
  2297. Caption = 'Inherited Form'
  2298. object Button1: TButton
  2299. OnClick = Button1Click
  2300. end
  2301. end`;
  2302. const result = extractFromSource('Form1.dfm', code);
  2303. const components = result.nodes.filter((n) => n.kind === 'component');
  2304. expect(components.length).toBe(2);
  2305. expect(components.map((c) => c.name)).toContain('Form1');
  2306. });
  2307. it('should handle item collection properties', () => {
  2308. const code = `object Form1: TForm1
  2309. object StatusBar1: TStatusBar
  2310. Panels = <
  2311. item
  2312. Width = 200
  2313. end
  2314. item
  2315. Width = 200
  2316. end>
  2317. end
  2318. end`;
  2319. const result = extractFromSource('Form1.dfm', code);
  2320. const components = result.nodes.filter((n) => n.kind === 'component');
  2321. expect(components.length).toBe(2);
  2322. });
  2323. describe('Full fixture: MainForm.dfm', () => {
  2324. const code = `object frmMain: TfrmMain
  2325. Left = 0
  2326. Top = 0
  2327. Caption = 'CodeGraph DFM Fixture'
  2328. ClientHeight = 480
  2329. ClientWidth = 640
  2330. OnCreate = FormCreate
  2331. OnDestroy = FormDestroy
  2332. object pnlTop: TPanel
  2333. Left = 0
  2334. Top = 0
  2335. Width = 640
  2336. Height = 50
  2337. object lblTitle: TLabel
  2338. Left = 16
  2339. Top = 16
  2340. Caption = 'Authentication Service'
  2341. end
  2342. object btnLogin: TButton
  2343. Left = 540
  2344. Top = 12
  2345. OnClick = btnLoginClick
  2346. end
  2347. end
  2348. object pnlContent: TPanel
  2349. Left = 0
  2350. Top = 50
  2351. object edtUsername: TEdit
  2352. Left = 16
  2353. Top = 16
  2354. OnChange = edtUsernameChange
  2355. end
  2356. object edtPassword: TEdit
  2357. Left = 16
  2358. Top = 48
  2359. OnKeyPress = edtPasswordKeyPress
  2360. end
  2361. object mmoLog: TMemo
  2362. Left = 16
  2363. Top = 88
  2364. end
  2365. end
  2366. object pnlStatus: TStatusBar
  2367. Left = 0
  2368. Top = 440
  2369. Panels = <
  2370. item
  2371. Width = 200
  2372. end
  2373. item
  2374. Width = 200
  2375. end>
  2376. end
  2377. end`;
  2378. it('should extract all components', () => {
  2379. const result = extractFromSource('MainForm.dfm', code);
  2380. const components = result.nodes.filter((n) => n.kind === 'component');
  2381. expect(components.length).toBe(9);
  2382. expect(components.map((c) => c.name)).toEqual(
  2383. expect.arrayContaining([
  2384. 'frmMain', 'pnlTop', 'lblTitle', 'btnLogin',
  2385. 'pnlContent', 'edtUsername', 'edtPassword', 'mmoLog', 'pnlStatus',
  2386. ])
  2387. );
  2388. });
  2389. it('should extract all event handlers', () => {
  2390. const result = extractFromSource('MainForm.dfm', code);
  2391. const refs = result.unresolvedReferences;
  2392. expect(refs.length).toBe(5);
  2393. expect(refs.map((r) => r.referenceName)).toEqual(
  2394. expect.arrayContaining([
  2395. 'FormCreate', 'FormDestroy', 'btnLoginClick',
  2396. 'edtUsernameChange', 'edtPasswordKeyPress',
  2397. ])
  2398. );
  2399. });
  2400. });
  2401. });
  2402. describe('Full Indexing', () => {
  2403. let tempDir: string;
  2404. beforeEach(() => {
  2405. tempDir = createTempDir();
  2406. });
  2407. afterEach(() => {
  2408. cleanupTempDir(tempDir);
  2409. });
  2410. it('should index a TypeScript file', async () => {
  2411. // Create test file
  2412. const srcDir = path.join(tempDir, 'src');
  2413. fs.mkdirSync(srcDir);
  2414. fs.writeFileSync(
  2415. path.join(srcDir, 'utils.ts'),
  2416. `
  2417. export function add(a: number, b: number): number {
  2418. return a + b;
  2419. }
  2420. export function multiply(a: number, b: number): number {
  2421. return a * b;
  2422. }
  2423. `
  2424. );
  2425. // Initialize and index
  2426. const cg = CodeGraph.initSync(tempDir);
  2427. const result = await cg.indexAll();
  2428. expect(result.success).toBe(true);
  2429. expect(result.filesIndexed).toBe(1);
  2430. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  2431. // Check nodes were stored
  2432. const nodes = cg.getNodesInFile('src/utils.ts');
  2433. expect(nodes.length).toBeGreaterThanOrEqual(2);
  2434. const addFunc = nodes.find((n) => n.name === 'add');
  2435. expect(addFunc).toBeDefined();
  2436. expect(addFunc?.kind).toBe('function');
  2437. cg.close();
  2438. });
  2439. it('should index multiple files', async () => {
  2440. // Create test files
  2441. const srcDir = path.join(tempDir, 'src');
  2442. fs.mkdirSync(srcDir);
  2443. fs.writeFileSync(
  2444. path.join(srcDir, 'math.ts'),
  2445. `export function add(a: number, b: number) { return a + b; }`
  2446. );
  2447. fs.writeFileSync(
  2448. path.join(srcDir, 'string.ts'),
  2449. `export function capitalize(s: string) { return s.toUpperCase(); }`
  2450. );
  2451. // Initialize and index
  2452. const cg = CodeGraph.initSync(tempDir);
  2453. const result = await cg.indexAll();
  2454. expect(result.success).toBe(true);
  2455. expect(result.filesIndexed).toBe(2);
  2456. const files = cg.getFiles();
  2457. expect(files.length).toBe(2);
  2458. cg.close();
  2459. });
  2460. it('should track file hashes for incremental updates', async () => {
  2461. // Create initial file
  2462. const srcDir = path.join(tempDir, 'src');
  2463. fs.mkdirSync(srcDir);
  2464. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  2465. // Initialize and index
  2466. const cg = CodeGraph.initSync(tempDir);
  2467. await cg.indexAll();
  2468. // Check file is tracked
  2469. const file = cg.getFile('src/main.ts');
  2470. expect(file).toBeDefined();
  2471. expect(file?.contentHash).toBeDefined();
  2472. // Modify file
  2473. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  2474. // Check for changes
  2475. const changes = cg.getChangedFiles();
  2476. expect(changes.modified).toContain('src/main.ts');
  2477. cg.close();
  2478. });
  2479. it('should sync and detect changes', async () => {
  2480. // Create initial file
  2481. const srcDir = path.join(tempDir, 'src');
  2482. fs.mkdirSync(srcDir);
  2483. fs.writeFileSync(
  2484. path.join(srcDir, 'main.ts'),
  2485. `export function original() { return 1; }`
  2486. );
  2487. // Initialize and index
  2488. const cg = CodeGraph.initSync(tempDir);
  2489. await cg.indexAll();
  2490. const initialNodes = cg.getNodesInFile('src/main.ts');
  2491. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  2492. // Modify file
  2493. fs.writeFileSync(
  2494. path.join(srcDir, 'main.ts'),
  2495. `export function updated() { return 2; }`
  2496. );
  2497. // Sync
  2498. const syncResult = await cg.sync();
  2499. expect(syncResult.filesModified).toBe(1);
  2500. // Check nodes were updated
  2501. const updatedNodes = cg.getNodesInFile('src/main.ts');
  2502. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  2503. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  2504. cg.close();
  2505. });
  2506. });
  2507. describe('Path Normalization', () => {
  2508. it('should convert backslashes to forward slashes', () => {
  2509. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  2510. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  2511. });
  2512. it('should leave forward-slash paths unchanged', () => {
  2513. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  2514. });
  2515. it('should handle empty string', () => {
  2516. expect(normalizePath('')).toBe('');
  2517. });
  2518. });
  2519. describe('Directory Exclusion', () => {
  2520. let tempDir: string;
  2521. beforeEach(() => {
  2522. tempDir = createTempDir();
  2523. });
  2524. afterEach(() => {
  2525. cleanupTempDir(tempDir);
  2526. });
  2527. it('should exclude directories listed in .gitignore', () => {
  2528. // Create structure: src/index.ts + node_modules/pkg/index.js, gitignore node_modules
  2529. const srcDir = path.join(tempDir, 'src');
  2530. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  2531. fs.mkdirSync(srcDir, { recursive: true });
  2532. fs.mkdirSync(nmDir, { recursive: true });
  2533. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2534. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2535. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  2536. const files = scanDirectory(tempDir);
  2537. expect(files).toContain('src/index.ts');
  2538. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2539. });
  2540. it('should exclude nested node_modules via a root .gitignore', () => {
  2541. // A trailing-slash pattern with no leading slash matches at any depth.
  2542. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  2543. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  2544. fs.mkdirSync(srcDir, { recursive: true });
  2545. fs.mkdirSync(nmDir, { recursive: true });
  2546. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2547. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  2548. fs.writeFileSync(path.join(tempDir, '.gitignore'), 'node_modules/\n');
  2549. const files = scanDirectory(tempDir);
  2550. expect(files).toContain('packages/app/src/index.ts');
  2551. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  2552. });
  2553. it('should apply a nested .gitignore only to its own subtree', () => {
  2554. const appSrc = path.join(tempDir, 'app', 'src');
  2555. fs.mkdirSync(appSrc, { recursive: true });
  2556. fs.writeFileSync(path.join(appSrc, 'keep.ts'), 'export const a = 1;');
  2557. fs.writeFileSync(path.join(appSrc, 'skip.ts'), 'export const b = 2;');
  2558. fs.writeFileSync(path.join(tempDir, 'app', '.gitignore'), 'src/skip.ts\n');
  2559. // A sibling with the same name outside app/ must NOT be ignored.
  2560. const otherDir = path.join(tempDir, 'other', 'src');
  2561. fs.mkdirSync(otherDir, { recursive: true });
  2562. fs.writeFileSync(path.join(otherDir, 'skip.ts'), 'export const c = 3;');
  2563. const files = scanDirectory(tempDir);
  2564. expect(files).toContain('app/src/keep.ts');
  2565. expect(files).not.toContain('app/src/skip.ts');
  2566. expect(files).toContain('other/src/skip.ts');
  2567. });
  2568. it('should always skip .git directories', () => {
  2569. const srcDir = path.join(tempDir, 'src');
  2570. const gitDir = path.join(tempDir, '.git', 'objects');
  2571. fs.mkdirSync(srcDir, { recursive: true });
  2572. fs.mkdirSync(gitDir, { recursive: true });
  2573. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  2574. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  2575. const files = scanDirectory(tempDir);
  2576. expect(files).toContain('src/index.ts');
  2577. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  2578. });
  2579. it('should return forward-slash paths on all platforms', () => {
  2580. const srcDir = path.join(tempDir, 'src', 'components');
  2581. fs.mkdirSync(srcDir, { recursive: true });
  2582. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  2583. const files = scanDirectory(tempDir);
  2584. expect(files.length).toBe(1);
  2585. expect(files[0]).toBe('src/components/Button.tsx');
  2586. expect(files[0]).not.toContain('\\');
  2587. });
  2588. });
  2589. describe('Git Submodules', () => {
  2590. let tempDir: string;
  2591. beforeEach(() => {
  2592. tempDir = createTempDir();
  2593. });
  2594. afterEach(() => {
  2595. cleanupTempDir(tempDir);
  2596. });
  2597. it('should index files inside git submodules (issue #147)', async () => {
  2598. const { execFileSync } = await import('child_process');
  2599. const git = (cwd: string, ...args: string[]) =>
  2600. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2601. // Build a separate "library" repo to use as a submodule source.
  2602. const libDir = path.join(tempDir, '_lib');
  2603. fs.mkdirSync(libDir, { recursive: true });
  2604. git(libDir, 'init', '-q');
  2605. git(libDir, 'config', 'user.email', 'test@test.com');
  2606. git(libDir, 'config', 'user.name', 'Test');
  2607. fs.writeFileSync(path.join(libDir, 'lib.ts'), 'export const fromSubmodule = 1;');
  2608. git(libDir, 'add', '-A');
  2609. git(libDir, 'commit', '-q', '-m', 'lib init');
  2610. // Build the main repo and add the lib repo as a submodule.
  2611. const mainDir = path.join(tempDir, 'main');
  2612. fs.mkdirSync(mainDir, { recursive: true });
  2613. git(mainDir, 'init', '-q');
  2614. git(mainDir, 'config', 'user.email', 'test@test.com');
  2615. git(mainDir, 'config', 'user.name', 'Test');
  2616. fs.writeFileSync(path.join(mainDir, 'app.ts'), 'export const app = 1;');
  2617. git(mainDir, 'add', '-A');
  2618. git(mainDir, 'commit', '-q', '-m', 'app init');
  2619. // protocol.file.allow=always is required to add a local-path submodule on
  2620. // recent git versions (CVE-2022-39253 mitigation).
  2621. execFileSync(
  2622. 'git',
  2623. ['-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', libDir, 'libs/lib'],
  2624. { cwd: mainDir, stdio: 'pipe' }
  2625. );
  2626. git(mainDir, 'commit', '-q', '-m', 'add submodule');
  2627. const files = scanDirectory(mainDir);
  2628. expect(files).toContain('app.ts');
  2629. expect(files).toContain('libs/lib/lib.ts');
  2630. });
  2631. });
  2632. describe('Nested non-submodule git repos', () => {
  2633. let tempDir: string;
  2634. beforeEach(() => {
  2635. tempDir = createTempDir();
  2636. });
  2637. afterEach(() => {
  2638. cleanupTempDir(tempDir);
  2639. });
  2640. it('should index files in embedded git repos run from a git super-repo (issue #193)', async () => {
  2641. const { execFileSync } = await import('child_process');
  2642. const git = (cwd: string, ...args: string[]) =>
  2643. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2644. // Top-level workspace is itself a git repo, holding no source directly —
  2645. // the CMake "super-repo" layout from the issue.
  2646. const root = path.join(tempDir, 'root');
  2647. fs.mkdirSync(path.join(root, 'coding'), { recursive: true });
  2648. git(root, 'init', '-q');
  2649. git(root, 'config', 'user.email', 'test@test.com');
  2650. git(root, 'config', 'user.name', 'Test');
  2651. fs.writeFileSync(path.join(root, 'CMakeLists.txt'), 'cmake_minimum_required(VERSION 3.10)\n');
  2652. // Two independent clones living inside the workspace (NOT submodules):
  2653. // one with committed source, one with only untracked source.
  2654. const sub1 = path.join(root, 'sub_repo1', 'src');
  2655. fs.mkdirSync(sub1, { recursive: true });
  2656. git(path.join(root, 'sub_repo1'), 'init', '-q');
  2657. git(path.join(root, 'sub_repo1'), 'config', 'user.email', 'test@test.com');
  2658. git(path.join(root, 'sub_repo1'), 'config', 'user.name', 'Test');
  2659. fs.writeFileSync(path.join(sub1, 'one.ts'), 'export const one = 1;');
  2660. git(path.join(root, 'sub_repo1'), 'add', '-A');
  2661. git(path.join(root, 'sub_repo1'), 'commit', '-q', '-m', 'sub1 init');
  2662. const sub2 = path.join(root, 'sub_repo2', 'src');
  2663. fs.mkdirSync(sub2, { recursive: true });
  2664. git(path.join(root, 'sub_repo2'), 'init', '-q');
  2665. fs.writeFileSync(path.join(sub2, 'two.ts'), 'export const two = 2;');
  2666. const files = scanDirectory(root);
  2667. // Both committed and untracked source from the nested repos must be found.
  2668. expect(files).toContain('sub_repo1/src/one.ts');
  2669. expect(files).toContain('sub_repo2/src/two.ts');
  2670. });
  2671. it('should respect each embedded repo\'s own .gitignore', async () => {
  2672. const { execFileSync } = await import('child_process');
  2673. const git = (cwd: string, ...args: string[]) =>
  2674. execFileSync('git', args, { cwd, stdio: 'pipe' });
  2675. const root = path.join(tempDir, 'root');
  2676. fs.mkdirSync(root, { recursive: true });
  2677. git(root, 'init', '-q');
  2678. const sub = path.join(root, 'sub_repo', 'src');
  2679. fs.mkdirSync(sub, { recursive: true });
  2680. git(path.join(root, 'sub_repo'), 'init', '-q');
  2681. fs.writeFileSync(path.join(root, 'sub_repo', '.gitignore'), 'src/generated.ts\n');
  2682. fs.writeFileSync(path.join(sub, 'real.ts'), 'export const real = 1;');
  2683. fs.writeFileSync(path.join(sub, 'generated.ts'), 'export const generated = 1;');
  2684. const files = scanDirectory(root);
  2685. expect(files).toContain('sub_repo/src/real.ts');
  2686. expect(files).not.toContain('sub_repo/src/generated.ts');
  2687. });
  2688. });
  2689. // =============================================================================
  2690. // Scala
  2691. // =============================================================================
  2692. describe('Scala Extraction', () => {
  2693. describe('Language detection', () => {
  2694. it('should detect Scala files', () => {
  2695. expect(detectLanguage('Main.scala')).toBe('scala');
  2696. expect(detectLanguage('script.sc')).toBe('scala');
  2697. expect(detectLanguage('src/UserService.scala')).toBe('scala');
  2698. });
  2699. it('should report Scala as supported', () => {
  2700. expect(isLanguageSupported('scala')).toBe(true);
  2701. expect(getSupportedLanguages()).toContain('scala');
  2702. });
  2703. });
  2704. describe('Class extraction', () => {
  2705. it('should extract class definitions', () => {
  2706. const code = `
  2707. class UserService(private val repo: UserRepository) {
  2708. def findUser(id: String): Option[String] = Some(id)
  2709. }
  2710. `;
  2711. const result = extractFromSource('UserService.scala', code);
  2712. const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'UserService');
  2713. expect(cls).toBeDefined();
  2714. expect(cls?.language).toBe('scala');
  2715. });
  2716. it('should extract object definitions as class kind', () => {
  2717. const code = `
  2718. object DatabaseConfig {
  2719. val url = "jdbc:postgresql://localhost/mydb"
  2720. }
  2721. `;
  2722. const result = extractFromSource('Config.scala', code);
  2723. const obj = result.nodes.find((n) => n.kind === 'class' && n.name === 'DatabaseConfig');
  2724. expect(obj).toBeDefined();
  2725. });
  2726. it('should extract trait definitions as trait kind', () => {
  2727. const code = `
  2728. trait Repository[A] {
  2729. def findById(id: String): Option[A]
  2730. def save(entity: A): Unit
  2731. }
  2732. `;
  2733. const result = extractFromSource('Repository.scala', code);
  2734. const trait_ = result.nodes.find((n) => n.kind === 'trait' && n.name === 'Repository');
  2735. expect(trait_).toBeDefined();
  2736. });
  2737. });
  2738. describe('Method and function extraction', () => {
  2739. it('should extract method definitions inside a class', () => {
  2740. const code = `
  2741. class Calculator {
  2742. def add(a: Int, b: Int): Int = a + b
  2743. def divide(a: Double, b: Double): Double = a / b
  2744. }
  2745. `;
  2746. const result = extractFromSource('Calculator.scala', code);
  2747. const methods = result.nodes.filter((n) => n.kind === 'method');
  2748. expect(methods.find((m) => m.name === 'add')).toBeDefined();
  2749. expect(methods.find((m) => m.name === 'divide')).toBeDefined();
  2750. });
  2751. it('should extract method signatures', () => {
  2752. const code = `
  2753. class Greeter {
  2754. def greet(name: String): String = s"Hello, \${name}!"
  2755. }
  2756. `;
  2757. const result = extractFromSource('Greeter.scala', code);
  2758. const method = result.nodes.find((n) => n.name === 'greet');
  2759. expect(method?.signature).toContain('name: String');
  2760. expect(method?.signature).toContain('String');
  2761. });
  2762. it('should extract top-level function definitions as functions', () => {
  2763. const code = `
  2764. def factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
  2765. def greet(name: String): String = s"Hello, \${name}!"
  2766. `;
  2767. const result = extractFromSource('utils.scala', code);
  2768. const fns = result.nodes.filter((n) => n.kind === 'function');
  2769. expect(fns.find((f) => f.name === 'factorial')).toBeDefined();
  2770. expect(fns.find((f) => f.name === 'greet')).toBeDefined();
  2771. });
  2772. });
  2773. describe('Val and var extraction', () => {
  2774. it('should extract val inside a class as field', () => {
  2775. const code = `
  2776. class Config {
  2777. val timeout: Int = 30
  2778. val host: String = "localhost"
  2779. }
  2780. `;
  2781. const result = extractFromSource('Config.scala', code);
  2782. const fields = result.nodes.filter((n) => n.kind === 'field');
  2783. expect(fields.find((f) => f.name === 'timeout')).toBeDefined();
  2784. expect(fields.find((f) => f.name === 'host')).toBeDefined();
  2785. });
  2786. it('should extract var inside a class as field', () => {
  2787. const code = `
  2788. class Counter {
  2789. var count: Int = 0
  2790. }
  2791. `;
  2792. const result = extractFromSource('Counter.scala', code);
  2793. const field = result.nodes.find((n) => n.kind === 'field' && n.name === 'count');
  2794. expect(field).toBeDefined();
  2795. });
  2796. it('should extract top-level val as constant', () => {
  2797. const code = `
  2798. val MaxConnections: Int = 100
  2799. val DefaultTimeout = 30
  2800. `;
  2801. const result = extractFromSource('constants.scala', code);
  2802. const consts = result.nodes.filter((n) => n.kind === 'constant');
  2803. expect(consts.find((c) => c.name === 'MaxConnections')).toBeDefined();
  2804. });
  2805. it('should extract top-level var as variable', () => {
  2806. const code = `
  2807. var retries: Int = 3
  2808. `;
  2809. const result = extractFromSource('state.scala', code);
  2810. const v = result.nodes.find((n) => n.kind === 'variable' && n.name === 'retries');
  2811. expect(v).toBeDefined();
  2812. });
  2813. it('should include type in val/var signature', () => {
  2814. const code = `
  2815. class Service {
  2816. val timeout: Int = 30
  2817. }
  2818. `;
  2819. const result = extractFromSource('Service.scala', code);
  2820. const field = result.nodes.find((n) => n.name === 'timeout');
  2821. expect(field?.signature).toContain('timeout');
  2822. expect(field?.signature).toContain('Int');
  2823. });
  2824. });
  2825. describe('Enum extraction', () => {
  2826. it('should extract enum definitions', () => {
  2827. const code = `
  2828. enum Color:
  2829. case Red
  2830. case Green
  2831. case Blue
  2832. `;
  2833. const result = extractFromSource('Color.scala', code);
  2834. const enumNode = result.nodes.find((n) => n.kind === 'enum' && n.name === 'Color');
  2835. expect(enumNode).toBeDefined();
  2836. });
  2837. it('should extract enum cases as enum_member', () => {
  2838. const code = `
  2839. enum Direction:
  2840. case North
  2841. case South
  2842. case East
  2843. case West
  2844. `;
  2845. const result = extractFromSource('Direction.scala', code);
  2846. const members = result.nodes.filter((n) => n.kind === 'enum_member');
  2847. expect(members.find((m) => m.name === 'North')).toBeDefined();
  2848. expect(members.find((m) => m.name === 'South')).toBeDefined();
  2849. expect(members.length).toBeGreaterThanOrEqual(4);
  2850. });
  2851. });
  2852. describe('Type alias extraction', () => {
  2853. it('should extract type aliases', () => {
  2854. const code = `
  2855. type UserId = String
  2856. type UserMap = Map[String, String]
  2857. `;
  2858. const result = extractFromSource('types.scala', code);
  2859. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  2860. expect(aliases.find((a) => a.name === 'UserId')).toBeDefined();
  2861. expect(aliases.find((a) => a.name === 'UserMap')).toBeDefined();
  2862. });
  2863. });
  2864. describe('Import extraction', () => {
  2865. it('should extract import declarations', () => {
  2866. const code = `
  2867. import scala.collection.mutable.ListBuffer
  2868. import scala.concurrent.Future
  2869. `;
  2870. const result = extractFromSource('imports.scala', code);
  2871. const imports = result.nodes.filter((n) => n.kind === 'import');
  2872. expect(imports.length).toBeGreaterThanOrEqual(2);
  2873. });
  2874. });
  2875. describe('Visibility modifiers', () => {
  2876. it('should extract private visibility', () => {
  2877. const code = `
  2878. class Service {
  2879. private val secret: String = "abc"
  2880. private def helper(): Unit = {}
  2881. }
  2882. `;
  2883. const result = extractFromSource('Service.scala', code);
  2884. const secretField = result.nodes.find((n) => n.name === 'secret');
  2885. expect(secretField?.visibility).toBe('private');
  2886. const helperMethod = result.nodes.find((n) => n.name === 'helper');
  2887. expect(helperMethod?.visibility).toBe('private');
  2888. });
  2889. it('should extract protected visibility', () => {
  2890. const code = `
  2891. class Base {
  2892. protected def helperMethod(): Unit = {}
  2893. }
  2894. `;
  2895. const result = extractFromSource('Base.scala', code);
  2896. const method = result.nodes.find((n) => n.name === 'helperMethod');
  2897. expect(method?.visibility).toBe('protected');
  2898. });
  2899. it('should default to public visibility', () => {
  2900. const code = `
  2901. class Greeter {
  2902. def hello(): Unit = {}
  2903. }
  2904. `;
  2905. const result = extractFromSource('Greeter.scala', code);
  2906. const method = result.nodes.find((n) => n.name === 'hello');
  2907. expect(method?.visibility).toBe('public');
  2908. });
  2909. });
  2910. describe('Inheritance', () => {
  2911. it('should extract extends relationships', () => {
  2912. const code = `
  2913. class AdminUser extends User {
  2914. def adminAction(): Unit = {}
  2915. }
  2916. `;
  2917. const result = extractFromSource('AdminUser.scala', code);
  2918. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  2919. expect(extendsRefs.find((r) => r.referenceName === 'User')).toBeDefined();
  2920. });
  2921. });
  2922. describe('Call extraction', () => {
  2923. it('should extract function call expressions', () => {
  2924. const code = `
  2925. def processData(): Unit = {
  2926. val result = computeResult()
  2927. println(result)
  2928. }
  2929. `;
  2930. const result = extractFromSource('processor.scala', code);
  2931. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  2932. expect(calls.length).toBeGreaterThan(0);
  2933. });
  2934. });
  2935. });
  2936. describe('Vue Extraction', () => {
  2937. it('should detect Vue files', () => {
  2938. expect(detectLanguage('App.vue')).toBe('vue');
  2939. expect(detectLanguage('components/Button.vue')).toBe('vue');
  2940. expect(isLanguageSupported('vue')).toBe(true);
  2941. });
  2942. it('should extract component node from a Vue SFC', () => {
  2943. const code = `<template>
  2944. <div>{{ message }}</div>
  2945. </template>
  2946. <script>
  2947. export default {
  2948. data() {
  2949. return { message: 'Hello' };
  2950. }
  2951. }
  2952. </script>
  2953. `;
  2954. const result = extractFromSource('HelloWorld.vue', code);
  2955. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2956. expect(componentNode).toBeDefined();
  2957. expect(componentNode?.name).toBe('HelloWorld');
  2958. expect(componentNode?.language).toBe('vue');
  2959. expect(componentNode?.isExported).toBe(true);
  2960. });
  2961. it('should extract functions from <script> block', () => {
  2962. const code = `<template>
  2963. <button @click="handleClick">Click</button>
  2964. </template>
  2965. <script>
  2966. function handleClick() {
  2967. console.log('clicked');
  2968. }
  2969. const count = 0;
  2970. </script>
  2971. `;
  2972. const result = extractFromSource('Button.vue', code);
  2973. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2974. expect(componentNode).toBeDefined();
  2975. expect(componentNode?.name).toBe('Button');
  2976. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'handleClick');
  2977. expect(funcNode).toBeDefined();
  2978. expect(funcNode?.language).toBe('vue');
  2979. });
  2980. it('should extract from <script setup lang="ts"> block', () => {
  2981. const code = `<template>
  2982. <div>{{ count }}</div>
  2983. </template>
  2984. <script setup lang="ts">
  2985. import { ref } from 'vue';
  2986. const count = ref(0);
  2987. function increment(): void {
  2988. count.value++;
  2989. }
  2990. </script>
  2991. `;
  2992. const result = extractFromSource('Counter.vue', code);
  2993. const componentNode = result.nodes.find((n) => n.kind === 'component');
  2994. expect(componentNode).toBeDefined();
  2995. expect(componentNode?.name).toBe('Counter');
  2996. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'increment');
  2997. expect(funcNode).toBeDefined();
  2998. expect(funcNode?.language).toBe('vue');
  2999. // All nodes should be marked as vue language
  3000. for (const node of result.nodes) {
  3001. expect(node.language).toBe('vue');
  3002. }
  3003. });
  3004. it('should extract calls from top-level <script setup> initializers', () => {
  3005. const code = `<template>
  3006. <div>{{ token }}</div>
  3007. </template>
  3008. <script setup lang="ts">
  3009. import { getTokenMp } from './api/upload';
  3010. const token = getTokenMp();
  3011. </script>
  3012. `;
  3013. const result = extractFromSource('Issue425Setup.vue', code);
  3014. const call = result.unresolvedReferences.find(
  3015. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3016. );
  3017. expect(call).toBeDefined();
  3018. });
  3019. it('should extract calls from Vue Options API object methods', () => {
  3020. const code = `<template>
  3021. <button @click="save">Save</button>
  3022. </template>
  3023. <script>
  3024. import { getTokenMp } from './api/upload';
  3025. export default {
  3026. methods: {
  3027. save() {
  3028. return getTokenMp();
  3029. }
  3030. },
  3031. setup() {
  3032. return getTokenMp();
  3033. }
  3034. }
  3035. </script>
  3036. `;
  3037. const result = extractFromSource('Issue425Options.vue', code);
  3038. const calls = result.unresolvedReferences.filter(
  3039. (ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
  3040. );
  3041. expect(calls).toHaveLength(2);
  3042. });
  3043. it('should extract from both <script> and <script setup> blocks', () => {
  3044. const code = `<template>
  3045. <div>{{ msg }}</div>
  3046. </template>
  3047. <script>
  3048. export default {
  3049. name: 'DualScript'
  3050. }
  3051. </script>
  3052. <script setup>
  3053. const msg = 'hello';
  3054. function greet() {
  3055. return msg;
  3056. }
  3057. </script>
  3058. `;
  3059. const result = extractFromSource('DualScript.vue', code);
  3060. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3061. expect(componentNode).toBeDefined();
  3062. const greetFunc = result.nodes.find((n) => n.kind === 'function' && n.name === 'greet');
  3063. expect(greetFunc).toBeDefined();
  3064. });
  3065. it('should create component node for template-only Vue file', () => {
  3066. const code = `<template>
  3067. <div>Static content</div>
  3068. </template>
  3069. `;
  3070. const result = extractFromSource('Static.vue', code);
  3071. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3072. expect(componentNode).toBeDefined();
  3073. expect(componentNode?.name).toBe('Static');
  3074. expect(componentNode?.language).toBe('vue');
  3075. // Only the component node should exist (no script nodes)
  3076. expect(result.nodes.length).toBe(1);
  3077. });
  3078. it('should create containment edges from component to script nodes', () => {
  3079. const code = `<template>
  3080. <div>{{ value }}</div>
  3081. </template>
  3082. <script setup lang="ts">
  3083. const value = 42;
  3084. </script>
  3085. `;
  3086. const result = extractFromSource('Contained.vue', code);
  3087. const componentNode = result.nodes.find((n) => n.kind === 'component');
  3088. expect(componentNode).toBeDefined();
  3089. // Should have containment edges from component to child nodes
  3090. const containEdges = result.edges.filter(
  3091. (e) => e.source === componentNode!.id && e.kind === 'contains'
  3092. );
  3093. expect(containEdges.length).toBeGreaterThan(0);
  3094. });
  3095. });
  3096. describe('Instantiates + Decorates edge extraction', () => {
  3097. it('emits an instantiates ref for `new Foo()`', () => {
  3098. const code = `
  3099. class Foo {}
  3100. function bootstrap() { return new Foo(); }
  3101. `;
  3102. const result = extractFromSource('app.ts', code);
  3103. const ref = result.unresolvedReferences.find(
  3104. (r) => r.referenceKind === 'instantiates' && r.referenceName === 'Foo'
  3105. );
  3106. expect(ref).toBeDefined();
  3107. });
  3108. it('strips type-argument suffix from generic constructors', () => {
  3109. const code = `
  3110. class Container<T> { constructor(_: T) {} }
  3111. function go() { return new Container<string>('x'); }
  3112. `;
  3113. const result = extractFromSource('app.ts', code);
  3114. const ref = result.unresolvedReferences.find(
  3115. (r) => r.referenceKind === 'instantiates'
  3116. );
  3117. expect(ref).toBeDefined();
  3118. // Container<string> must be normalised to "Container" — otherwise
  3119. // resolution can never match the class node.
  3120. expect(ref!.referenceName).toBe('Container');
  3121. });
  3122. it('keeps trailing identifier from qualified `new ns.Foo()`', () => {
  3123. const code = `
  3124. const ns = { Foo: class {} };
  3125. function go() { return new ns.Foo(); }
  3126. `;
  3127. const result = extractFromSource('app.ts', code);
  3128. const ref = result.unresolvedReferences.find(
  3129. (r) => r.referenceKind === 'instantiates'
  3130. );
  3131. // We can't always resolve which Foo, but the name should be the
  3132. // simple identifier so name-matching has a chance.
  3133. expect(ref?.referenceName).toBe('Foo');
  3134. });
  3135. it('emits a decorates ref for `@Foo class X {}`', () => {
  3136. const code = `
  3137. function Foo(_arg: string) { return (cls: any) => cls; }
  3138. @Foo('x')
  3139. class X {}
  3140. `;
  3141. const result = extractFromSource('app.ts', code);
  3142. const decorClass = result.unresolvedReferences.find(
  3143. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Foo'
  3144. );
  3145. expect(decorClass).toBeDefined();
  3146. });
  3147. it('does NOT attribute a prior class\'s decorator to the next class', () => {
  3148. // Regression: the sibling-walk must stop at the first non-
  3149. // decorator separator. `@A class Foo {} @B class Bar {}` must
  3150. // produce `decorates(Foo, A)` and `decorates(Bar, B)` — never
  3151. // `decorates(Bar, A)`.
  3152. const code = `
  3153. function A(cls: any) { return cls; }
  3154. function B(cls: any) { return cls; }
  3155. @A
  3156. class Foo {}
  3157. @B
  3158. class Bar {}
  3159. `;
  3160. const result = extractFromSource('app.ts', code);
  3161. const decoratesEdges = result.unresolvedReferences.filter(
  3162. (r) => r.referenceKind === 'decorates'
  3163. );
  3164. // Exactly one decorates ref per decorated class, no cross-attribution.
  3165. const fromBar = decoratesEdges.filter((r) =>
  3166. result.nodes.find((n) => n.id === r.fromNodeId && n.name === 'Bar')
  3167. );
  3168. expect(fromBar.length).toBe(1);
  3169. expect(fromBar[0]!.referenceName).toBe('B');
  3170. });
  3171. it('emits a decorates ref for `@Foo method() {}`', () => {
  3172. const code = `
  3173. function Get(p: string) { return (t: any, k: string) => t; }
  3174. class Svc {
  3175. @Get('/x') method() { return 1; }
  3176. }
  3177. `;
  3178. const result = extractFromSource('app.ts', code);
  3179. const decorMethod = result.unresolvedReferences.find(
  3180. (r) => r.referenceKind === 'decorates' && r.referenceName === 'Get'
  3181. );
  3182. expect(decorMethod).toBeDefined();
  3183. // The decorated symbol must be `method`, not the constructor or class.
  3184. const decoratedNode = result.nodes.find((n) => n.id === decorMethod!.fromNodeId);
  3185. expect(decoratedNode?.name).toBe('method');
  3186. });
  3187. });
  3188. // =============================================================================
  3189. // Lua
  3190. // =============================================================================
  3191. describe('Lua Extraction', () => {
  3192. describe('Language detection', () => {
  3193. it('should detect Lua files', () => {
  3194. expect(detectLanguage('init.lua')).toBe('lua');
  3195. expect(detectLanguage('src/util.lua')).toBe('lua');
  3196. });
  3197. it('should report Lua as supported', () => {
  3198. expect(isLanguageSupported('lua')).toBe(true);
  3199. expect(getSupportedLanguages()).toContain('lua');
  3200. });
  3201. });
  3202. describe('Function extraction', () => {
  3203. it('should extract global and local functions', () => {
  3204. const code = `
  3205. function configure(opts) return opts end
  3206. local function helper(x) return x * 2 end
  3207. `;
  3208. const result = extractFromSource('init.lua', code);
  3209. const funcs = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  3210. expect(funcs).toContain('configure');
  3211. expect(funcs).toContain('helper');
  3212. const configure = result.nodes.find((n) => n.name === 'configure');
  3213. expect(configure?.language).toBe('lua');
  3214. expect(configure?.signature).toBe('(opts)');
  3215. });
  3216. it('should split table/method functions into a receiver and method name', () => {
  3217. const code = `
  3218. function M.connect(host, port) return host end
  3219. function M:send(data) return self end
  3220. `;
  3221. const result = extractFromSource('init.lua', code);
  3222. const methods = result.nodes.filter((n) => n.kind === 'method');
  3223. const connect = methods.find((m) => m.name === 'connect');
  3224. expect(connect?.qualifiedName).toBe('M::connect');
  3225. const send = methods.find((m) => m.name === 'send');
  3226. expect(send?.qualifiedName).toBe('M::send');
  3227. });
  3228. });
  3229. describe('Variable extraction', () => {
  3230. it('should extract local variable declarations', () => {
  3231. const code = `
  3232. local M = {}
  3233. local count = 0
  3234. `;
  3235. const result = extractFromSource('mod.lua', code);
  3236. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3237. expect(vars).toContain('M');
  3238. expect(vars).toContain('count');
  3239. });
  3240. });
  3241. describe('Import extraction (require)', () => {
  3242. it('should extract require() in local declarations and bare calls', () => {
  3243. const code = `
  3244. local socket = require("socket")
  3245. local http = require "resty.http"
  3246. require("side.effect")
  3247. `;
  3248. const result = extractFromSource('net.lua', code);
  3249. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3250. expect(imports).toContain('socket');
  3251. expect(imports).toContain('resty.http');
  3252. expect(imports).toContain('side.effect');
  3253. const ref = result.unresolvedReferences.find(
  3254. (r) => r.referenceKind === 'imports' && r.referenceName === 'socket'
  3255. );
  3256. expect(ref).toBeDefined();
  3257. });
  3258. // Regression: the tree-sitter-wasms Lua grammar (ABI 13) corrupts the shared
  3259. // WASM heap under web-tree-sitter 0.25, dropping nested calls/imports on every
  3260. // parse after the first. We vendor the ABI-15 grammar instead — this guards it
  3261. // by extracting several sources in sequence and asserting the LAST still works.
  3262. it('should keep extracting require across many sequential parses', () => {
  3263. let last;
  3264. for (let i = 0; i < 8; i++) {
  3265. last = extractFromSource(`f${i}.lua`, `local m = require("module.${i}")\nreturn m\n`);
  3266. }
  3267. const imports = last!.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3268. expect(imports).toContain('module.7');
  3269. });
  3270. });
  3271. describe('Call extraction', () => {
  3272. it('should record intra-file calls as resolvable references', () => {
  3273. const code = `
  3274. local function helper(x) return x end
  3275. local function run(y) return helper(y) end
  3276. `;
  3277. const result = extractFromSource('calls.lua', code);
  3278. const call = result.unresolvedReferences.find(
  3279. (r) => r.referenceKind === 'calls' && r.referenceName === 'helper'
  3280. );
  3281. expect(call).toBeDefined();
  3282. });
  3283. });
  3284. });
  3285. // =============================================================================
  3286. // Luau (typed superset of Lua — https://luau.org)
  3287. // =============================================================================
  3288. describe('Luau Extraction', () => {
  3289. describe('Language detection', () => {
  3290. it('should detect Luau files', () => {
  3291. expect(detectLanguage('init.luau')).toBe('luau');
  3292. expect(detectLanguage('src/Client.luau')).toBe('luau');
  3293. });
  3294. it('should report Luau as supported', () => {
  3295. expect(isLanguageSupported('luau')).toBe(true);
  3296. expect(getSupportedLanguages()).toContain('luau');
  3297. });
  3298. });
  3299. describe('Type aliases', () => {
  3300. it('should extract `type` and `export type` definitions', () => {
  3301. const code = `
  3302. export type Vector = { x: number, y: number }
  3303. type Handler = (msg: string) -> boolean
  3304. `;
  3305. const result = extractFromSource('types.luau', code);
  3306. const aliases = result.nodes.filter((n) => n.kind === 'type_alias');
  3307. const vector = aliases.find((a) => a.name === 'Vector');
  3308. expect(vector).toBeDefined();
  3309. expect(vector?.isExported).toBe(true);
  3310. const handler = aliases.find((a) => a.name === 'Handler');
  3311. expect(handler).toBeDefined();
  3312. expect(handler?.isExported).toBe(false);
  3313. });
  3314. });
  3315. describe('Typed functions and methods', () => {
  3316. it('should capture typed signatures and split methods by receiver', () => {
  3317. const code = `
  3318. function configure(opts: { debug: boolean }): boolean
  3319. return opts.debug
  3320. end
  3321. function Client:fetch(path: string): Response
  3322. return path
  3323. end
  3324. `;
  3325. const result = extractFromSource('client.luau', code);
  3326. const configure = result.nodes.find((n) => n.kind === 'function' && n.name === 'configure');
  3327. expect(configure?.language).toBe('luau');
  3328. expect(configure?.signature).toBe('(opts: { debug: boolean }): boolean');
  3329. const fetch = result.nodes.find((n) => n.kind === 'method' && n.name === 'fetch');
  3330. expect(fetch?.qualifiedName).toBe('Client::fetch');
  3331. });
  3332. });
  3333. describe('Imports and variables', () => {
  3334. it('should extract string and Roblox instance-path require imports', () => {
  3335. const code = `
  3336. local http = require("http")
  3337. local Signal = require(script.Parent.Signal)
  3338. local count = 0
  3339. `;
  3340. const result = extractFromSource('mod.luau', code);
  3341. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3342. expect(imports).toContain('http'); // string require
  3343. expect(imports).toContain('Signal'); // Roblox instance-path require
  3344. const vars = result.nodes.filter((n) => n.kind === 'variable').map((n) => n.name);
  3345. expect(vars).toContain('count');
  3346. });
  3347. });
  3348. });
  3349. // =============================================================================
  3350. // Objective-C
  3351. // =============================================================================
  3352. describe('Objective-C Extraction', () => {
  3353. const sample = `
  3354. #import <Foundation/Foundation.h>
  3355. #import "MyClass.h"
  3356. @interface MyClass : NSObject <NSCopying>
  3357. @property (nonatomic, copy) NSString *name;
  3358. - (void)greet;
  3359. - (void)doThing:(id)x with:(id)y;
  3360. + (instancetype)shared;
  3361. @end
  3362. @implementation MyClass
  3363. - (void)greet {
  3364. NSLog(@"Hello");
  3365. [self doWork];
  3366. }
  3367. - (void)doThing:(id)x with:(id)y {
  3368. [self notify:x];
  3369. }
  3370. + (instancetype)shared {
  3371. return [[MyClass alloc] init];
  3372. }
  3373. @end
  3374. void helperFunction(int count) {
  3375. MyClass *obj = [MyClass shared];
  3376. [obj greet];
  3377. }
  3378. `;
  3379. it('should extract classes, methods, functions, and imports', () => {
  3380. const result = extractFromSource('App.m', sample);
  3381. const classes = result.nodes.filter((n) => n.kind === 'class');
  3382. expect(classes.filter((c) => c.name === 'MyClass')).toHaveLength(1);
  3383. const methods = result.nodes.filter((n) => n.kind === 'method');
  3384. expect(methods.map((m) => m.name).sort()).toEqual(['doThing:with:', 'greet', 'shared']);
  3385. const shared = methods.find((m) => m.name === 'shared');
  3386. expect(shared?.isStatic).toBe(true);
  3387. const properties = result.nodes.filter((n) => n.kind === 'property');
  3388. expect(properties.some((p) => p.name === 'name')).toBe(true);
  3389. const functions = result.nodes.filter((n) => n.kind === 'function');
  3390. expect(functions.some((f) => f.name === 'helperFunction')).toBe(true);
  3391. const imports = result.nodes.filter((n) => n.kind === 'import').map((n) => n.name);
  3392. expect(imports).toContain('Foundation/Foundation.h');
  3393. expect(imports).toContain('MyClass.h');
  3394. });
  3395. it('should record inheritance and protocol conformance', () => {
  3396. const result = extractFromSource('App.m', sample);
  3397. const extendsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'extends');
  3398. const implementsRefs = result.unresolvedReferences.filter((r) => r.referenceKind === 'implements');
  3399. expect(extendsRefs.map((r) => r.referenceName)).toContain('NSObject');
  3400. expect(implementsRefs.map((r) => r.referenceName)).toContain('NSCopying');
  3401. });
  3402. it('should record message sends and C calls', () => {
  3403. const result = extractFromSource('App.m', sample);
  3404. const calls = result.unresolvedReferences
  3405. .filter((r) => r.referenceKind === 'calls')
  3406. .map((r) => r.referenceName);
  3407. expect(calls).toEqual(expect.arrayContaining(['NSLog', 'doWork', 'MyClass.shared', 'obj.greet']));
  3408. });
  3409. it('should reconstruct multi-keyword selectors at the call site so they resolve to the method definition', () => {
  3410. // Regression for the gap discovered post-#165: message_expression's
  3411. // multi-keyword form `[obj a:1 b:2]` was only emitting the first keyword,
  3412. // so calls never resolved to multi-part method definitions like
  3413. // `GET:parameters:headers:progress:success:failure:`. The call-site name
  3414. // must match the method-definition name with full keywords + trailing colons.
  3415. const code = `
  3416. @implementation Caller
  3417. - (void)demo {
  3418. NSMutableDictionary *d = [NSMutableDictionary new];
  3419. [d setObject:@"v" forKey:@"k"];
  3420. [d setObject:@"v2" forKey:@"k2" withRetry:@YES];
  3421. [self touchesBegan:nil withEvent:nil];
  3422. }
  3423. @end
  3424. `;
  3425. const result = extractFromSource('Caller.m', code);
  3426. const calls = result.unresolvedReferences
  3427. .filter((r) => r.referenceKind === 'calls')
  3428. .map((r) => r.referenceName);
  3429. expect(calls).toEqual(
  3430. expect.arrayContaining([
  3431. 'd.setObject:forKey:',
  3432. 'd.setObject:forKey:withRetry:',
  3433. 'touchesBegan:withEvent:',
  3434. ])
  3435. );
  3436. });
  3437. it('should not classify pure C headers with @end in comments as objc', () => {
  3438. const cHeader = '/* @end of file */\n#ifndef STDIO_H\nvoid printf(const char *);\n#endif\n';
  3439. expect(detectLanguage('stdio.h', cHeader)).toBe('c');
  3440. });
  3441. it('should extract protocol declarations', () => {
  3442. const code = `
  3443. @protocol DataSource <NSObject>
  3444. - (NSInteger)numberOfItems;
  3445. @end
  3446. `;
  3447. const result = extractFromSource('DataSource.h', code);
  3448. const protocol = result.nodes.find((n) => n.kind === 'protocol' && n.name === 'DataSource');
  3449. expect(protocol).toBeDefined();
  3450. });
  3451. it('should report Objective-C as supported', () => {
  3452. expect(isLanguageSupported('objc')).toBe(true);
  3453. expect(getSupportedLanguages()).toContain('objc');
  3454. });
  3455. });