1
0

extraction.test.ts 64 KB

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