1
0

extraction.test.ts 131 KB

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