extraction.test.ts 125 KB

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