1
0

extraction.test.ts 125 KB

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