extraction.test.ts 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049
  1. /**
  2. * Extraction Tests
  3. *
  4. * Tests for the tree-sitter extraction system.
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { extractFromSource, scanDirectory, shouldIncludeFile } from '../src/extraction';
  12. import { detectLanguage, isLanguageSupported, getSupportedLanguages } from '../src/extraction/grammars';
  13. import { normalizePath } from '../src/utils';
  14. import { DEFAULT_CONFIG } from '../src/types';
  15. // Create a temporary directory for each test
  16. function createTempDir(): string {
  17. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  18. }
  19. // Clean up temporary directory
  20. function cleanupTempDir(dir: string): void {
  21. if (fs.existsSync(dir)) {
  22. fs.rmSync(dir, { recursive: true, force: true });
  23. }
  24. }
  25. describe('Language Detection', () => {
  26. it('should detect TypeScript files', () => {
  27. expect(detectLanguage('src/index.ts')).toBe('typescript');
  28. expect(detectLanguage('components/Button.tsx')).toBe('tsx');
  29. });
  30. it('should detect JavaScript files', () => {
  31. expect(detectLanguage('index.js')).toBe('javascript');
  32. expect(detectLanguage('App.jsx')).toBe('jsx');
  33. expect(detectLanguage('config.mjs')).toBe('javascript');
  34. });
  35. it('should detect Python files', () => {
  36. expect(detectLanguage('main.py')).toBe('python');
  37. });
  38. it('should detect Go files', () => {
  39. expect(detectLanguage('main.go')).toBe('go');
  40. });
  41. it('should detect Rust files', () => {
  42. expect(detectLanguage('lib.rs')).toBe('rust');
  43. });
  44. it('should detect Java files', () => {
  45. expect(detectLanguage('Main.java')).toBe('java');
  46. });
  47. it('should detect C files', () => {
  48. expect(detectLanguage('main.c')).toBe('c');
  49. expect(detectLanguage('utils.h')).toBe('c');
  50. });
  51. it('should detect C++ files', () => {
  52. expect(detectLanguage('main.cpp')).toBe('cpp');
  53. expect(detectLanguage('class.hpp')).toBe('cpp');
  54. });
  55. it('should detect C# files', () => {
  56. expect(detectLanguage('Program.cs')).toBe('csharp');
  57. });
  58. it('should detect PHP files', () => {
  59. expect(detectLanguage('index.php')).toBe('php');
  60. });
  61. it('should detect Ruby files', () => {
  62. expect(detectLanguage('app.rb')).toBe('ruby');
  63. });
  64. it('should detect Swift files', () => {
  65. expect(detectLanguage('ViewController.swift')).toBe('swift');
  66. });
  67. it('should detect Kotlin files', () => {
  68. expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
  69. expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
  70. });
  71. it('should detect Dart files', () => {
  72. expect(detectLanguage('main.dart')).toBe('dart');
  73. });
  74. it('should return unknown for unsupported extensions', () => {
  75. expect(detectLanguage('styles.css')).toBe('unknown');
  76. expect(detectLanguage('data.json')).toBe('unknown');
  77. });
  78. });
  79. describe('Language Support', () => {
  80. it('should report supported languages', () => {
  81. expect(isLanguageSupported('typescript')).toBe(true);
  82. expect(isLanguageSupported('python')).toBe(true);
  83. expect(isLanguageSupported('go')).toBe(true);
  84. expect(isLanguageSupported('unknown')).toBe(false);
  85. });
  86. it('should list all supported languages', () => {
  87. const languages = getSupportedLanguages();
  88. expect(languages).toContain('typescript');
  89. expect(languages).toContain('javascript');
  90. expect(languages).toContain('python');
  91. expect(languages).toContain('go');
  92. expect(languages).toContain('rust');
  93. expect(languages).toContain('java');
  94. expect(languages).toContain('csharp');
  95. expect(languages).toContain('php');
  96. expect(languages).toContain('ruby');
  97. expect(languages).toContain('swift');
  98. expect(languages).toContain('kotlin');
  99. expect(languages).toContain('dart');
  100. });
  101. });
  102. describe('TypeScript Extraction', () => {
  103. it('should extract function declarations', () => {
  104. const code = `
  105. export function processPayment(amount: number): Promise<Receipt> {
  106. return stripe.charge(amount);
  107. }
  108. `;
  109. const result = extractFromSource('payment.ts', code);
  110. // File node + function node
  111. const fileNode = result.nodes.find((n) => n.kind === 'file');
  112. expect(fileNode).toBeDefined();
  113. expect(fileNode?.name).toBe('payment.ts');
  114. const funcNode = result.nodes.find((n) => n.kind === 'function');
  115. expect(funcNode).toMatchObject({
  116. kind: 'function',
  117. name: 'processPayment',
  118. language: 'typescript',
  119. isExported: true,
  120. });
  121. expect(funcNode?.signature).toContain('amount: number');
  122. });
  123. it('should extract class declarations', () => {
  124. const code = `
  125. export class PaymentService {
  126. private stripe: StripeClient;
  127. constructor(apiKey: string) {
  128. this.stripe = new StripeClient(apiKey);
  129. }
  130. async charge(amount: number): Promise<Receipt> {
  131. return this.stripe.charge(amount);
  132. }
  133. }
  134. `;
  135. const result = extractFromSource('service.ts', code);
  136. const classNode = result.nodes.find((n) => n.kind === 'class');
  137. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  138. expect(classNode).toBeDefined();
  139. expect(classNode?.name).toBe('PaymentService');
  140. expect(classNode?.isExported).toBe(true);
  141. expect(methodNodes.length).toBeGreaterThanOrEqual(1);
  142. const chargeMethod = methodNodes.find((m) => m.name === 'charge');
  143. expect(chargeMethod).toBeDefined();
  144. });
  145. it('should extract interfaces', () => {
  146. const code = `
  147. export interface User {
  148. id: string;
  149. name: string;
  150. email: string;
  151. }
  152. `;
  153. const result = extractFromSource('types.ts', code);
  154. const fileNode = result.nodes.find((n) => n.kind === 'file');
  155. expect(fileNode).toBeDefined();
  156. const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
  157. expect(ifaceNode).toMatchObject({
  158. kind: 'interface',
  159. name: 'User',
  160. isExported: true,
  161. });
  162. });
  163. it('should track function calls', () => {
  164. const code = `
  165. function main() {
  166. const result = processData();
  167. console.log(result);
  168. }
  169. `;
  170. const result = extractFromSource('main.ts', code);
  171. expect(result.unresolvedReferences.length).toBeGreaterThan(0);
  172. const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
  173. expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
  174. });
  175. });
  176. describe('Arrow Function Export Extraction', () => {
  177. it('should extract exported arrow functions assigned to const', () => {
  178. const code = `
  179. export const useAuth = (): AuthContextValue => {
  180. return useContext(AuthContext);
  181. };
  182. `;
  183. const result = extractFromSource('hooks.ts', code);
  184. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
  185. expect(funcNode).toBeDefined();
  186. expect(funcNode).toMatchObject({
  187. kind: 'function',
  188. name: 'useAuth',
  189. isExported: true,
  190. });
  191. });
  192. it('should extract exported function expressions assigned to const', () => {
  193. const code = `
  194. export const processData = function(input: string): string {
  195. return input.trim();
  196. };
  197. `;
  198. const result = extractFromSource('utils.ts', code);
  199. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
  200. expect(funcNode).toBeDefined();
  201. expect(funcNode).toMatchObject({
  202. kind: 'function',
  203. name: 'processData',
  204. isExported: true,
  205. });
  206. });
  207. it('should not extract non-exported arrow functions as exported', () => {
  208. const code = `
  209. const internalHelper = () => {
  210. return 42;
  211. };
  212. `;
  213. const result = extractFromSource('internal.ts', code);
  214. const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
  215. expect(helperNode).toBeDefined();
  216. expect(helperNode?.isExported).toBeFalsy();
  217. });
  218. it('should still skip truly anonymous arrow functions', () => {
  219. const code = `
  220. const items = [1, 2, 3].map((x) => x * 2);
  221. `;
  222. const result = extractFromSource('anon.ts', code);
  223. // The inline arrow function passed to .map() has no variable_declarator parent
  224. // and should remain anonymous (skipped)
  225. const anonFunctions = result.nodes.filter(
  226. (n) => n.kind === 'function' && n.name === '<anonymous>'
  227. );
  228. expect(anonFunctions).toHaveLength(0);
  229. });
  230. it('should extract multiple exported arrow functions from the same file', () => {
  231. const code = `
  232. export const add = (a: number, b: number): number => a + b;
  233. export const subtract = (a: number, b: number): number => a - b;
  234. const internal = () => 'not exported';
  235. `;
  236. const result = extractFromSource('math.ts', code);
  237. const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
  238. expect(exported).toHaveLength(2);
  239. expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
  240. const internalNode = result.nodes.find((n) => n.name === 'internal');
  241. expect(internalNode).toBeDefined();
  242. expect(internalNode?.isExported).toBeFalsy();
  243. });
  244. it('should extract arrow functions in JavaScript files', () => {
  245. const code = `
  246. export const fetchData = async () => {
  247. const response = await fetch('/api/data');
  248. return response.json();
  249. };
  250. `;
  251. const result = extractFromSource('api.js', code);
  252. const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
  253. expect(funcNode).toBeDefined();
  254. expect(funcNode).toMatchObject({
  255. kind: 'function',
  256. name: 'fetchData',
  257. isExported: true,
  258. });
  259. });
  260. });
  261. describe('Type Alias Extraction', () => {
  262. it('should extract exported type aliases in TypeScript', () => {
  263. const code = `
  264. export type AuthContextValue = {
  265. user: User | null;
  266. login: () => void;
  267. logout: () => void;
  268. };
  269. `;
  270. const result = extractFromSource('types.ts', code);
  271. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  272. expect(typeNode).toMatchObject({
  273. kind: 'type_alias',
  274. name: 'AuthContextValue',
  275. isExported: true,
  276. });
  277. });
  278. it('should extract non-exported type aliases', () => {
  279. const code = `
  280. type InternalState = {
  281. loading: boolean;
  282. error: string | null;
  283. };
  284. `;
  285. const result = extractFromSource('internal.ts', code);
  286. const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
  287. expect(typeNode).toMatchObject({
  288. kind: 'type_alias',
  289. name: 'InternalState',
  290. isExported: false,
  291. });
  292. });
  293. it('should extract multiple type aliases from the same file', () => {
  294. const code = `
  295. export type UnitSystem = 'metric' | 'imperial';
  296. export type DateFormat = 'ISO' | 'US' | 'EU';
  297. type Internal = string;
  298. `;
  299. const result = extractFromSource('config.ts', code);
  300. const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
  301. expect(typeAliases).toHaveLength(3);
  302. const exported = typeAliases.filter((n) => n.isExported);
  303. expect(exported).toHaveLength(2);
  304. expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
  305. });
  306. });
  307. describe('Exported Variable Extraction', () => {
  308. it('should extract exported const with call expression (Zustand store)', () => {
  309. const code = `
  310. export const useUIStore = create<UIState>((set) => ({
  311. isOpen: false,
  312. toggle: () => set((s) => ({ isOpen: !s.isOpen })),
  313. }));
  314. `;
  315. const result = extractFromSource('store.ts', code);
  316. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'useUIStore');
  317. expect(varNode).toBeDefined();
  318. expect(varNode?.isExported).toBe(true);
  319. });
  320. it('should extract exported const with object literal', () => {
  321. const code = `
  322. export const config = {
  323. apiUrl: 'https://api.example.com',
  324. timeout: 5000,
  325. };
  326. `;
  327. const result = extractFromSource('config.ts', code);
  328. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'config');
  329. expect(varNode).toBeDefined();
  330. expect(varNode?.isExported).toBe(true);
  331. });
  332. it('should extract exported const with array literal', () => {
  333. const code = `
  334. export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
  335. `;
  336. const result = extractFromSource('constants.ts', code);
  337. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'SCREEN_NAMES');
  338. expect(varNode).toBeDefined();
  339. expect(varNode?.isExported).toBe(true);
  340. });
  341. it('should extract exported const with primitive value', () => {
  342. const code = `
  343. export const MAX_RETRIES = 3;
  344. export const API_VERSION = "v2";
  345. `;
  346. const result = extractFromSource('constants.ts', code);
  347. const variables = result.nodes.filter((n) => n.kind === 'variable');
  348. expect(variables).toHaveLength(2);
  349. expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
  350. });
  351. it('should NOT duplicate arrow functions as both function and variable', () => {
  352. const code = `
  353. export const useAuth = () => {
  354. return useContext(AuthContext);
  355. };
  356. `;
  357. const result = extractFromSource('hooks.ts', code);
  358. // Should be extracted as function (from arrow function handler), NOT as variable
  359. const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
  360. const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
  361. expect(funcNodes).toHaveLength(1);
  362. expect(varNodes).toHaveLength(0);
  363. });
  364. it('should extract non-exported const as non-exported variable', () => {
  365. const code = `
  366. const internalConfig = {
  367. debug: true,
  368. };
  369. `;
  370. const result = extractFromSource('internal.ts', code);
  371. // Non-exported const at file level should be extracted as a constant (not exported)
  372. const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
  373. expect(varNodes).toHaveLength(1);
  374. expect(varNodes[0]?.isExported).toBeFalsy();
  375. });
  376. it('should extract Zod schema exports', () => {
  377. const code = `
  378. export const userSchema = z.object({
  379. id: z.string(),
  380. name: z.string(),
  381. email: z.string().email(),
  382. });
  383. `;
  384. const result = extractFromSource('schemas.ts', code);
  385. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'userSchema');
  386. expect(varNode).toBeDefined();
  387. expect(varNode?.isExported).toBe(true);
  388. });
  389. it('should extract XState machine exports', () => {
  390. const code = `
  391. export const authMachine = createMachine({
  392. id: "auth",
  393. initial: "idle",
  394. states: {
  395. idle: {},
  396. authenticated: {},
  397. },
  398. });
  399. `;
  400. const result = extractFromSource('machine.ts', code);
  401. const varNode = result.nodes.find((n) => n.kind === 'variable' && n.name === 'authMachine');
  402. expect(varNode).toBeDefined();
  403. expect(varNode?.isExported).toBe(true);
  404. });
  405. });
  406. describe('File Node Extraction', () => {
  407. it('should create a file-kind node for each parsed file', () => {
  408. const code = `
  409. export function greet(name: string): string {
  410. return "Hello " + name;
  411. }
  412. `;
  413. const result = extractFromSource('greeter.ts', code);
  414. const fileNode = result.nodes.find((n) => n.kind === 'file');
  415. expect(fileNode).toBeDefined();
  416. expect(fileNode?.name).toBe('greeter.ts');
  417. expect(fileNode?.filePath).toBe('greeter.ts');
  418. expect(fileNode?.language).toBe('typescript');
  419. expect(fileNode?.startLine).toBe(1);
  420. });
  421. it('should create file nodes for Python files', () => {
  422. const code = `
  423. def main():
  424. pass
  425. `;
  426. const result = extractFromSource('main.py', code);
  427. const fileNode = result.nodes.find((n) => n.kind === 'file');
  428. expect(fileNode).toBeDefined();
  429. expect(fileNode?.name).toBe('main.py');
  430. expect(fileNode?.language).toBe('python');
  431. });
  432. it('should create containment edges from file node to top-level declarations', () => {
  433. const code = `
  434. export function foo() {}
  435. export function bar() {}
  436. `;
  437. const result = extractFromSource('fns.ts', code);
  438. const fileNode = result.nodes.find((n) => n.kind === 'file');
  439. expect(fileNode).toBeDefined();
  440. // There should be contains edges from the file node to each function
  441. const containsEdges = result.edges.filter(
  442. (e) => e.source === fileNode?.id && e.kind === 'contains'
  443. );
  444. expect(containsEdges.length).toBeGreaterThanOrEqual(2);
  445. });
  446. });
  447. describe('Python Extraction', () => {
  448. it('should extract function definitions', () => {
  449. const code = `
  450. def calculate_total(items: list, tax_rate: float) -> float:
  451. """Calculate total with tax."""
  452. subtotal = sum(item.price for item in items)
  453. return subtotal * (1 + tax_rate)
  454. `;
  455. const result = extractFromSource('calc.py', code);
  456. const fileNode = result.nodes.find((n) => n.kind === 'file');
  457. expect(fileNode).toBeDefined();
  458. const funcNode = result.nodes.find((n) => n.kind === 'function');
  459. expect(funcNode).toMatchObject({
  460. kind: 'function',
  461. name: 'calculate_total',
  462. language: 'python',
  463. });
  464. });
  465. it('should extract class definitions', () => {
  466. const code = `
  467. class UserService:
  468. """Service for managing users."""
  469. def __init__(self, db):
  470. self.db = db
  471. def get_user(self, user_id: str) -> User:
  472. return self.db.find_user(user_id)
  473. `;
  474. const result = extractFromSource('service.py', code);
  475. const classNode = result.nodes.find((n) => n.kind === 'class');
  476. expect(classNode).toBeDefined();
  477. expect(classNode?.name).toBe('UserService');
  478. });
  479. });
  480. describe('Go Extraction', () => {
  481. it('should extract function declarations', () => {
  482. const code = `
  483. package main
  484. func ProcessOrder(order Order) (Receipt, error) {
  485. // Process the order
  486. return Receipt{}, nil
  487. }
  488. `;
  489. const result = extractFromSource('main.go', code);
  490. const funcNode = result.nodes.find((n) => n.kind === 'function');
  491. expect(funcNode).toBeDefined();
  492. expect(funcNode?.name).toBe('ProcessOrder');
  493. });
  494. it('should extract method declarations', () => {
  495. const code = `
  496. package main
  497. type Service struct {
  498. db *Database
  499. }
  500. func (s *Service) GetUser(id string) (*User, error) {
  501. return s.db.FindUser(id)
  502. }
  503. `;
  504. const result = extractFromSource('service.go', code);
  505. const methodNode = result.nodes.find((n) => n.kind === 'method');
  506. expect(methodNode).toBeDefined();
  507. expect(methodNode?.name).toBe('GetUser');
  508. });
  509. });
  510. describe('Rust Extraction', () => {
  511. it('should extract function declarations', () => {
  512. const code = `
  513. pub fn process_data(input: &str) -> Result<Output, Error> {
  514. // Process data
  515. Ok(Output::new())
  516. }
  517. `;
  518. const result = extractFromSource('lib.rs', code);
  519. const funcNode = result.nodes.find((n) => n.kind === 'function');
  520. expect(funcNode).toBeDefined();
  521. expect(funcNode?.name).toBe('process_data');
  522. expect(funcNode?.visibility).toBe('public');
  523. });
  524. it('should extract struct declarations', () => {
  525. const code = `
  526. pub struct User {
  527. pub id: String,
  528. pub name: String,
  529. email: String,
  530. }
  531. `;
  532. const result = extractFromSource('models.rs', code);
  533. const structNode = result.nodes.find((n) => n.kind === 'struct');
  534. expect(structNode).toBeDefined();
  535. expect(structNode?.name).toBe('User');
  536. });
  537. it('should extract trait declarations', () => {
  538. const code = `
  539. pub trait Repository {
  540. fn find(&self, id: &str) -> Option<Entity>;
  541. fn save(&mut self, entity: Entity) -> Result<(), Error>;
  542. }
  543. `;
  544. const result = extractFromSource('traits.rs', code);
  545. const traitNode = result.nodes.find((n) => n.kind === 'trait');
  546. expect(traitNode).toBeDefined();
  547. expect(traitNode?.name).toBe('Repository');
  548. });
  549. });
  550. describe('Java Extraction', () => {
  551. it('should extract class declarations', () => {
  552. const code = `
  553. public class UserService {
  554. private final UserRepository repository;
  555. public UserService(UserRepository repository) {
  556. this.repository = repository;
  557. }
  558. public User getUser(String id) {
  559. return repository.findById(id);
  560. }
  561. }
  562. `;
  563. const result = extractFromSource('UserService.java', code);
  564. const classNode = result.nodes.find((n) => n.kind === 'class');
  565. expect(classNode).toBeDefined();
  566. expect(classNode?.name).toBe('UserService');
  567. expect(classNode?.visibility).toBe('public');
  568. });
  569. it('should extract method declarations', () => {
  570. const code = `
  571. public class Calculator {
  572. public static int add(int a, int b) {
  573. return a + b;
  574. }
  575. }
  576. `;
  577. const result = extractFromSource('Calculator.java', code);
  578. const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
  579. expect(methodNode).toBeDefined();
  580. expect(methodNode?.isStatic).toBe(true);
  581. });
  582. });
  583. describe('C# Extraction', () => {
  584. it('should extract class declarations', () => {
  585. const code = `
  586. public class OrderService
  587. {
  588. private readonly IOrderRepository _repository;
  589. public OrderService(IOrderRepository repository)
  590. {
  591. _repository = repository;
  592. }
  593. public async Task<Order> GetOrderAsync(string id)
  594. {
  595. return await _repository.FindByIdAsync(id);
  596. }
  597. }
  598. `;
  599. const result = extractFromSource('OrderService.cs', code);
  600. const classNode = result.nodes.find((n) => n.kind === 'class');
  601. expect(classNode).toBeDefined();
  602. expect(classNode?.name).toBe('OrderService');
  603. expect(classNode?.visibility).toBe('public');
  604. });
  605. });
  606. describe('PHP Extraction', () => {
  607. it('should extract class declarations', () => {
  608. const code = `<?php
  609. class UserController
  610. {
  611. private UserService $userService;
  612. public function __construct(UserService $userService)
  613. {
  614. $this->userService = $userService;
  615. }
  616. public function show(string $id): User
  617. {
  618. return $this->userService->find($id);
  619. }
  620. }
  621. `;
  622. const result = extractFromSource('UserController.php', code);
  623. const classNode = result.nodes.find((n) => n.kind === 'class');
  624. expect(classNode).toBeDefined();
  625. expect(classNode?.name).toBe('UserController');
  626. });
  627. });
  628. describe('Swift Extraction', () => {
  629. it('should extract class declarations', () => {
  630. const code = `
  631. public class NetworkManager {
  632. private let session: URLSession
  633. public init(session: URLSession = .shared) {
  634. self.session = session
  635. }
  636. public func fetchData(from url: URL) async throws -> Data {
  637. let (data, _) = try await session.data(from: url)
  638. return data
  639. }
  640. }
  641. `;
  642. const result = extractFromSource('NetworkManager.swift', code);
  643. const classNode = result.nodes.find((n) => n.kind === 'class');
  644. expect(classNode).toBeDefined();
  645. expect(classNode?.name).toBe('NetworkManager');
  646. });
  647. it('should extract function declarations', () => {
  648. const code = `
  649. func calculateSum(_ numbers: [Int]) -> Int {
  650. return numbers.reduce(0, +)
  651. }
  652. public func formatCurrency(amount: Double) -> String {
  653. return String(format: "$%.2f", amount)
  654. }
  655. `;
  656. const result = extractFromSource('utils.swift', code);
  657. const functions = result.nodes.filter((n) => n.kind === 'function');
  658. expect(functions.length).toBeGreaterThanOrEqual(1);
  659. });
  660. it('should extract struct declarations', () => {
  661. const code = `
  662. public struct User {
  663. let id: UUID
  664. var name: String
  665. var email: String
  666. func displayName() -> String {
  667. return name
  668. }
  669. }
  670. `;
  671. const result = extractFromSource('User.swift', code);
  672. const structNode = result.nodes.find((n) => n.kind === 'struct');
  673. expect(structNode).toBeDefined();
  674. expect(structNode?.name).toBe('User');
  675. });
  676. it('should extract protocol declarations', () => {
  677. const code = `
  678. public protocol Repository {
  679. associatedtype Entity
  680. func find(id: String) async throws -> Entity?
  681. func save(_ entity: Entity) async throws
  682. }
  683. `;
  684. const result = extractFromSource('Repository.swift', code);
  685. const protocolNode = result.nodes.find((n) => n.kind === 'interface');
  686. expect(protocolNode).toBeDefined();
  687. expect(protocolNode?.name).toBe('Repository');
  688. });
  689. });
  690. describe('Kotlin Extraction', () => {
  691. it('should extract class declarations', () => {
  692. const code = `
  693. class UserRepository(private val database: Database) {
  694. fun findById(id: String): User? {
  695. return database.query("SELECT * FROM users WHERE id = ?", id)
  696. }
  697. suspend fun save(user: User) {
  698. database.insert(user)
  699. }
  700. }
  701. `;
  702. const result = extractFromSource('UserRepository.kt', code);
  703. const classNode = result.nodes.find((n) => n.kind === 'class');
  704. expect(classNode).toBeDefined();
  705. expect(classNode?.name).toBe('UserRepository');
  706. });
  707. it('should extract function declarations', () => {
  708. const code = `
  709. fun calculateTotal(items: List<Item>): Double {
  710. return items.sumOf { it.price }
  711. }
  712. suspend fun fetchUserData(userId: String): User {
  713. return api.getUser(userId)
  714. }
  715. `;
  716. const result = extractFromSource('utils.kt', code);
  717. const functions = result.nodes.filter((n) => n.kind === 'function');
  718. expect(functions.length).toBeGreaterThanOrEqual(1);
  719. });
  720. it('should detect suspend functions as async', () => {
  721. const code = `
  722. suspend fun loadData(): List<String> {
  723. delay(1000)
  724. return listOf("a", "b", "c")
  725. }
  726. `;
  727. const result = extractFromSource('loader.kt', code);
  728. const funcNode = result.nodes.find((n) => n.kind === 'function');
  729. expect(funcNode).toBeDefined();
  730. expect(funcNode?.isAsync).toBe(true);
  731. });
  732. });
  733. describe('Dart Extraction', () => {
  734. it('should extract class declarations', () => {
  735. const code = `
  736. class UserService {
  737. final Database _db;
  738. Future<User> findById(String id) async {
  739. return await _db.query(id);
  740. }
  741. void _privateMethod() {}
  742. }
  743. `;
  744. const result = extractFromSource('service.dart', code);
  745. const classNode = result.nodes.find((n) => n.kind === 'class');
  746. expect(classNode).toBeDefined();
  747. expect(classNode?.name).toBe('UserService');
  748. expect(classNode?.visibility).toBe('public');
  749. const methodNodes = result.nodes.filter((n) => n.kind === 'method');
  750. expect(methodNodes.length).toBeGreaterThanOrEqual(2);
  751. const findById = methodNodes.find((m) => m.name === 'findById');
  752. expect(findById).toBeDefined();
  753. expect(findById?.isAsync).toBe(true);
  754. const privateMethod = methodNodes.find((m) => m.name === '_privateMethod');
  755. expect(privateMethod).toBeDefined();
  756. expect(privateMethod?.visibility).toBe('private');
  757. });
  758. it('should extract top-level function declarations', () => {
  759. const code = `
  760. void topLevelFunction(String name) {
  761. print(name);
  762. }
  763. `;
  764. const result = extractFromSource('utils.dart', code);
  765. const funcNode = result.nodes.find((n) => n.kind === 'function');
  766. expect(funcNode).toBeDefined();
  767. expect(funcNode?.name).toBe('topLevelFunction');
  768. expect(funcNode?.language).toBe('dart');
  769. });
  770. it('should extract enum declarations', () => {
  771. const code = `
  772. enum Status { active, inactive, pending }
  773. `;
  774. const result = extractFromSource('models.dart', code);
  775. const enumNode = result.nodes.find((n) => n.kind === 'enum');
  776. expect(enumNode).toBeDefined();
  777. expect(enumNode?.name).toBe('Status');
  778. });
  779. it('should extract mixin declarations', () => {
  780. const code = `
  781. mixin LoggerMixin {
  782. void log(String message) {}
  783. }
  784. `;
  785. const result = extractFromSource('mixins.dart', code);
  786. const classNode = result.nodes.find((n) => n.kind === 'class');
  787. expect(classNode).toBeDefined();
  788. expect(classNode?.name).toBe('LoggerMixin');
  789. const methodNode = result.nodes.find((n) => n.kind === 'method');
  790. expect(methodNode).toBeDefined();
  791. expect(methodNode?.name).toBe('log');
  792. });
  793. it('should extract extension declarations', () => {
  794. const code = `
  795. extension StringExt on String {
  796. bool get isBlank => trim().isEmpty;
  797. }
  798. `;
  799. const result = extractFromSource('extensions.dart', code);
  800. const classNode = result.nodes.find((n) => n.kind === 'class');
  801. expect(classNode).toBeDefined();
  802. expect(classNode?.name).toBe('StringExt');
  803. });
  804. it('should detect static methods', () => {
  805. const code = `
  806. class Utils {
  807. static void doWork() {}
  808. }
  809. `;
  810. const result = extractFromSource('utils.dart', code);
  811. const methodNode = result.nodes.find((n) => n.kind === 'method');
  812. expect(methodNode).toBeDefined();
  813. expect(methodNode?.name).toBe('doWork');
  814. expect(methodNode?.isStatic).toBe(true);
  815. });
  816. it('should detect async functions', () => {
  817. const code = `
  818. Future<String> fetchData() async {
  819. return await http.get('/data');
  820. }
  821. `;
  822. const result = extractFromSource('api.dart', code);
  823. const funcNode = result.nodes.find((n) => n.kind === 'function');
  824. expect(funcNode).toBeDefined();
  825. expect(funcNode?.name).toBe('fetchData');
  826. expect(funcNode?.isAsync).toBe(true);
  827. });
  828. it('should detect private visibility via underscore convention', () => {
  829. const code = `
  830. void _privateHelper() {}
  831. void publicFunction() {}
  832. `;
  833. const result = extractFromSource('helpers.dart', code);
  834. const functions = result.nodes.filter((n) => n.kind === 'function');
  835. const privateFunc = functions.find((f) => f.name === '_privateHelper');
  836. const publicFunc = functions.find((f) => f.name === 'publicFunction');
  837. expect(privateFunc?.visibility).toBe('private');
  838. expect(publicFunc?.visibility).toBe('public');
  839. });
  840. });
  841. describe('Import Extraction', () => {
  842. describe('TypeScript/JavaScript imports', () => {
  843. it('should extract default imports', () => {
  844. const code = `import React from 'react';`;
  845. const result = extractFromSource('app.tsx', code);
  846. const importNode = result.nodes.find((n) => n.kind === 'import');
  847. expect(importNode).toBeDefined();
  848. expect(importNode?.name).toBe('react');
  849. expect(importNode?.signature).toBe("import React from 'react';");
  850. });
  851. it('should extract named imports', () => {
  852. const code = `import { Bug, Database } from '@phosphor-icons/react';`;
  853. const result = extractFromSource('icons.tsx', code);
  854. const importNode = result.nodes.find((n) => n.kind === 'import');
  855. expect(importNode).toBeDefined();
  856. expect(importNode?.name).toBe('@phosphor-icons/react');
  857. expect(importNode?.signature).toContain('Bug');
  858. expect(importNode?.signature).toContain('Database');
  859. });
  860. it('should extract namespace imports', () => {
  861. const code = `import * as Icons from '@phosphor-icons/react';`;
  862. const result = extractFromSource('icons.tsx', code);
  863. const importNode = result.nodes.find((n) => n.kind === 'import');
  864. expect(importNode).toBeDefined();
  865. expect(importNode?.name).toBe('@phosphor-icons/react');
  866. expect(importNode?.signature).toContain('* as Icons');
  867. });
  868. it('should extract side-effect imports', () => {
  869. const code = `import './styles.css';`;
  870. const result = extractFromSource('app.tsx', code);
  871. const importNode = result.nodes.find((n) => n.kind === 'import');
  872. expect(importNode).toBeDefined();
  873. expect(importNode?.name).toBe('./styles.css');
  874. });
  875. it('should extract mixed imports (default + named)', () => {
  876. const code = `import React, { useState, useEffect } from 'react';`;
  877. const result = extractFromSource('app.tsx', code);
  878. const importNode = result.nodes.find((n) => n.kind === 'import');
  879. expect(importNode).toBeDefined();
  880. expect(importNode?.name).toBe('react');
  881. expect(importNode?.signature).toContain('React');
  882. expect(importNode?.signature).toContain('useState');
  883. expect(importNode?.signature).toContain('useEffect');
  884. });
  885. it('should extract multiple import statements', () => {
  886. const code = `
  887. import React from 'react';
  888. import { Button } from './components';
  889. import './styles.css';
  890. `;
  891. const result = extractFromSource('app.tsx', code);
  892. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  893. expect(importNodes.length).toBe(3);
  894. const names = importNodes.map((n) => n.name);
  895. expect(names).toContain('react');
  896. expect(names).toContain('./components');
  897. expect(names).toContain('./styles.css');
  898. });
  899. it('should extract type imports', () => {
  900. const code = `import type { FC, ReactNode } from 'react';`;
  901. const result = extractFromSource('types.ts', code);
  902. const importNode = result.nodes.find((n) => n.kind === 'import');
  903. expect(importNode).toBeDefined();
  904. expect(importNode?.name).toBe('react');
  905. expect(importNode?.signature).toContain('type');
  906. expect(importNode?.signature).toContain('FC');
  907. });
  908. it('should extract aliased named imports', () => {
  909. const code = `import { useState as useStateAlias } from 'react';`;
  910. const result = extractFromSource('hooks.ts', code);
  911. const importNode = result.nodes.find((n) => n.kind === 'import');
  912. expect(importNode).toBeDefined();
  913. expect(importNode?.name).toBe('react');
  914. expect(importNode?.signature).toContain('useState');
  915. expect(importNode?.signature).toContain('useStateAlias');
  916. });
  917. it('should extract relative path imports', () => {
  918. const code = `import { helper } from '../utils/helper';`;
  919. const result = extractFromSource('components/Button.tsx', code);
  920. const importNode = result.nodes.find((n) => n.kind === 'import');
  921. expect(importNode).toBeDefined();
  922. expect(importNode?.name).toBe('../utils/helper');
  923. expect(importNode?.signature).toContain('helper');
  924. });
  925. });
  926. describe('Python imports', () => {
  927. it('should extract simple import statement', () => {
  928. const code = `import json`;
  929. const result = extractFromSource('utils.py', code);
  930. const importNode = result.nodes.find((n) => n.kind === 'import');
  931. expect(importNode).toBeDefined();
  932. expect(importNode?.name).toBe('json');
  933. });
  934. it('should extract from import statement', () => {
  935. const code = `from os import path`;
  936. const result = extractFromSource('utils.py', code);
  937. const importNode = result.nodes.find((n) => n.kind === 'import');
  938. expect(importNode).toBeDefined();
  939. expect(importNode?.name).toBe('os');
  940. expect(importNode?.signature).toContain('path');
  941. });
  942. it('should extract multiple imports from same module', () => {
  943. const code = `from typing import List, Dict, Optional`;
  944. const result = extractFromSource('types.py', code);
  945. const importNode = result.nodes.find((n) => n.kind === 'import');
  946. expect(importNode).toBeDefined();
  947. expect(importNode?.name).toBe('typing');
  948. expect(importNode?.signature).toContain('List');
  949. expect(importNode?.signature).toContain('Dict');
  950. });
  951. it('should extract multiple import statements', () => {
  952. const code = `
  953. import os
  954. import sys
  955. `;
  956. const result = extractFromSource('main.py', code);
  957. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  958. expect(importNodes.length).toBe(2);
  959. const names = importNodes.map((n) => n.name);
  960. expect(names).toContain('os');
  961. expect(names).toContain('sys');
  962. });
  963. it('should extract aliased import', () => {
  964. const code = `import numpy as np`;
  965. const result = extractFromSource('data.py', code);
  966. const importNode = result.nodes.find((n) => n.kind === 'import');
  967. expect(importNode).toBeDefined();
  968. expect(importNode?.name).toBe('numpy');
  969. expect(importNode?.signature).toContain('as np');
  970. });
  971. it('should extract relative import', () => {
  972. const code = `from .utils import helper`;
  973. const result = extractFromSource('module.py', code);
  974. const importNode = result.nodes.find((n) => n.kind === 'import');
  975. expect(importNode).toBeDefined();
  976. expect(importNode?.name).toBe('.utils');
  977. expect(importNode?.signature).toContain('helper');
  978. });
  979. it('should extract wildcard import', () => {
  980. const code = `from typing import *`;
  981. const result = extractFromSource('types.py', code);
  982. const importNode = result.nodes.find((n) => n.kind === 'import');
  983. expect(importNode).toBeDefined();
  984. expect(importNode?.name).toBe('typing');
  985. expect(importNode?.signature).toContain('*');
  986. });
  987. });
  988. describe('Rust imports', () => {
  989. it('should extract simple use declaration', () => {
  990. const code = `use std::io;`;
  991. const result = extractFromSource('main.rs', code);
  992. const importNode = result.nodes.find((n) => n.kind === 'import');
  993. expect(importNode).toBeDefined();
  994. expect(importNode?.name).toBe('std');
  995. expect(importNode?.signature).toBe('use std::io;');
  996. });
  997. it('should extract scoped use list', () => {
  998. const code = `use std::{ffi::OsStr, io, path::Path};`;
  999. const result = extractFromSource('main.rs', code);
  1000. const importNode = result.nodes.find((n) => n.kind === 'import');
  1001. expect(importNode).toBeDefined();
  1002. expect(importNode?.name).toBe('std');
  1003. expect(importNode?.signature).toContain('ffi::OsStr');
  1004. expect(importNode?.signature).toContain('path::Path');
  1005. });
  1006. it('should extract crate imports', () => {
  1007. const code = `use crate::error::Error;`;
  1008. const result = extractFromSource('lib.rs', code);
  1009. const importNode = result.nodes.find((n) => n.kind === 'import');
  1010. expect(importNode).toBeDefined();
  1011. expect(importNode?.name).toBe('crate');
  1012. });
  1013. it('should extract super imports', () => {
  1014. const code = `use super::utils;`;
  1015. const result = extractFromSource('submod.rs', code);
  1016. const importNode = result.nodes.find((n) => n.kind === 'import');
  1017. expect(importNode).toBeDefined();
  1018. expect(importNode?.name).toBe('super');
  1019. });
  1020. it('should extract external crate imports', () => {
  1021. const code = `use serde::{Serialize, Deserialize};`;
  1022. const result = extractFromSource('types.rs', code);
  1023. const importNode = result.nodes.find((n) => n.kind === 'import');
  1024. expect(importNode).toBeDefined();
  1025. expect(importNode?.name).toBe('serde');
  1026. expect(importNode?.signature).toContain('Serialize');
  1027. expect(importNode?.signature).toContain('Deserialize');
  1028. });
  1029. });
  1030. describe('Go imports', () => {
  1031. it('should extract single import', () => {
  1032. const code = `
  1033. package main
  1034. import "fmt"
  1035. `;
  1036. const result = extractFromSource('main.go', code);
  1037. const importNode = result.nodes.find((n) => n.kind === 'import');
  1038. expect(importNode).toBeDefined();
  1039. expect(importNode?.name).toBe('fmt');
  1040. });
  1041. it('should extract grouped imports', () => {
  1042. const code = `
  1043. package main
  1044. import (
  1045. "fmt"
  1046. "os"
  1047. "encoding/json"
  1048. )
  1049. `;
  1050. const result = extractFromSource('main.go', code);
  1051. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1052. expect(importNodes.length).toBe(3);
  1053. const names = importNodes.map((n) => n.name);
  1054. expect(names).toContain('fmt');
  1055. expect(names).toContain('os');
  1056. expect(names).toContain('encoding/json');
  1057. });
  1058. it('should extract aliased import', () => {
  1059. const code = `
  1060. package main
  1061. import f "fmt"
  1062. `;
  1063. const result = extractFromSource('main.go', code);
  1064. const importNode = result.nodes.find((n) => n.kind === 'import');
  1065. expect(importNode).toBeDefined();
  1066. expect(importNode?.name).toBe('fmt');
  1067. expect(importNode?.signature).toContain('f');
  1068. });
  1069. it('should extract dot import', () => {
  1070. const code = `
  1071. package main
  1072. import . "math"
  1073. `;
  1074. const result = extractFromSource('main.go', code);
  1075. const importNode = result.nodes.find((n) => n.kind === 'import');
  1076. expect(importNode).toBeDefined();
  1077. expect(importNode?.name).toBe('math');
  1078. expect(importNode?.signature).toContain('.');
  1079. });
  1080. it('should extract blank import', () => {
  1081. const code = `
  1082. package main
  1083. import _ "github.com/go-sql-driver/mysql"
  1084. `;
  1085. const result = extractFromSource('main.go', code);
  1086. const importNode = result.nodes.find((n) => n.kind === 'import');
  1087. expect(importNode).toBeDefined();
  1088. expect(importNode?.name).toBe('github.com/go-sql-driver/mysql');
  1089. expect(importNode?.signature).toContain('_');
  1090. });
  1091. });
  1092. describe('Swift imports', () => {
  1093. it('should extract simple import', () => {
  1094. const code = `import Foundation`;
  1095. const result = extractFromSource('main.swift', code);
  1096. const importNode = result.nodes.find((n) => n.kind === 'import');
  1097. expect(importNode).toBeDefined();
  1098. expect(importNode?.name).toBe('Foundation');
  1099. expect(importNode?.signature).toBe('import Foundation');
  1100. });
  1101. it('should extract @testable import', () => {
  1102. const code = `@testable import Alamofire`;
  1103. const result = extractFromSource('Tests.swift', code);
  1104. const importNode = result.nodes.find((n) => n.kind === 'import');
  1105. expect(importNode).toBeDefined();
  1106. expect(importNode?.name).toBe('Alamofire');
  1107. expect(importNode?.signature).toContain('@testable');
  1108. });
  1109. it('should extract @preconcurrency import', () => {
  1110. const code = `@preconcurrency import Security`;
  1111. const result = extractFromSource('Auth.swift', code);
  1112. const importNode = result.nodes.find((n) => n.kind === 'import');
  1113. expect(importNode).toBeDefined();
  1114. expect(importNode?.name).toBe('Security');
  1115. });
  1116. it('should extract multiple imports', () => {
  1117. const code = `
  1118. import Foundation
  1119. import UIKit
  1120. import Alamofire
  1121. `;
  1122. const result = extractFromSource('App.swift', code);
  1123. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1124. expect(importNodes.length).toBe(3);
  1125. const names = importNodes.map((n) => n.name);
  1126. expect(names).toContain('Foundation');
  1127. expect(names).toContain('UIKit');
  1128. expect(names).toContain('Alamofire');
  1129. });
  1130. });
  1131. describe('Kotlin imports', () => {
  1132. it('should extract simple import', () => {
  1133. const code = `import java.io.IOException`;
  1134. const result = extractFromSource('Main.kt', code);
  1135. const importNode = result.nodes.find((n) => n.kind === 'import');
  1136. expect(importNode).toBeDefined();
  1137. expect(importNode?.name).toBe('java.io.IOException');
  1138. expect(importNode?.signature).toBe('import java.io.IOException');
  1139. });
  1140. it('should extract aliased import', () => {
  1141. const code = `import okhttp3.Request.Builder as RequestBuilder`;
  1142. const result = extractFromSource('Utils.kt', code);
  1143. const importNode = result.nodes.find((n) => n.kind === 'import');
  1144. expect(importNode).toBeDefined();
  1145. expect(importNode?.name).toBe('okhttp3.Request.Builder');
  1146. expect(importNode?.signature).toContain('as RequestBuilder');
  1147. });
  1148. it('should extract wildcard import', () => {
  1149. const code = `import java.util.concurrent.TimeUnit.*`;
  1150. const result = extractFromSource('Time.kt', code);
  1151. const importNode = result.nodes.find((n) => n.kind === 'import');
  1152. expect(importNode).toBeDefined();
  1153. expect(importNode?.name).toBe('java.util.concurrent.TimeUnit');
  1154. expect(importNode?.signature).toContain('.*');
  1155. });
  1156. it('should extract multiple imports', () => {
  1157. const code = `
  1158. import java.io.IOException
  1159. import kotlin.test.assertFailsWith
  1160. import okhttp3.OkHttpClient
  1161. `;
  1162. const result = extractFromSource('Test.kt', code);
  1163. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1164. expect(importNodes.length).toBe(3);
  1165. const names = importNodes.map((n) => n.name);
  1166. expect(names).toContain('java.io.IOException');
  1167. expect(names).toContain('kotlin.test.assertFailsWith');
  1168. expect(names).toContain('okhttp3.OkHttpClient');
  1169. });
  1170. });
  1171. describe('Java imports', () => {
  1172. it('should extract simple import', () => {
  1173. const code = `import java.util.List;`;
  1174. const result = extractFromSource('Main.java', code);
  1175. const importNode = result.nodes.find((n) => n.kind === 'import');
  1176. expect(importNode).toBeDefined();
  1177. expect(importNode?.name).toBe('java.util.List');
  1178. expect(importNode?.signature).toBe('import java.util.List;');
  1179. });
  1180. it('should extract static import', () => {
  1181. const code = `import static java.util.Collections.emptyList;`;
  1182. const result = extractFromSource('Utils.java', code);
  1183. const importNode = result.nodes.find((n) => n.kind === 'import');
  1184. expect(importNode).toBeDefined();
  1185. expect(importNode?.name).toBe('java.util.Collections.emptyList');
  1186. expect(importNode?.signature).toContain('static');
  1187. });
  1188. it('should extract wildcard import', () => {
  1189. const code = `import java.util.*;`;
  1190. const result = extractFromSource('App.java', code);
  1191. const importNode = result.nodes.find((n) => n.kind === 'import');
  1192. expect(importNode).toBeDefined();
  1193. expect(importNode?.name).toBe('java.util');
  1194. expect(importNode?.signature).toContain('.*');
  1195. });
  1196. it('should extract nested class import', () => {
  1197. const code = `import java.util.Map.Entry;`;
  1198. const result = extractFromSource('MapUtil.java', code);
  1199. const importNode = result.nodes.find((n) => n.kind === 'import');
  1200. expect(importNode).toBeDefined();
  1201. expect(importNode?.name).toBe('java.util.Map.Entry');
  1202. });
  1203. it('should extract multiple imports', () => {
  1204. const code = `
  1205. import java.util.List;
  1206. import java.util.Map;
  1207. import java.io.IOException;
  1208. `;
  1209. const result = extractFromSource('Service.java', code);
  1210. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1211. expect(importNodes.length).toBe(3);
  1212. const names = importNodes.map((n) => n.name);
  1213. expect(names).toContain('java.util.List');
  1214. expect(names).toContain('java.util.Map');
  1215. expect(names).toContain('java.io.IOException');
  1216. });
  1217. });
  1218. describe('C# imports', () => {
  1219. it('should extract simple using', () => {
  1220. const code = `using System;`;
  1221. const result = extractFromSource('Program.cs', code);
  1222. const importNode = result.nodes.find((n) => n.kind === 'import');
  1223. expect(importNode).toBeDefined();
  1224. expect(importNode?.name).toBe('System');
  1225. expect(importNode?.signature).toBe('using System;');
  1226. });
  1227. it('should extract qualified using', () => {
  1228. const code = `using System.Collections.Generic;`;
  1229. const result = extractFromSource('Utils.cs', code);
  1230. const importNode = result.nodes.find((n) => n.kind === 'import');
  1231. expect(importNode).toBeDefined();
  1232. expect(importNode?.name).toBe('System.Collections.Generic');
  1233. });
  1234. it('should extract static using', () => {
  1235. const code = `using static System.Console;`;
  1236. const result = extractFromSource('App.cs', code);
  1237. const importNode = result.nodes.find((n) => n.kind === 'import');
  1238. expect(importNode).toBeDefined();
  1239. expect(importNode?.name).toBe('System.Console');
  1240. expect(importNode?.signature).toContain('static');
  1241. });
  1242. it('should extract alias using', () => {
  1243. const code = `using MyList = System.Collections.Generic.List<int>;`;
  1244. const result = extractFromSource('Types.cs', code);
  1245. const importNode = result.nodes.find((n) => n.kind === 'import');
  1246. expect(importNode).toBeDefined();
  1247. expect(importNode?.name).toBe('System.Collections.Generic.List<int>');
  1248. expect(importNode?.signature).toContain('MyList =');
  1249. });
  1250. it('should extract multiple usings', () => {
  1251. const code = `
  1252. using System;
  1253. using System.Threading.Tasks;
  1254. using Microsoft.Extensions.DependencyInjection;
  1255. `;
  1256. const result = extractFromSource('Service.cs', code);
  1257. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1258. expect(importNodes.length).toBe(3);
  1259. const names = importNodes.map((n) => n.name);
  1260. expect(names).toContain('System');
  1261. expect(names).toContain('System.Threading.Tasks');
  1262. expect(names).toContain('Microsoft.Extensions.DependencyInjection');
  1263. });
  1264. });
  1265. describe('PHP imports', () => {
  1266. it('should extract simple use', () => {
  1267. const code = `<?php use PHPUnit\\Framework\\TestCase;`;
  1268. const result = extractFromSource('Test.php', code);
  1269. const importNode = result.nodes.find((n) => n.kind === 'import');
  1270. expect(importNode).toBeDefined();
  1271. expect(importNode?.name).toBe('PHPUnit\\Framework\\TestCase');
  1272. });
  1273. it('should extract aliased use', () => {
  1274. const code = `<?php use Mockery as m;`;
  1275. const result = extractFromSource('Test.php', code);
  1276. const importNode = result.nodes.find((n) => n.kind === 'import');
  1277. expect(importNode).toBeDefined();
  1278. expect(importNode?.name).toBe('Mockery');
  1279. expect(importNode?.signature).toContain('as m');
  1280. });
  1281. it('should extract function use', () => {
  1282. const code = `<?php use function Illuminate\\Support\\env;`;
  1283. const result = extractFromSource('helpers.php', code);
  1284. const importNode = result.nodes.find((n) => n.kind === 'import');
  1285. expect(importNode).toBeDefined();
  1286. expect(importNode?.name).toBe('Illuminate\\Support\\env');
  1287. expect(importNode?.signature).toContain('function');
  1288. });
  1289. it('should extract grouped use', () => {
  1290. const code = `<?php use Illuminate\\Database\\{Model, Builder};`;
  1291. const result = extractFromSource('Models.php', code);
  1292. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1293. expect(importNodes.length).toBe(2);
  1294. const names = importNodes.map((n) => n.name);
  1295. expect(names).toContain('Illuminate\\Database\\Model');
  1296. expect(names).toContain('Illuminate\\Database\\Builder');
  1297. });
  1298. it('should extract multiple uses', () => {
  1299. const code = `<?php
  1300. use Illuminate\\Support\\Collection;
  1301. use Illuminate\\Support\\Str;
  1302. use Closure;
  1303. `;
  1304. const result = extractFromSource('Service.php', code);
  1305. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1306. expect(importNodes.length).toBe(3);
  1307. const names = importNodes.map((n) => n.name);
  1308. expect(names).toContain('Illuminate\\Support\\Collection');
  1309. expect(names).toContain('Illuminate\\Support\\Str');
  1310. expect(names).toContain('Closure');
  1311. });
  1312. });
  1313. describe('Ruby imports', () => {
  1314. it('should extract require', () => {
  1315. const code = `require 'json'`;
  1316. const result = extractFromSource('app.rb', code);
  1317. const importNode = result.nodes.find((n) => n.kind === 'import');
  1318. expect(importNode).toBeDefined();
  1319. expect(importNode?.name).toBe('json');
  1320. expect(importNode?.signature).toBe("require 'json'");
  1321. });
  1322. it('should extract require with path', () => {
  1323. const code = `require 'active_support/core_ext/string'`;
  1324. const result = extractFromSource('config.rb', code);
  1325. const importNode = result.nodes.find((n) => n.kind === 'import');
  1326. expect(importNode).toBeDefined();
  1327. expect(importNode?.name).toBe('active_support/core_ext/string');
  1328. });
  1329. it('should extract require_relative', () => {
  1330. const code = `require_relative '../test_helper'`;
  1331. const result = extractFromSource('test/my_test.rb', code);
  1332. const importNode = result.nodes.find((n) => n.kind === 'import');
  1333. expect(importNode).toBeDefined();
  1334. expect(importNode?.name).toBe('../test_helper');
  1335. expect(importNode?.signature).toContain('require_relative');
  1336. });
  1337. it('should not extract non-require calls', () => {
  1338. const code = `puts 'hello'`;
  1339. const result = extractFromSource('app.rb', code);
  1340. const importNode = result.nodes.find((n) => n.kind === 'import');
  1341. expect(importNode).toBeUndefined();
  1342. });
  1343. it('should extract multiple requires', () => {
  1344. const code = `
  1345. require 'json'
  1346. require 'yaml'
  1347. require_relative 'helper'
  1348. `;
  1349. const result = extractFromSource('lib.rb', code);
  1350. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1351. expect(importNodes.length).toBe(3);
  1352. const names = importNodes.map((n) => n.name);
  1353. expect(names).toContain('json');
  1354. expect(names).toContain('yaml');
  1355. expect(names).toContain('helper');
  1356. });
  1357. });
  1358. describe('C/C++ imports', () => {
  1359. it('should extract system include', () => {
  1360. const code = `#include <iostream>`;
  1361. const result = extractFromSource('main.cpp', code);
  1362. const importNode = result.nodes.find((n) => n.kind === 'import');
  1363. expect(importNode).toBeDefined();
  1364. expect(importNode?.name).toBe('iostream');
  1365. expect(importNode?.signature).toBe('#include <iostream>');
  1366. });
  1367. it('should extract system include with path', () => {
  1368. const code = `#include <nlohmann/json.hpp>`;
  1369. const result = extractFromSource('app.cpp', code);
  1370. const importNode = result.nodes.find((n) => n.kind === 'import');
  1371. expect(importNode).toBeDefined();
  1372. expect(importNode?.name).toBe('nlohmann/json.hpp');
  1373. });
  1374. it('should extract local include', () => {
  1375. const code = `#include "myheader.h"`;
  1376. const result = extractFromSource('main.cpp', code);
  1377. const importNode = result.nodes.find((n) => n.kind === 'import');
  1378. expect(importNode).toBeDefined();
  1379. expect(importNode?.name).toBe('myheader.h');
  1380. });
  1381. it('should extract C header', () => {
  1382. const code = `#include <stdio.h>`;
  1383. const result = extractFromSource('main.c', code);
  1384. const importNode = result.nodes.find((n) => n.kind === 'import');
  1385. expect(importNode).toBeDefined();
  1386. expect(importNode?.name).toBe('stdio.h');
  1387. });
  1388. it('should extract multiple includes', () => {
  1389. const code = `
  1390. #include <iostream>
  1391. #include <vector>
  1392. #include "config.h"
  1393. `;
  1394. const result = extractFromSource('app.cpp', code);
  1395. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1396. expect(importNodes.length).toBe(3);
  1397. const names = importNodes.map((n) => n.name);
  1398. expect(names).toContain('iostream');
  1399. expect(names).toContain('vector');
  1400. expect(names).toContain('config.h');
  1401. });
  1402. });
  1403. describe('Dart imports', () => {
  1404. it('should extract dart: import', () => {
  1405. const code = `import 'dart:async';`;
  1406. const result = extractFromSource('main.dart', code);
  1407. const importNode = result.nodes.find((n) => n.kind === 'import');
  1408. expect(importNode).toBeDefined();
  1409. expect(importNode?.name).toBe('dart:async');
  1410. expect(importNode?.signature).toBe("import 'dart:async';");
  1411. });
  1412. it('should extract package import', () => {
  1413. const code = `import 'package:flutter/material.dart';`;
  1414. const result = extractFromSource('app.dart', code);
  1415. const importNode = result.nodes.find((n) => n.kind === 'import');
  1416. expect(importNode).toBeDefined();
  1417. expect(importNode?.name).toBe('package:flutter/material.dart');
  1418. });
  1419. it('should extract aliased import', () => {
  1420. const code = `import 'package:http/http.dart' as http;`;
  1421. const result = extractFromSource('api.dart', code);
  1422. const importNode = result.nodes.find((n) => n.kind === 'import');
  1423. expect(importNode).toBeDefined();
  1424. expect(importNode?.name).toBe('package:http/http.dart');
  1425. expect(importNode?.signature).toContain('as http');
  1426. });
  1427. it('should extract multiple imports', () => {
  1428. const code = `
  1429. import 'dart:async';
  1430. import 'dart:convert';
  1431. import 'package:flutter/material.dart';
  1432. `;
  1433. const result = extractFromSource('main.dart', code);
  1434. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1435. expect(importNodes.length).toBe(3);
  1436. const names = importNodes.map((n) => n.name);
  1437. expect(names).toContain('dart:async');
  1438. expect(names).toContain('dart:convert');
  1439. expect(names).toContain('package:flutter/material.dart');
  1440. });
  1441. it('should extract relative import', () => {
  1442. const code = `import '../utils/helpers.dart';`;
  1443. const result = extractFromSource('lib/main.dart', code);
  1444. const importNode = result.nodes.find((n) => n.kind === 'import');
  1445. expect(importNode).toBeDefined();
  1446. expect(importNode?.name).toBe('../utils/helpers.dart');
  1447. });
  1448. });
  1449. describe('Liquid imports', () => {
  1450. it('should extract render tag', () => {
  1451. const code = `{% render 'loading-spinner' %}`;
  1452. const result = extractFromSource('template.liquid', code);
  1453. const importNode = result.nodes.find((n) => n.kind === 'import');
  1454. expect(importNode).toBeDefined();
  1455. expect(importNode?.name).toBe('loading-spinner');
  1456. expect(importNode?.signature).toContain('render');
  1457. });
  1458. it('should extract section tag', () => {
  1459. const code = `{% section 'header' %}`;
  1460. const result = extractFromSource('layout/theme.liquid', code);
  1461. const importNode = result.nodes.find((n) => n.kind === 'import');
  1462. expect(importNode).toBeDefined();
  1463. expect(importNode?.name).toBe('header');
  1464. expect(importNode?.signature).toContain('section');
  1465. });
  1466. it('should extract include tag', () => {
  1467. const code = `{% include 'icon-cart' %}`;
  1468. const result = extractFromSource('snippets/header.liquid', code);
  1469. const importNode = result.nodes.find((n) => n.kind === 'import');
  1470. expect(importNode).toBeDefined();
  1471. expect(importNode?.name).toBe('icon-cart');
  1472. expect(importNode?.signature).toContain('include');
  1473. });
  1474. it('should extract render with whitespace control', () => {
  1475. const code = `{%- render 'price' -%}`;
  1476. const result = extractFromSource('snippets/product.liquid', code);
  1477. const importNode = result.nodes.find((n) => n.kind === 'import');
  1478. expect(importNode).toBeDefined();
  1479. expect(importNode?.name).toBe('price');
  1480. });
  1481. it('should extract multiple imports', () => {
  1482. const code = `
  1483. {% section 'header' %}
  1484. {% render 'loading-spinner' %}
  1485. {% render 'cart-drawer' %}
  1486. `;
  1487. const result = extractFromSource('layout/theme.liquid', code);
  1488. const importNodes = result.nodes.filter((n) => n.kind === 'import');
  1489. expect(importNodes.length).toBe(3);
  1490. const names = importNodes.map((n) => n.name);
  1491. expect(names).toContain('header');
  1492. expect(names).toContain('loading-spinner');
  1493. expect(names).toContain('cart-drawer');
  1494. });
  1495. });
  1496. });
  1497. describe('Full Indexing', () => {
  1498. let tempDir: string;
  1499. beforeEach(() => {
  1500. tempDir = createTempDir();
  1501. });
  1502. afterEach(() => {
  1503. cleanupTempDir(tempDir);
  1504. });
  1505. it('should index a TypeScript file', async () => {
  1506. // Create test file
  1507. const srcDir = path.join(tempDir, 'src');
  1508. fs.mkdirSync(srcDir);
  1509. fs.writeFileSync(
  1510. path.join(srcDir, 'utils.ts'),
  1511. `
  1512. export function add(a: number, b: number): number {
  1513. return a + b;
  1514. }
  1515. export function multiply(a: number, b: number): number {
  1516. return a * b;
  1517. }
  1518. `
  1519. );
  1520. // Initialize and index
  1521. const cg = CodeGraph.initSync(tempDir);
  1522. const result = await cg.indexAll();
  1523. expect(result.success).toBe(true);
  1524. expect(result.filesIndexed).toBe(1);
  1525. expect(result.nodesCreated).toBeGreaterThanOrEqual(2);
  1526. // Check nodes were stored
  1527. const nodes = cg.getNodesInFile('src/utils.ts');
  1528. expect(nodes.length).toBeGreaterThanOrEqual(2);
  1529. const addFunc = nodes.find((n) => n.name === 'add');
  1530. expect(addFunc).toBeDefined();
  1531. expect(addFunc?.kind).toBe('function');
  1532. cg.close();
  1533. });
  1534. it('should index multiple files', async () => {
  1535. // Create test files
  1536. const srcDir = path.join(tempDir, 'src');
  1537. fs.mkdirSync(srcDir);
  1538. fs.writeFileSync(
  1539. path.join(srcDir, 'math.ts'),
  1540. `export function add(a: number, b: number) { return a + b; }`
  1541. );
  1542. fs.writeFileSync(
  1543. path.join(srcDir, 'string.ts'),
  1544. `export function capitalize(s: string) { return s.toUpperCase(); }`
  1545. );
  1546. // Initialize and index
  1547. const cg = CodeGraph.initSync(tempDir);
  1548. const result = await cg.indexAll();
  1549. expect(result.success).toBe(true);
  1550. expect(result.filesIndexed).toBe(2);
  1551. const files = cg.getFiles();
  1552. expect(files.length).toBe(2);
  1553. cg.close();
  1554. });
  1555. it('should track file hashes for incremental updates', async () => {
  1556. // Create initial file
  1557. const srcDir = path.join(tempDir, 'src');
  1558. fs.mkdirSync(srcDir);
  1559. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 1;`);
  1560. // Initialize and index
  1561. const cg = CodeGraph.initSync(tempDir);
  1562. await cg.indexAll();
  1563. // Check file is tracked
  1564. const file = cg.getFile('src/main.ts');
  1565. expect(file).toBeDefined();
  1566. expect(file?.contentHash).toBeDefined();
  1567. // Modify file
  1568. fs.writeFileSync(path.join(srcDir, 'main.ts'), `export const x = 2;`);
  1569. // Check for changes
  1570. const changes = cg.getChangedFiles();
  1571. expect(changes.modified).toContain('src/main.ts');
  1572. cg.close();
  1573. });
  1574. it('should sync and detect changes', async () => {
  1575. // Create initial file
  1576. const srcDir = path.join(tempDir, 'src');
  1577. fs.mkdirSync(srcDir);
  1578. fs.writeFileSync(
  1579. path.join(srcDir, 'main.ts'),
  1580. `export function original() { return 1; }`
  1581. );
  1582. // Initialize and index
  1583. const cg = CodeGraph.initSync(tempDir);
  1584. await cg.indexAll();
  1585. const initialNodes = cg.getNodesInFile('src/main.ts');
  1586. expect(initialNodes.some((n) => n.name === 'original')).toBe(true);
  1587. // Modify file
  1588. fs.writeFileSync(
  1589. path.join(srcDir, 'main.ts'),
  1590. `export function updated() { return 2; }`
  1591. );
  1592. // Sync
  1593. const syncResult = await cg.sync();
  1594. expect(syncResult.filesModified).toBe(1);
  1595. // Check nodes were updated
  1596. const updatedNodes = cg.getNodesInFile('src/main.ts');
  1597. expect(updatedNodes.some((n) => n.name === 'updated')).toBe(true);
  1598. expect(updatedNodes.some((n) => n.name === 'original')).toBe(false);
  1599. cg.close();
  1600. });
  1601. });
  1602. describe('Path Normalization', () => {
  1603. it('should convert backslashes to forward slashes', () => {
  1604. expect(normalizePath('gui\\node_modules\\foo')).toBe('gui/node_modules/foo');
  1605. expect(normalizePath('src\\components\\Button.tsx')).toBe('src/components/Button.tsx');
  1606. });
  1607. it('should leave forward-slash paths unchanged', () => {
  1608. expect(normalizePath('src/components/Button.tsx')).toBe('src/components/Button.tsx');
  1609. });
  1610. it('should handle empty string', () => {
  1611. expect(normalizePath('')).toBe('');
  1612. });
  1613. });
  1614. describe('Directory Exclusion', () => {
  1615. let tempDir: string;
  1616. beforeEach(() => {
  1617. tempDir = createTempDir();
  1618. });
  1619. afterEach(() => {
  1620. cleanupTempDir(tempDir);
  1621. });
  1622. it('should exclude node_modules directories', () => {
  1623. // Create structure: src/index.ts + node_modules/pkg/index.js
  1624. const srcDir = path.join(tempDir, 'src');
  1625. const nmDir = path.join(tempDir, 'node_modules', 'pkg');
  1626. fs.mkdirSync(srcDir, { recursive: true });
  1627. fs.mkdirSync(nmDir, { recursive: true });
  1628. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  1629. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  1630. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1631. const files = scanDirectory(tempDir, config);
  1632. expect(files).toContain('src/index.ts');
  1633. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  1634. });
  1635. it('should exclude nested node_modules directories', () => {
  1636. // Create structure: packages/app/node_modules/pkg/index.js
  1637. const srcDir = path.join(tempDir, 'packages', 'app', 'src');
  1638. const nmDir = path.join(tempDir, 'packages', 'app', 'node_modules', 'pkg');
  1639. fs.mkdirSync(srcDir, { recursive: true });
  1640. fs.mkdirSync(nmDir, { recursive: true });
  1641. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  1642. fs.writeFileSync(path.join(nmDir, 'index.js'), 'module.exports = {};');
  1643. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1644. const files = scanDirectory(tempDir, config);
  1645. expect(files).toContain('packages/app/src/index.ts');
  1646. expect(files.every((f) => !f.includes('node_modules'))).toBe(true);
  1647. });
  1648. it('should exclude .git directories', () => {
  1649. const srcDir = path.join(tempDir, 'src');
  1650. const gitDir = path.join(tempDir, '.git', 'objects');
  1651. fs.mkdirSync(srcDir, { recursive: true });
  1652. fs.mkdirSync(gitDir, { recursive: true });
  1653. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  1654. fs.writeFileSync(path.join(gitDir, 'pack.ts'), 'export const y = 2;');
  1655. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1656. const files = scanDirectory(tempDir, config);
  1657. expect(files).toContain('src/index.ts');
  1658. expect(files.every((f) => !f.includes('.git'))).toBe(true);
  1659. });
  1660. it('should return forward-slash paths on all platforms', () => {
  1661. const srcDir = path.join(tempDir, 'src', 'components');
  1662. fs.mkdirSync(srcDir, { recursive: true });
  1663. fs.writeFileSync(path.join(srcDir, 'Button.tsx'), 'export function Button() {}');
  1664. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1665. const files = scanDirectory(tempDir, config);
  1666. expect(files.length).toBe(1);
  1667. expect(files[0]).toBe('src/components/Button.tsx');
  1668. expect(files[0]).not.toContain('\\');
  1669. });
  1670. it('should respect .codegraphignore marker', () => {
  1671. const srcDir = path.join(tempDir, 'src');
  1672. const vendorDir = path.join(tempDir, 'vendor');
  1673. fs.mkdirSync(srcDir, { recursive: true });
  1674. fs.mkdirSync(vendorDir, { recursive: true });
  1675. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  1676. fs.writeFileSync(path.join(vendorDir, 'lib.ts'), 'export const y = 2;');
  1677. fs.writeFileSync(path.join(vendorDir, '.codegraphignore'), '');
  1678. const config = { ...DEFAULT_CONFIG, rootDir: tempDir };
  1679. const files = scanDirectory(tempDir, config);
  1680. expect(files).toContain('src/index.ts');
  1681. expect(files.every((f) => !f.includes('vendor'))).toBe(true);
  1682. });
  1683. });