frameworks-integration.test.ts 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. import { describe, it, expect, beforeAll, afterEach } from 'vitest';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import * as os from 'os';
  5. import { CodeGraph } from '../src';
  6. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  7. beforeAll(async () => {
  8. await initGrammars();
  9. await loadAllGrammars();
  10. });
  11. describe('Django end-to-end framework extraction', () => {
  12. let tmpDir: string | undefined;
  13. afterEach(() => {
  14. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  15. tmpDir = undefined;
  16. });
  17. it('creates a route->view edge from urls.py to view class', async () => {
  18. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-django-'));
  19. fs.writeFileSync(path.join(tmpDir, 'manage.py'), '# marker\n');
  20. fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'django==4.2\n');
  21. fs.mkdirSync(path.join(tmpDir, 'users'));
  22. fs.writeFileSync(path.join(tmpDir, 'users/__init__.py'), '');
  23. fs.writeFileSync(
  24. path.join(tmpDir, 'users/views.py'),
  25. 'class UserListView:\n def get(self, request): pass\n'
  26. );
  27. fs.writeFileSync(
  28. path.join(tmpDir, 'users/urls.py'),
  29. 'from django.urls import path\n' +
  30. 'from users.views import UserListView\n' +
  31. 'urlpatterns = [path("users/", UserListView.as_view(), name="user-list")]\n'
  32. );
  33. const cg = CodeGraph.initSync(tmpDir);
  34. await cg.indexAll();
  35. // Route node exists
  36. const routes = cg.getNodesByKind('route');
  37. expect(routes.length).toBeGreaterThan(0);
  38. const route = routes.find((n) => n.name === 'users/');
  39. expect(route).toBeDefined();
  40. // View class exists
  41. const classNodes = cg.getNodesByKind('class');
  42. const view = classNodes.find((n) => n.name === 'UserListView');
  43. expect(view).toBeDefined();
  44. // Edge route -> view exists
  45. const edges = cg.getOutgoingEdges(route!.id);
  46. const toView = edges.find((e) => e.target === view!.id);
  47. expect(toView).toBeDefined();
  48. expect(toView!.kind).toBe('references');
  49. cg.close();
  50. });
  51. });
  52. describe('Flask end-to-end framework extraction', () => {
  53. let tmpDir: string | undefined;
  54. afterEach(() => {
  55. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  56. tmpDir = undefined;
  57. });
  58. it('resolves stacked routes across @login_required to a view named after a builtin (index)', async () => {
  59. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-flask-'));
  60. fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'flask==3.0\n');
  61. fs.writeFileSync(
  62. path.join(tmpDir, 'app.py'),
  63. 'from flask import Blueprint, render_template\n' +
  64. 'from flask_login import login_required\n' +
  65. 'bp = Blueprint("main", __name__)\n' +
  66. '\n' +
  67. '@bp.route("/", methods=["GET", "POST"])\n' +
  68. '@bp.route("/index", methods=["GET", "POST"])\n' +
  69. '@login_required\n' +
  70. 'def index():\n' +
  71. ' return render_template("index.html")\n'
  72. );
  73. const cg = CodeGraph.initSync(tmpDir);
  74. await cg.indexAll();
  75. // Both stacked @bp.route decorators are extracted (the second was previously
  76. // dropped because @login_required broke the "def must follow" assumption).
  77. const routes = cg.getNodesByKind('route');
  78. expect(routes.map((r) => r.name).sort()).toEqual(['GET /', 'GET /index']);
  79. // The view function exists even though its name is a Python builtin method.
  80. const fn = cg.getNodesByKind('function').find((n) => n.name === 'index');
  81. expect(fn).toBeDefined();
  82. // Both routes resolve to it — exercises the bare-name builtin guard, which
  83. // previously filtered the `index` reference as a builtin method.
  84. for (const route of routes) {
  85. const edges = cg.getOutgoingEdges(route.id);
  86. const toView = edges.find((e) => e.target === fn!.id && e.kind === 'references');
  87. expect(toView, `route ${route.name} should resolve to index()`).toBeDefined();
  88. }
  89. cg.close();
  90. });
  91. });
  92. describe('Flutter end-to-end — setState→build synthesis', () => {
  93. let tmpDir: string | undefined;
  94. afterEach(() => {
  95. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  96. tmpDir = undefined;
  97. });
  98. it('synthesizes a handler→build edge when a State method calls setState', async () => {
  99. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-flutter-'));
  100. fs.writeFileSync(
  101. path.join(tmpDir, 'main.dart'),
  102. 'import "package:flutter/material.dart";\n' +
  103. 'class CounterPage extends StatefulWidget {\n' +
  104. ' @override\n' +
  105. ' State<CounterPage> createState() => _CounterPageState();\n' +
  106. '}\n' +
  107. 'class _CounterPageState extends State<CounterPage> {\n' +
  108. ' int _count = 0;\n' +
  109. ' void _increment() {\n' +
  110. ' setState(() {\n' +
  111. ' _count++;\n' +
  112. ' });\n' +
  113. ' }\n' +
  114. ' @override\n' +
  115. ' Widget build(BuildContext context) {\n' +
  116. ' return Text("$_count");\n' +
  117. ' }\n' +
  118. '}\n'
  119. );
  120. const cg = CodeGraph.initSync(tmpDir);
  121. await cg.indexAll();
  122. const methods = cg.getNodesByKind('method');
  123. const increment = methods.find((n) => n.name === '_increment');
  124. const build = methods.find((n) => n.name === 'build');
  125. expect(increment).toBeDefined();
  126. expect(build).toBeDefined();
  127. // setState re-runs build (Flutter-internal, no static edge). The synthesizer
  128. // bridges the handler → build so the "tap → setState → rebuilt UI" flow connects.
  129. const edges = cg.getOutgoingEdges(increment!.id);
  130. const toBuild = edges.find((e) => e.target === build!.id && e.kind === 'calls');
  131. expect(toBuild, '_increment should reach build via setState synthesis').toBeDefined();
  132. cg.close();
  133. });
  134. });
  135. describe('C++ end-to-end — virtual override synthesis', () => {
  136. let tmpDir: string | undefined;
  137. afterEach(() => {
  138. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  139. tmpDir = undefined;
  140. });
  141. it('resolves callers through typed object pointers', async () => {
  142. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  143. let cg: CodeGraph | undefined;
  144. try {
  145. fs.writeFileSync(
  146. path.join(tmpDir, 'detect.hpp'),
  147. 'class CDetect {\n' +
  148. ' public:\n' +
  149. ' int Processing();\n' +
  150. '};\n' +
  151. 'class CDetector {\n' +
  152. ' private:\n' +
  153. ' CDetect* m_cpAlg = nullptr;\n' +
  154. ' public:\n' +
  155. ' int Run();\n' +
  156. ' int Flush();\n' +
  157. '};\n'
  158. );
  159. fs.writeFileSync(
  160. path.join(tmpDir, 'detect.cpp'),
  161. '#include "detect.hpp"\n' +
  162. 'int CDetector::Run() { return m_cpAlg->Processing(); }\n' +
  163. 'int CDetector::Flush() { return m_cpAlg->Processing(); }\n' +
  164. 'int CDetect::Processing() { return 0; }\n'
  165. );
  166. cg = CodeGraph.initSync(tmpDir);
  167. await cg.indexAll();
  168. const processing = cg
  169. .getNodesByKind('method')
  170. .find((n) => n.qualifiedName.endsWith('CDetect::Processing'));
  171. expect(processing).toBeDefined();
  172. const callers = cg.getCallers(processing!.id).map((c) => c.node.qualifiedName);
  173. expect(callers).toContain('CDetector::Run');
  174. expect(callers).toContain('CDetector::Flush');
  175. const runMethod = cg
  176. .getNodesByKind('method')
  177. .find((n) => n.qualifiedName.endsWith('CDetector::Run'));
  178. expect(runMethod).toBeDefined();
  179. const callees = cg.getCallees(runMethod!.id).map((c) => c.node.qualifiedName);
  180. expect(callees).toContain('CDetect::Processing');
  181. } finally {
  182. cg?.close();
  183. }
  184. });
  185. it('resolves typed pointer callers when the method name is ambiguous and the call sits inside a return/declaration', async () => {
  186. // Regression: an earlier version of the C++ receiver-type inference matched
  187. // the call line itself (`return m_cpAlg->Processing()`) and treated `return`
  188. // as the type, OR grabbed `int r =` as a type from the prefix. With Strategy
  189. // 3's "unique method name" fallback, the original issue example resolved
  190. // anyway — but as soon as two classes share a method name (very common in
  191. // real C++), both calls go unresolved.
  192. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  193. let cg: CodeGraph | undefined;
  194. try {
  195. fs.writeFileSync(
  196. path.join(tmpDir, 'detect.hpp'),
  197. 'class CDetect { public: int Processing(); };\n' +
  198. 'class CWidget { public: int Processing(); };\n' +
  199. 'class CDetector {\n' +
  200. ' private:\n' +
  201. ' CDetect* m_cpAlg = nullptr;\n' +
  202. ' public:\n' +
  203. ' int RunReturn();\n' +
  204. ' int RunAssign();\n' +
  205. '};\n'
  206. );
  207. fs.writeFileSync(
  208. path.join(tmpDir, 'detect.cpp'),
  209. '#include "detect.hpp"\n' +
  210. 'int CDetector::RunReturn() { return m_cpAlg->Processing(); }\n' +
  211. 'int CDetector::RunAssign() { int r = m_cpAlg->Processing(); return r; }\n' +
  212. 'int CDetect::Processing() { return 0; }\n' +
  213. 'int CWidget::Processing() { return 0; }\n'
  214. );
  215. cg = CodeGraph.initSync(tmpDir);
  216. await cg.indexAll();
  217. const detectProc = cg
  218. .getNodesByKind('method')
  219. .find((n) => n.qualifiedName === 'CDetect::Processing');
  220. const widgetProc = cg
  221. .getNodesByKind('method')
  222. .find((n) => n.qualifiedName === 'CWidget::Processing');
  223. expect(detectProc).toBeDefined();
  224. expect(widgetProc).toBeDefined();
  225. const detectCallers = cg.getCallers(detectProc!.id).map((c) => c.node.qualifiedName);
  226. expect(detectCallers).toContain('CDetector::RunReturn');
  227. expect(detectCallers).toContain('CDetector::RunAssign');
  228. // CWidget::Processing is never called — calls must NOT misroute here.
  229. const widgetCallers = cg.getCallers(widgetProc!.id).map((c) => c.node.qualifiedName);
  230. expect(widgetCallers).not.toContain('CDetector::RunReturn');
  231. expect(widgetCallers).not.toContain('CDetector::RunAssign');
  232. } finally {
  233. cg?.close();
  234. }
  235. });
  236. it('bridges a base virtual method to the subclass override', async () => {
  237. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  238. fs.writeFileSync(
  239. path.join(tmpDir, 'iter.cpp'),
  240. 'class Iterator {\n' +
  241. ' public:\n' +
  242. ' virtual void Next() { }\n' +
  243. '};\n' +
  244. 'class DBIter : public Iterator {\n' +
  245. ' public:\n' +
  246. ' void Next() override { advance(); }\n' +
  247. ' void advance() { }\n' +
  248. '};\n'
  249. );
  250. const cg = CodeGraph.initSync(tmpDir);
  251. await cg.indexAll();
  252. // Two methods named Next: the base virtual (lower line) and the override.
  253. const nexts = cg
  254. .getNodesByKind('method')
  255. .filter((n) => n.name === 'Next')
  256. .sort((a, b) => a.startLine - b.startLine);
  257. expect(nexts.length).toBe(2);
  258. const [baseNext, overrideNext] = nexts;
  259. // A vtable call to Iterator::Next dispatches to DBIter::Next — bridge it so
  260. // trace/callees from the interface method reaches the implementation.
  261. const edge = cg
  262. .getOutgoingEdges(baseNext!.id)
  263. .find((e) => e.target === overrideNext!.id && e.kind === 'calls');
  264. expect(edge, 'Iterator::Next should reach DBIter::Next via override synthesis').toBeDefined();
  265. cg.close();
  266. });
  267. });
  268. describe('Java end-to-end — field-injected bean trace (issue #389)', () => {
  269. let tmpDir: string | undefined;
  270. afterEach(() => {
  271. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  272. tmpDir = undefined;
  273. });
  274. // Mirrors the issue's Spring MVC pattern:
  275. // UserAction(@Resource UserBO userbo).toLogin2() -> this.userbo.toLogin2()
  276. // -> UserBO.toLogin2() -> userService.toLogin() -> UserService.toLogin (iface)
  277. // -> UserServiceImpl.toLogin() via interface→impl synthesis.
  278. // Without the extractor `this.` strip + field-typed receiver lookup, the very
  279. // first hop (controller -> bean) was missing entirely, breaking trace.
  280. it('connects controller -> @Resource bean -> interface -> impl end-to-end', async () => {
  281. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-bean-'));
  282. const javaDir = path.join(tmpDir, 'src/main/java/com/example/user');
  283. fs.mkdirSync(path.join(javaDir, 'action'), { recursive: true });
  284. fs.mkdirSync(path.join(javaDir, 'bo'), { recursive: true });
  285. fs.mkdirSync(path.join(javaDir, 'service'), { recursive: true });
  286. fs.mkdirSync(path.join(javaDir, 'service/impl'), { recursive: true });
  287. fs.writeFileSync(
  288. path.join(tmpDir, 'pom.xml'),
  289. '<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies></project>\n'
  290. );
  291. fs.writeFileSync(
  292. path.join(javaDir, 'action/UserAction.java'),
  293. 'package com.example.user.action;\n' +
  294. 'import com.example.user.bo.UserBO;\n' +
  295. 'import javax.annotation.Resource;\n' +
  296. '@org.springframework.stereotype.Controller\n' +
  297. 'public class UserAction {\n' +
  298. ' @Resource(name = "userBO") private UserBO userbo;\n' +
  299. ' public void toLogin2() { this.userbo.toLogin2(); }\n' +
  300. '}\n'
  301. );
  302. fs.writeFileSync(
  303. path.join(javaDir, 'bo/UserBO.java'),
  304. 'package com.example.user.bo;\n' +
  305. 'import com.example.user.service.UserService;\n' +
  306. 'import javax.annotation.Resource;\n' +
  307. '@org.springframework.stereotype.Component("userBO")\n' +
  308. 'public class UserBO {\n' +
  309. ' @Resource private UserService userService;\n' +
  310. ' public void toLogin2() { userService.toLogin(); }\n' +
  311. '}\n'
  312. );
  313. fs.writeFileSync(
  314. path.join(javaDir, 'service/UserService.java'),
  315. 'package com.example.user.service;\n' +
  316. 'public interface UserService { void toLogin(); }\n'
  317. );
  318. fs.writeFileSync(
  319. path.join(javaDir, 'service/impl/UserServiceImpl.java'),
  320. 'package com.example.user.service.impl;\n' +
  321. 'import com.example.user.service.UserService;\n' +
  322. '@org.springframework.stereotype.Service("userService")\n' +
  323. 'public class UserServiceImpl implements UserService {\n' +
  324. ' public void toLogin() { }\n' +
  325. '}\n'
  326. );
  327. const cg = CodeGraph.initSync(tmpDir);
  328. await cg.indexAll();
  329. const methods = cg.getNodesByKind('method');
  330. const find = (cls: string, name: string) =>
  331. methods.find((m) => m.name === name && m.filePath.endsWith(`${cls}.java`));
  332. const action = find('UserAction', 'toLogin2');
  333. const bo = find('UserBO', 'toLogin2');
  334. const svc = find('UserService', 'toLogin');
  335. const impl = find('UserServiceImpl', 'toLogin');
  336. expect(action).toBeDefined();
  337. expect(bo).toBeDefined();
  338. expect(svc).toBeDefined();
  339. expect(impl).toBeDefined();
  340. // UserAction.toLogin2 -> UserBO.toLogin2 (the regressed hop — `this.userbo`
  341. // receiver was emitted verbatim and the field-type lookup didn't exist).
  342. const actionToBo = cg.getOutgoingEdges(action!.id).find((e) => e.target === bo!.id);
  343. expect(actionToBo, 'controller `this.userbo.toLogin2()` should reach UserBO.toLogin2').toBeDefined();
  344. expect(actionToBo!.kind).toBe('calls');
  345. // UserBO.toLogin2 -> UserService.toLogin (plain identifier receiver, works pre-fix).
  346. const boToSvc = cg.getOutgoingEdges(bo!.id).find((e) => e.target === svc!.id);
  347. expect(boToSvc).toBeDefined();
  348. // UserService.toLogin -> UserServiceImpl.toLogin (interface->impl synth).
  349. const svcToImpl = cg.getOutgoingEdges(svc!.id).find((e) => e.target === impl!.id);
  350. expect(svcToImpl).toBeDefined();
  351. cg.close();
  352. });
  353. it('bridges a Java mapper interface method to its MyBatis XML statement (incl. SQL fragments)', async () => {
  354. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-mybatis-'));
  355. const javaDir = path.join(tmpDir, 'src/main/java/com/example/dao');
  356. const xmlDir = path.join(tmpDir, 'src/main/resources/mappers');
  357. fs.mkdirSync(javaDir, { recursive: true });
  358. fs.mkdirSync(xmlDir, { recursive: true });
  359. fs.writeFileSync(
  360. path.join(tmpDir, 'pom.xml'),
  361. '<project><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId></dependency></dependencies></project>\n'
  362. );
  363. fs.writeFileSync(
  364. path.join(javaDir, 'UserDAOMapper.java'),
  365. 'package com.example.dao;\n' +
  366. 'public interface UserDAOMapper {\n' +
  367. ' Object getById(int id);\n' +
  368. ' int updateUser(Object u);\n' +
  369. '}\n'
  370. );
  371. fs.writeFileSync(
  372. path.join(xmlDir, 'UserDAOMapper.xml'),
  373. '<?xml version="1.0" encoding="UTF-8"?>\n' +
  374. '<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">\n' +
  375. '<mapper namespace="com.example.dao.UserDAOMapper">\n' +
  376. ' <sql id="userCols">id, name, email</sql>\n' +
  377. ' <select id="getById" parameterType="int" resultType="User">\n' +
  378. ' SELECT <include refid="userCols"/> FROM users WHERE id = #{id}\n' +
  379. ' </select>\n' +
  380. ' <update id="updateUser" parameterType="User">\n' +
  381. ' UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}\n' +
  382. ' </update>\n' +
  383. '</mapper>\n'
  384. );
  385. const cg = CodeGraph.initSync(tmpDir);
  386. await cg.indexAll();
  387. const methods = cg.getNodesByKind('method');
  388. const getByIdJava = methods.find((m) => m.name === 'getById' && m.language === 'java');
  389. const getByIdXml = methods.find((m) => m.name === 'getById' && m.language === 'xml');
  390. const updateJava = methods.find((m) => m.name === 'updateUser' && m.language === 'java');
  391. const updateXml = methods.find((m) => m.name === 'updateUser' && m.language === 'xml');
  392. const sqlFrag = methods.find((m) => m.name === 'userCols' && m.language === 'xml');
  393. expect(getByIdJava).toBeDefined();
  394. expect(getByIdXml).toBeDefined();
  395. expect(updateJava).toBeDefined();
  396. expect(updateXml).toBeDefined();
  397. expect(sqlFrag).toBeDefined();
  398. // XML statement qualified name must be `<namespace>::<id>` so the
  399. // synthesizer can match against the Java method's `<Class>::<method>`
  400. // suffix — this is the load-bearing contract between extractor + synthesis.
  401. expect(getByIdXml!.qualifiedName).toBe('com.example.dao.UserDAOMapper::getById');
  402. // Bridge: Java mapper method -> XML statement, kind 'calls'.
  403. const j2xGet = cg.getOutgoingEdges(getByIdJava!.id).find((e) => e.target === getByIdXml!.id);
  404. expect(j2xGet, 'Java getById should reach the XML <select id="getById">').toBeDefined();
  405. expect(j2xGet!.kind).toBe('calls');
  406. const j2xUpd = cg.getOutgoingEdges(updateJava!.id).find((e) => e.target === updateXml!.id);
  407. expect(j2xUpd, 'Java updateUser should reach the XML <update id="updateUser">').toBeDefined();
  408. // <include refid="userCols"/> inside <select> -> <sql id="userCols"> in same mapper.
  409. const incEdge = cg.getOutgoingEdges(getByIdXml!.id).find((e) => e.target === sqlFrag!.id);
  410. expect(incEdge, '<include refid="userCols"/> should reach the <sql> fragment').toBeDefined();
  411. cg.close();
  412. });
  413. it('covers legacy iBatis <sqlMap> statements and keeps same-line vendor-split pairs (#1182)', async () => {
  414. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-ibatis-'));
  415. const xmlDir = path.join(tmpDir, 'src/main/resources/sqlmaps');
  416. fs.mkdirSync(xmlDir, { recursive: true });
  417. // iBatis 2 sqlMap with an explicit namespace.
  418. fs.writeFileSync(
  419. path.join(xmlDir, 'Account.xml'),
  420. '<?xml version="1.0" encoding="UTF-8"?>\n' +
  421. '<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">\n' +
  422. "<sqlMap namespace='Account'>\n" +
  423. " <sql id='cols'>id, name, email</sql>\n" +
  424. " <select id='getById' resultClass='Account'>SELECT <include refid='cols'/> FROM account WHERE id = #id#</select>\n" +
  425. " <insert id='insert' parameterClass='Account'>INSERT INTO account (id) VALUES (#id#)</insert>\n" +
  426. ' <!-- <select id="disabled">SELECT 0</select> -->\n' +
  427. '</sqlMap>\n'
  428. );
  429. // Namespace-less sqlMap whose ids carry the qualifier as `Map.statement`.
  430. fs.writeFileSync(
  431. path.join(xmlDir, 'LegacyDao.xml'),
  432. '<sqlMap>\n' +
  433. ' <select id="LegacyDao.findAll" resultClass="Row">SELECT * FROM t</select>\n' +
  434. '</sqlMap>\n'
  435. );
  436. // MyBatis mapper with a vendor-split databaseId pair written on ONE line —
  437. // same qualifiedName + same start line. Before the id-hash fold both nodes
  438. // hashed identically and INSERT OR REPLACE dropped one.
  439. fs.writeFileSync(
  440. path.join(xmlDir, 'VendorMapper.xml'),
  441. '<mapper namespace="com.example.VendorMapper">\n' +
  442. '<select id="findUser" databaseId="oracle">SELECT 1 FROM dual</select><select id="findUser" databaseId="mysql">SELECT 1</select>\n' +
  443. '</mapper>\n'
  444. );
  445. const cg = CodeGraph.initSync(tmpDir);
  446. await cg.indexAll();
  447. const xmlMethods = cg.getNodesByKind('method').filter((n) => n.language === 'xml');
  448. const qnames = xmlMethods.map((n) => n.qualifiedName);
  449. // iBatis statements now land in the graph (was zero coverage before #1182).
  450. expect(qnames).toContain('Account::getById');
  451. expect(qnames).toContain('Account::insert');
  452. expect(qnames).toContain('Account::cols');
  453. expect(qnames).toContain('LegacyDao::findAll');
  454. // The commented-out statement produced no node.
  455. expect(qnames).not.toContain('Account::disabled');
  456. // <include refid='cols'/> resolves to the <sql> fragment in the same map.
  457. const getById = xmlMethods.find((n) => n.qualifiedName === 'Account::getById');
  458. const cols = xmlMethods.find((n) => n.qualifiedName === 'Account::cols');
  459. expect(getById).toBeDefined();
  460. expect(cols).toBeDefined();
  461. const incEdge = cg.getOutgoingEdges(getById!.id).find((e) => e.target === cols!.id);
  462. expect(incEdge, "iBatis <include refid='cols'/> should reach the <sql> fragment").toBeDefined();
  463. // Both vendor-split statements survive the DB write (the collision fix).
  464. const findUser = xmlMethods.filter((n) => n.name === 'findUser');
  465. expect(findUser, 'both databaseId variants of findUser should survive').toHaveLength(2);
  466. expect(new Set(findUser.map((n) => n.id)).size).toBe(2);
  467. cg.close();
  468. });
  469. it('binds @Value / @ConfigurationProperties to YAML + .properties keys (incl. relaxed binding)', async () => {
  470. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-config-'));
  471. const javaDir = path.join(tmpDir, 'src/main/java/com/example');
  472. const resDir = path.join(tmpDir, 'src/main/resources');
  473. fs.mkdirSync(javaDir, { recursive: true });
  474. fs.mkdirSync(resDir, { recursive: true });
  475. fs.writeFileSync(
  476. path.join(tmpDir, 'pom.xml'),
  477. '<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency></dependencies></project>\n'
  478. );
  479. fs.writeFileSync(
  480. path.join(resDir, 'application.yml'),
  481. 'app:\n' +
  482. ' cache:\n' +
  483. ' name:\n' +
  484. ' user-token: "example-service:auth:token"\n' +
  485. ' enabled: true\n' +
  486. 'db:\n' +
  487. ' url: "jdbc:mysql://localhost/x"\n'
  488. );
  489. fs.writeFileSync(
  490. path.join(resDir, 'application.properties'),
  491. 'app.retry-count=3\n'
  492. );
  493. fs.writeFileSync(
  494. path.join(javaDir, 'CacheConfig.java'),
  495. 'package com.example;\n' +
  496. 'import org.springframework.beans.factory.annotation.Value;\n' +
  497. 'public class CacheConfig {\n' +
  498. ' @Value("${app.cache.name.user-token}") private String tokenCacheName;\n' +
  499. ' @Value("${app.cache.enabled:true}") private boolean enabled;\n' +
  500. ' // relaxed binding: java camelCase, properties kebab-case\n' +
  501. ' @Value("${app.retryCount}") private int retry;\n' +
  502. '}\n'
  503. );
  504. fs.writeFileSync(
  505. path.join(javaDir, 'CacheProperties.java'),
  506. 'package com.example;\n' +
  507. 'import org.springframework.boot.context.properties.ConfigurationProperties;\n' +
  508. '@ConfigurationProperties(prefix = "app.cache")\n' +
  509. 'public class CacheProperties { private boolean enabled; }\n'
  510. );
  511. const cg = CodeGraph.initSync(tmpDir);
  512. await cg.indexAll();
  513. // YAML/properties leaf keys: one constant node per dotted path.
  514. const cfgKeys = cg
  515. .getNodesByKind('constant')
  516. .filter((n) => n.language === 'yaml' || n.language === 'properties');
  517. const cfgByQn = (qn: string) => cfgKeys.find((n) => n.qualifiedName === qn);
  518. expect(cfgByQn('app.cache.name.user-token')).toBeDefined();
  519. expect(cfgByQn('app.cache.enabled')).toBeDefined();
  520. expect(cfgByQn('db.url')).toBeDefined();
  521. expect(cfgByQn('app.retry-count')).toBeDefined();
  522. // @Value("${app.cache.name.user-token}") -> the YAML leaf key.
  523. const valueBindings = cg
  524. .getNodesByKind('constant')
  525. .filter((n) => n.id.startsWith('spring-value:'));
  526. const userToken = valueBindings.find((n) => n.name === 'app.cache.name.user-token');
  527. expect(userToken).toBeDefined();
  528. const userTokenEdges = cg.getOutgoingEdges(userToken!.id);
  529. const userTokenTarget = userTokenEdges.find((e) =>
  530. cfgKeys.some((c) => c.id === e.target && c.qualifiedName === 'app.cache.name.user-token'),
  531. );
  532. expect(userTokenTarget, '@Value should reference the YAML leaf key').toBeDefined();
  533. // Default-value form `${k:default}` — strip the `:default` and bind the key.
  534. const enabledBind = valueBindings.find((n) => n.name === 'app.cache.enabled');
  535. expect(enabledBind).toBeDefined();
  536. expect(cg.getOutgoingEdges(enabledBind!.id).some((e) => {
  537. const t = cfgByQn('app.cache.enabled');
  538. return t && e.target === t.id;
  539. })).toBe(true);
  540. // Relaxed binding: `app.retryCount` (camel) -> `app.retry-count` (kebab).
  541. const retryBind = valueBindings.find((n) => n.name === 'app.retryCount');
  542. expect(retryBind).toBeDefined();
  543. expect(cg.getOutgoingEdges(retryBind!.id).some((e) => {
  544. const t = cfgByQn('app.retry-count');
  545. return t && e.target === t.id;
  546. })).toBe(true);
  547. // @ConfigurationProperties(prefix="app.cache") -> a key under that prefix.
  548. const cpBindings = cg
  549. .getNodesByKind('constant')
  550. .filter((n) => n.id.startsWith('spring-cp:'));
  551. const cpAppCache = cpBindings.find((n) => n.name === 'app.cache');
  552. expect(cpAppCache).toBeDefined();
  553. const cpEdges = cg.getOutgoingEdges(cpAppCache!.id);
  554. expect(cpEdges.length).toBeGreaterThan(0);
  555. cg.close();
  556. });
  557. it('emits only a file node for non-MyBatis XML (pom.xml, beans.xml, log4j.xml)', async () => {
  558. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-xml-non-mybatis-'));
  559. fs.writeFileSync(
  560. path.join(tmpDir, 'pom.xml'),
  561. '<project><groupId>x</groupId><artifactId>y</artifactId></project>\n'
  562. );
  563. fs.writeFileSync(
  564. path.join(tmpDir, 'log4j.xml'),
  565. '<?xml version="1.0"?><Configuration><Loggers><Root level="info"/></Loggers></Configuration>\n'
  566. );
  567. const cg = CodeGraph.initSync(tmpDir);
  568. await cg.indexAll();
  569. // No method nodes — non-mapper XML produces no symbols (just file rows).
  570. expect(cg.getNodesByKind('method').filter((n) => n.language === 'xml').length).toBe(0);
  571. cg.close();
  572. });
  573. it('resolves a `this.field.method()` call to a unique implementation class', async () => {
  574. // Standalone test of the extractor `this.` strip: even without Spring annotations,
  575. // `this.svc.run()` where `svc` is typed as a concrete class should route to that
  576. // class's method. This is the general Java fix, Spring is only one consumer.
  577. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-java-this-field-'));
  578. fs.writeFileSync(
  579. path.join(tmpDir, 'App.java'),
  580. 'class Svc { public void run() { } }\n' +
  581. 'class App {\n' +
  582. ' private Svc svc;\n' +
  583. ' public void go() { this.svc.run(); }\n' +
  584. '}\n'
  585. );
  586. const cg = CodeGraph.initSync(tmpDir);
  587. await cg.indexAll();
  588. const methods = cg.getNodesByKind('method');
  589. const go = methods.find((m) => m.name === 'go');
  590. const run = methods.find((m) => m.name === 'run');
  591. expect(go && run).toBeTruthy();
  592. const edge = cg.getOutgoingEdges(go!.id).find((e) => e.target === run!.id);
  593. expect(edge, '`this.svc.run()` should resolve to Svc.run').toBeDefined();
  594. cg.close();
  595. });
  596. });
  597. describe('JVM FQN imports — end-to-end', () => {
  598. let tmpDir: string | undefined;
  599. afterEach(() => {
  600. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  601. tmpDir = undefined;
  602. });
  603. it('resolves a Kotlin import when the file name differs from the class name', async () => {
  604. // Bar lives in Models.kt — the filesystem-based Java-style path lookup
  605. // (com/example/Bar.kt) misses this; only FQN-via-qualifiedName finds it.
  606. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  607. fs.writeFileSync(
  608. path.join(tmpDir, 'Models.kt'),
  609. 'package com.example\n\nclass Bar {\n fun greet(): String = "hi"\n}\n'
  610. );
  611. fs.writeFileSync(
  612. path.join(tmpDir, 'Caller.kt'),
  613. 'package com.example.app\n\nimport com.example.Bar\n\nclass App {\n fun run() { Bar().greet() }\n}\n'
  614. );
  615. const cg = CodeGraph.initSync(tmpDir);
  616. await cg.indexAll();
  617. const bar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example::Bar');
  618. expect(bar, 'Bar should be extracted with package-qualified name').toBeDefined();
  619. const importNode = cg.getNodesByKind('import').find((n) => n.name === 'com.example.Bar');
  620. expect(importNode, 'import statement node should exist').toBeDefined();
  621. // The imports edge may originate from the import node OR from a parent
  622. // scope (file / namespace) — accept either, but require that an
  623. // imports-kind edge to Bar exists.
  624. const reachesBar = cg
  625. .getIncomingEdges(bar!.id)
  626. .find((e) => e.kind === 'imports');
  627. expect(reachesBar, 'an imports edge should resolve to Bar via FQN').toBeDefined();
  628. cg.close();
  629. });
  630. it('resolves a Kotlin top-level function import', async () => {
  631. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  632. fs.writeFileSync(
  633. path.join(tmpDir, 'Utils.kt'),
  634. 'package com.example\n\nfun util(): Int = 42\n'
  635. );
  636. fs.writeFileSync(
  637. path.join(tmpDir, 'Caller.kt'),
  638. 'package com.example.app\n\nimport com.example.util\n\nfun main() { util() }\n'
  639. );
  640. const cg = CodeGraph.initSync(tmpDir);
  641. await cg.indexAll();
  642. const util = cg.getNodesByKind('function').find((n) => n.qualifiedName === 'com.example::util');
  643. expect(util, 'top-level util() should be extracted under com.example').toBeDefined();
  644. const edge = cg.getIncomingEdges(util!.id).find((e) => e.kind === 'imports');
  645. expect(edge, 'imports edge should reach the top-level function by FQN').toBeDefined();
  646. });
  647. it('resolves cross-language: Kotlin importing a Java class', async () => {
  648. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  649. fs.writeFileSync(
  650. path.join(tmpDir, 'JavaBar.java'),
  651. 'package com.example;\n\npublic class JavaBar {\n public String greet() { return "hi"; }\n}\n'
  652. );
  653. fs.writeFileSync(
  654. path.join(tmpDir, 'Caller.kt'),
  655. 'package com.example.app\n\nimport com.example.JavaBar\n\nfun main() { JavaBar().greet() }\n'
  656. );
  657. const cg = CodeGraph.initSync(tmpDir);
  658. await cg.indexAll();
  659. const javaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example::JavaBar');
  660. expect(javaBar, 'JavaBar should be extracted under com.example regardless of language').toBeDefined();
  661. const edge = cg.getIncomingEdges(javaBar!.id).find((e) => e.kind === 'imports');
  662. expect(edge, 'Kotlin caller should resolve its import to the Java class').toBeDefined();
  663. });
  664. it('disambiguates a class-name collision across packages', async () => {
  665. // Two `Bar` classes in different packages — each importer should reach
  666. // ITS Bar, not the other one. This is the central failure mode that
  667. // name-matcher alone cannot disambiguate.
  668. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  669. fs.writeFileSync(
  670. path.join(tmpDir, 'AlphaBar.kt'),
  671. 'package com.example.alpha\n\nclass Bar { fun who() = "alpha" }\n'
  672. );
  673. fs.writeFileSync(
  674. path.join(tmpDir, 'BetaBar.kt'),
  675. 'package com.example.beta\n\nclass Bar { fun who() = "beta" }\n'
  676. );
  677. fs.writeFileSync(
  678. path.join(tmpDir, 'CallerA.kt'),
  679. 'package app\n\nimport com.example.alpha.Bar\n\nfun a() { Bar().who() }\n'
  680. );
  681. fs.writeFileSync(
  682. path.join(tmpDir, 'CallerB.kt'),
  683. 'package app\n\nimport com.example.beta.Bar\n\nfun b() { Bar().who() }\n'
  684. );
  685. const cg = CodeGraph.initSync(tmpDir);
  686. await cg.indexAll();
  687. const alphaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example.alpha::Bar');
  688. const betaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example.beta::Bar');
  689. expect(alphaBar).toBeDefined();
  690. expect(betaBar).toBeDefined();
  691. expect(alphaBar!.id).not.toBe(betaBar!.id);
  692. // Each Bar receives exactly one imports edge — from its own caller.
  693. const alphaIncoming = cg.getIncomingEdges(alphaBar!.id).filter((e) => e.kind === 'imports');
  694. const betaIncoming = cg.getIncomingEdges(betaBar!.id).filter((e) => e.kind === 'imports');
  695. expect(alphaIncoming.length).toBeGreaterThan(0);
  696. expect(betaIncoming.length).toBeGreaterThan(0);
  697. // Sanity: the edges don't cross — alpha's incoming sources don't include
  698. // beta's filePath and vice versa.
  699. const sourceFiles = (edges: typeof alphaIncoming) =>
  700. edges.map((e) => cg.getNode(e.source)?.filePath).filter(Boolean);
  701. expect(sourceFiles(alphaIncoming).some((p) => p?.includes('CallerA.kt'))).toBe(true);
  702. expect(sourceFiles(betaIncoming).some((p) => p?.includes('CallerB.kt'))).toBe(true);
  703. });
  704. });
  705. describe('Java anonymous-class override synthesis — end-to-end', () => {
  706. let tmpDir: string | undefined;
  707. afterEach(() => {
  708. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  709. tmpDir = undefined;
  710. });
  711. it('bridges an abstract base method to overrides inside `new Base() { ... }`', async () => {
  712. // Mirrors guava Splitter: a factory returns `new BaseIter() {
  713. // @Override int separatorStart(...) { ... } }`. Without anon-class
  714. // extraction the override is invisible — Phase 5.5 interface-impl
  715. // has no class to bridge — and an agent investigating `BaseIter.separatorStart`
  716. // can't see its real implementation without reading the file.
  717. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-anon-java-'));
  718. fs.writeFileSync(
  719. path.join(tmpDir, 'Splitter.java'),
  720. 'package com.example;\n' +
  721. '\n' +
  722. 'abstract class BaseIter {\n' +
  723. ' abstract int separatorStart(int start);\n' +
  724. '}\n' +
  725. '\n' +
  726. 'public class Splitter {\n' +
  727. ' public BaseIter make() {\n' +
  728. ' return new BaseIter() {\n' +
  729. ' @Override\n' +
  730. ' int separatorStart(int start) { return start + 1; }\n' +
  731. ' };\n' +
  732. ' }\n' +
  733. '}\n'
  734. );
  735. const cg = CodeGraph.initSync(tmpDir);
  736. await cg.indexAll();
  737. // The anon class is extracted and contains the override.
  738. const anonClass = cg
  739. .getNodesByKind('class')
  740. .find((n) => /BaseIter\$anon@/.test(n.name));
  741. expect(anonClass, 'anonymous BaseIter subclass should be a class node').toBeDefined();
  742. const baseAbstract = cg
  743. .getNodesByKind('method')
  744. .find((n) => n.qualifiedName === 'com.example::BaseIter::separatorStart');
  745. const anonOverride = cg
  746. .getNodesByKind('method')
  747. .find(
  748. (n) =>
  749. n.name === 'separatorStart' &&
  750. n.qualifiedName.includes('$anon@') &&
  751. n.qualifiedName.startsWith('com.example::Splitter::make::')
  752. );
  753. expect(baseAbstract, 'base abstract method should be in the graph').toBeDefined();
  754. expect(anonOverride, 'anon-class override should be in the graph').toBeDefined();
  755. // Phase 5.5 interface-impl: the abstract method has a synthesized
  756. // `calls` edge to the anon override. Without this hop the agent
  757. // would have to Read the file to discover the implementation.
  758. const synthEdge = cg
  759. .getOutgoingEdges(baseAbstract!.id)
  760. .find((e) => e.target === anonOverride!.id && e.kind === 'calls');
  761. expect(synthEdge, 'BaseIter.separatorStart should bridge to anon.separatorStart').toBeDefined();
  762. expect(synthEdge!.provenance).toBe('heuristic');
  763. expect((synthEdge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy).toBe(
  764. 'interface-impl'
  765. );
  766. cg.close();
  767. });
  768. });
  769. describe('Go gRPC stub→impl synthesis', () => {
  770. let tmpDir: string | undefined;
  771. afterEach(() => {
  772. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  773. tmpDir = undefined;
  774. });
  775. it('bridges UnimplementedMsgServer methods to the hand-written keeper impl', async () => {
  776. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-grpc-'));
  777. // Mimic protoc-gen-go-grpc output: `*_grpc.pb.go` carrying the
  778. // UnimplementedMsgServer stub.
  779. fs.writeFileSync(
  780. path.join(tmpDir, 'tx_grpc.pb.go'),
  781. 'package banktypes\n\n' +
  782. 'type UnimplementedMsgServer struct{}\n\n' +
  783. 'func (UnimplementedMsgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) { return nil, nil }\n' +
  784. 'func (UnimplementedMsgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) { return nil, nil }\n' +
  785. 'func (UnimplementedMsgServer) mustEmbedUnimplementedMsgServer() {}\n' +
  786. 'func (UnimplementedMsgServer) testEmbeddedByValue() {}\n'
  787. );
  788. // Hand-written impl in a non-generated file — what an agent actually
  789. // wants the trace to land on.
  790. fs.writeFileSync(
  791. path.join(tmpDir, 'msg_server.go'),
  792. 'package keeper\n\n' +
  793. 'type msgServer struct{ k Keeper }\n\n' +
  794. 'func (m msgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) {\n' +
  795. ' return m.k.SendCoins(ctx, req.From, req.To, req.Amount)\n' +
  796. '}\n' +
  797. 'func (m msgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) {\n' +
  798. ' return nil, nil\n' +
  799. '}\n'
  800. );
  801. let cg: CodeGraph | undefined;
  802. try {
  803. cg = CodeGraph.initSync(tmpDir);
  804. await cg.indexAll();
  805. const stubSend = cg
  806. .getNodesByKind('method')
  807. .find((n) => n.qualifiedName.endsWith('UnimplementedMsgServer::Send'));
  808. const implSend = cg
  809. .getNodesByKind('method')
  810. .find((n) => n.qualifiedName.endsWith('msgServer::Send'));
  811. expect(stubSend, 'UnimplementedMsgServer.Send should be indexed').toBeDefined();
  812. expect(implSend, 'msgServer.Send should be indexed').toBeDefined();
  813. const bridge = cg
  814. .getOutgoingEdges(stubSend!.id)
  815. .find((e) => e.target === implSend!.id && e.kind === 'calls');
  816. expect(bridge, 'stub Send should bridge to impl Send').toBeDefined();
  817. expect(bridge!.provenance).toBe('heuristic');
  818. expect((bridge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy).toBe(
  819. 'go-grpc-stub-impl'
  820. );
  821. } finally {
  822. cg?.close();
  823. }
  824. });
  825. it('does not bridge to candidates living in another generated file', async () => {
  826. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-grpc-sib-'));
  827. // `*_grpc.pb.go` also contains a sibling `msgClient` struct that
  828. // happens to satisfy the same method set. We must NOT bridge to it —
  829. // it's not the hand-written impl, just the gRPC client wrapper.
  830. fs.writeFileSync(
  831. path.join(tmpDir, 'tx_grpc.pb.go'),
  832. 'package banktypes\n\n' +
  833. 'type UnimplementedMsgServer struct{}\n' +
  834. 'func (UnimplementedMsgServer) Send() {}\n' +
  835. 'func (UnimplementedMsgServer) MultiSend() {}\n\n' +
  836. 'type msgClient struct{}\n' +
  837. 'func (m msgClient) Send() {}\n' +
  838. 'func (m msgClient) MultiSend() {}\n'
  839. );
  840. let cg: CodeGraph | undefined;
  841. try {
  842. cg = CodeGraph.initSync(tmpDir);
  843. await cg.indexAll();
  844. const stub = cg
  845. .getNodesByKind('struct')
  846. .find((n) => n.name === 'UnimplementedMsgServer');
  847. expect(stub).toBeDefined();
  848. const bridges = cg
  849. .getNodesByKind('method')
  850. .filter((n) => n.qualifiedName.endsWith('UnimplementedMsgServer::Send'))
  851. .flatMap((stubSend) => cg!.getOutgoingEdges(stubSend.id))
  852. .filter(
  853. (e) =>
  854. e.kind === 'calls' &&
  855. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  856. 'go-grpc-stub-impl',
  857. );
  858. expect(bridges, 'no bridge to msgClient (also generated)').toHaveLength(0);
  859. } finally {
  860. cg?.close();
  861. }
  862. });
  863. });
  864. describe('React Router end-to-end route extraction (.tsx/.jsx)', () => {
  865. let tmpDir: string | undefined;
  866. afterEach(() => {
  867. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  868. tmpDir = undefined;
  869. });
  870. // Regression for the resolver language-gate bug: the `react` resolver's
  871. // `extract()` was filtered out of the .tsx/.jsx grammars, so `<Route>` routes
  872. // — which only live in JSX files — were never indexed through the real
  873. // indexing path (the unit tests call extract() directly and so missed this).
  874. it('indexes <Route element={<X/>}> routes from a .tsx file and links them to the component', async () => {
  875. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-rr-'));
  876. fs.writeFileSync(
  877. path.join(tmpDir, 'package.json'),
  878. '{"dependencies":{"react":"^18.0.0","react-router-dom":"^6.0.0"}}'
  879. );
  880. fs.writeFileSync(
  881. path.join(tmpDir, 'Home.tsx'),
  882. 'export function Home() { return null; }\n'
  883. );
  884. fs.writeFileSync(
  885. path.join(tmpDir, 'routes.tsx'),
  886. `import { Routes, Route } from 'react-router-dom';
  887. import { Home } from './Home';
  888. export function AppRoutes() {
  889. return (
  890. <Routes>
  891. <Route path="/home" element={<Home/>} />
  892. </Routes>
  893. );
  894. }
  895. `
  896. );
  897. const cg = CodeGraph.initSync(tmpDir);
  898. await cg.indexAll();
  899. try {
  900. // The route node from the .tsx file exists (the bug: it didn't).
  901. const route = cg.getNodesByKind('route').find((n) => n.name === '/home');
  902. expect(route, '/home route from .tsx should be indexed').toBeDefined();
  903. // ...and it links to the Home component.
  904. const home = cg.getNodesByName('Home').find((n) => n.kind === 'function');
  905. expect(home).toBeDefined();
  906. const toHome = cg.getOutgoingEdges(route!.id).find((e) => e.target === home!.id);
  907. expect(toHome, 'route → Home component edge').toBeDefined();
  908. } finally {
  909. cg.close();
  910. }
  911. });
  912. });
  913. describe('Terraform end-to-end module-boundary resolution', () => {
  914. let tmpDir: string | undefined;
  915. afterEach(() => {
  916. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  917. tmpDir = undefined;
  918. });
  919. function writeMultiModuleRepo(root: string) {
  920. fs.mkdirSync(path.join(root, 'modules/vpc'), { recursive: true });
  921. fs.mkdirSync(path.join(root, 'modules/other'), { recursive: true });
  922. fs.mkdirSync(path.join(root, 'envs'), { recursive: true });
  923. fs.writeFileSync(
  924. path.join(root, 'main.tf'),
  925. 'variable "vpc_cidr" {\n type = string\n}\n\n' +
  926. 'module "vpc" {\n source = "./modules/vpc"\n cidr = var.vpc_cidr\n}\n\n' +
  927. 'module "registry_thing" {\n source = "terraform-aws-modules/s3-bucket/aws"\n bucket = "x"\n}\n\n' +
  928. 'output "vpc_id" {\n value = module.vpc.vpc_id\n}\n'
  929. );
  930. fs.writeFileSync(
  931. path.join(root, 'modules/vpc/variables.tf'),
  932. 'variable "cidr" {\n type = string\n}\n'
  933. );
  934. fs.writeFileSync(
  935. path.join(root, 'modules/vpc/main.tf'),
  936. 'resource "aws_vpc" "this" {\n cidr_block = var.cidr\n}\n'
  937. );
  938. fs.writeFileSync(
  939. path.join(root, 'modules/vpc/outputs.tf'),
  940. 'output "vpc_id" {\n value = aws_vpc.this.id\n}\n'
  941. );
  942. // Same-named variable in an UNRELATED module — must never receive edges
  943. // from outside its own directory.
  944. fs.writeFileSync(
  945. path.join(root, 'modules/other/variables.tf'),
  946. 'variable "cidr" {\n type = string\n}\nvariable "orphan_ref_target" {}\n'
  947. );
  948. // References a variable that has no same-dir declaration: must stay unlinked.
  949. fs.writeFileSync(
  950. path.join(root, 'modules/other/main.tf'),
  951. 'resource "aws_eip" "e" {\n tags = { Name = var.undeclared_here_elsewhere_yes }\n}\n'
  952. );
  953. fs.writeFileSync(path.join(root, 'envs/prod.tfvars'), 'vpc_cidr = "10.0.0.0/16"\n');
  954. }
  955. it('bridges module inputs/outputs/source and enforces directory scoping', async () => {
  956. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-terraform-'));
  957. writeMultiModuleRepo(tmpDir);
  958. const cg = CodeGraph.initSync(tmpDir);
  959. await cg.indexAll();
  960. try {
  961. const byQname = (q: string, file?: string) =>
  962. cg
  963. .getNodesByName(q.split('.').pop()!)
  964. .filter((n) => n.qualifiedName === q && (!file || n.filePath === file));
  965. const moduleDecl = byQname('module.vpc')[0];
  966. expect(moduleDecl, 'module.vpc declaration node').toBeDefined();
  967. const childCidr = byQname('var.cidr', 'modules/vpc/variables.tf')[0];
  968. expect(childCidr, "child module's var.cidr").toBeDefined();
  969. const childOutput = byQname('output.vpc_id', 'modules/vpc/outputs.tf')[0];
  970. expect(childOutput, "child module's output.vpc_id").toBeDefined();
  971. const rootOutput = byQname('output.vpc_id', 'main.tf')[0];
  972. expect(rootOutput, 'root output.vpc_id').toBeDefined();
  973. const declEdges = cg.getOutgoingEdges(moduleDecl!.id);
  974. // Input wiring: module block → child variable (cross-directory).
  975. expect(
  976. declEdges.find((e) => e.target === childCidr!.id),
  977. 'module.vpc → child var.cidr input edge'
  978. ).toBeDefined();
  979. // Source wiring: module block → child entry file.
  980. const fileNode = cg
  981. .getNodesInFile('modules/vpc/main.tf')
  982. .find((n) => n.kind === 'file');
  983. expect(fileNode).toBeDefined();
  984. const importEdge = declEdges.find((e) => e.target === fileNode!.id);
  985. expect(importEdge, 'module.vpc → modules/vpc/main.tf imports edge').toBeDefined();
  986. expect(importEdge!.kind).toBe('imports');
  987. // Output bridge: root output → child output (not just the declaration).
  988. const rootOutEdges = cg.getOutgoingEdges(rootOutput!.id);
  989. expect(
  990. rootOutEdges.find((e) => e.target === childOutput!.id),
  991. 'root output.vpc_id → child output.vpc_id'
  992. ).toBeDefined();
  993. expect(
  994. rootOutEdges.find((e) => e.target === moduleDecl!.id),
  995. 'root output.vpc_id → module.vpc declaration'
  996. ).toBeDefined();
  997. // tfvars assignment walks up to the ROOT variable.
  998. const rootVar = byQname('var.vpc_cidr', 'main.tf')[0];
  999. expect(rootVar).toBeDefined();
  1000. const tfvarsFile = cg.getNodesInFile('envs/prod.tfvars').find((n) => n.kind === 'file');
  1001. expect(tfvarsFile).toBeDefined();
  1002. expect(
  1003. cg.getOutgoingEdges(tfvarsFile!.id).find((e) => e.target === rootVar!.id),
  1004. 'envs/prod.tfvars → var.vpc_cidr'
  1005. ).toBeDefined();
  1006. // Directory scoping: the unrelated module's same-named var.cidr gets
  1007. // NO incoming edges from outside its own directory…
  1008. const otherCidr = byQname('var.cidr', 'modules/other/variables.tf')[0];
  1009. expect(otherCidr).toBeDefined();
  1010. const incomingOther = cg.getIncomingEdges(otherCidr!.id).filter((e) => e.kind !== 'contains');
  1011. expect(incomingOther, 'unrelated module var.cidr must stay isolated').toHaveLength(0);
  1012. // …and a reference with no same-dir declaration stays unlinked rather
  1013. // than borrowing another module's declaration.
  1014. const orphanEdges = cg
  1015. .getNodesInFile('modules/other/main.tf')
  1016. .filter((n) => n.qualifiedName === 'aws_eip.e')
  1017. .flatMap((n) => cg.getOutgoingEdges(n.id))
  1018. .filter((e) => e.kind === 'references');
  1019. const orphanTargets = orphanEdges.map((e) => cg.getNode(e.target)?.qualifiedName);
  1020. expect(orphanTargets).not.toContain('var.undeclared_here_elsewhere_yes');
  1021. // Registry-sourced module: inputs stay unresolved (no guessed edges).
  1022. const registryDecl = byQname('module.registry_thing')[0];
  1023. expect(registryDecl).toBeDefined();
  1024. const registryEdges = cg
  1025. .getOutgoingEdges(registryDecl!.id)
  1026. .filter((e) => e.kind !== 'contains');
  1027. expect(registryEdges, 'registry module must not link anywhere').toHaveLength(0);
  1028. } finally {
  1029. cg.close();
  1030. }
  1031. });
  1032. });
  1033. describe('Terraform follow-ups: remote-state bridge, provider alias, moved blocks', () => {
  1034. let tmpDir: string | undefined;
  1035. afterEach(() => {
  1036. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  1037. tmpDir = undefined;
  1038. });
  1039. it('bridges atmos remote-state to the target component, resolves provider aliases up the tree, links moved blocks', async () => {
  1040. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-terraform-fu-'));
  1041. // Component producing state.
  1042. fs.mkdirSync(path.join(tmpDir, 'components/terraform/vpc'), { recursive: true });
  1043. fs.writeFileSync(
  1044. path.join(tmpDir, 'components/terraform/vpc/outputs.tf'),
  1045. 'output "vpc_id" {\n value = "vpc-123"\n}\n'
  1046. );
  1047. // Component consuming it via the cloudposse remote-state module.
  1048. fs.mkdirSync(path.join(tmpDir, 'components/terraform/eks/cluster'), { recursive: true });
  1049. fs.writeFileSync(
  1050. path.join(tmpDir, 'components/terraform/eks/cluster/remote-state.tf'),
  1051. 'module "vpc" {\n' +
  1052. ' source = "cloudposse/stack-config/yaml//modules/remote-state"\n' +
  1053. ' component = var.vpc_component_name\n' +
  1054. '}\n' +
  1055. 'variable "vpc_component_name" {\n' +
  1056. ' type = string\n' +
  1057. ' default = "vpc"\n' +
  1058. '}\n'
  1059. );
  1060. fs.writeFileSync(
  1061. path.join(tmpDir, 'components/terraform/eks/cluster/main.tf'),
  1062. 'resource "aws_eks_cluster" "this" {\n vpc_id = module.vpc.outputs.vpc_id\n}\n'
  1063. );
  1064. // Ambiguous component name — two directories called "dns" with the same
  1065. // output; the bridge must refuse to pick one.
  1066. fs.mkdirSync(path.join(tmpDir, 'components/terraform/dns'), { recursive: true });
  1067. fs.mkdirSync(path.join(tmpDir, 'legacy/dns'), { recursive: true });
  1068. fs.writeFileSync(path.join(tmpDir, 'components/terraform/dns/outputs.tf'), 'output "zone_id" {\n value = "z1"\n}\n');
  1069. fs.writeFileSync(path.join(tmpDir, 'legacy/dns/outputs.tf'), 'output "zone_id" {\n value = "z2"\n}\n');
  1070. fs.writeFileSync(
  1071. path.join(tmpDir, 'components/terraform/eks/cluster/dns.tf'),
  1072. 'module "dns" {\n' +
  1073. ' source = "cloudposse/stack-config/yaml//modules/remote-state"\n' +
  1074. ' component = "dns"\n' +
  1075. '}\n' +
  1076. 'output "zone" {\n value = module.dns.outputs.zone_id\n}\n'
  1077. );
  1078. // Provider alias declared at the root, selected inside a module dir.
  1079. fs.writeFileSync(
  1080. path.join(tmpDir, 'providers.tf'),
  1081. 'provider "aws" {\n region = "us-east-1"\n}\n' +
  1082. 'provider "aws" {\n alias = "east"\n region = "us-east-2"\n}\n'
  1083. );
  1084. fs.mkdirSync(path.join(tmpDir, 'modules/app'), { recursive: true });
  1085. fs.writeFileSync(
  1086. path.join(tmpDir, 'modules/app/main.tf'),
  1087. 'resource "aws_s3_bucket" "b" {\n provider = aws.east\n bucket = "x"\n}\n'
  1088. );
  1089. // Moved block referencing a live resource.
  1090. fs.writeFileSync(
  1091. path.join(tmpDir, 'main.tf'),
  1092. 'resource "aws_instance" "renamed" {}\n' +
  1093. 'moved {\n from = aws_instance.old\n to = aws_instance.renamed\n}\n'
  1094. );
  1095. const cg = CodeGraph.initSync(tmpDir);
  1096. await cg.indexAll();
  1097. try {
  1098. const byQname = (q: string, file?: string) =>
  1099. cg
  1100. .getNodesByName(q.split('.').pop()!)
  1101. .filter((n) => n.qualifiedName === q && (!file || n.filePath === file));
  1102. // 1. remote-state bridge: consumer resource → producer component's output.
  1103. const consumer = byQname('aws_eks_cluster.this')[0] ??
  1104. cg.getNodesInFile('components/terraform/eks/cluster/main.tf').find((n) => n.qualifiedName === 'aws_eks_cluster.this');
  1105. expect(consumer, 'consumer resource').toBeDefined();
  1106. const producerOut = byQname('output.vpc_id', 'components/terraform/vpc/outputs.tf')[0];
  1107. expect(producerOut, "producer component's output").toBeDefined();
  1108. expect(
  1109. cg.getOutgoingEdges(consumer!.id).find((e) => e.target === producerOut!.id),
  1110. 'remote-state bridge edge eks/cluster → vpc output'
  1111. ).toBeDefined();
  1112. // 2. Ambiguous component name → no bridge edge to either candidate.
  1113. const zoneOut = byQname('output.zone', 'components/terraform/eks/cluster/dns.tf')[0];
  1114. expect(zoneOut).toBeDefined();
  1115. const zoneTargets = cg
  1116. .getOutgoingEdges(zoneOut!.id)
  1117. .map((e) => cg.getNode(e.target))
  1118. .filter((n) => n?.qualifiedName === 'output.zone_id');
  1119. expect(zoneTargets, 'ambiguous component must not be guessed').toHaveLength(0);
  1120. // 3. Provider alias: nodes are distinct, and the selection inside the
  1121. // module resolves up the tree to the aliased configuration.
  1122. const provNodes = cg.getNodesInFile('providers.tf');
  1123. const aliased = provNodes.find((n) => n.qualifiedName === 'provider.aws.east');
  1124. const defaultProv = provNodes.find((n) => n.qualifiedName === 'provider.aws');
  1125. expect(aliased, 'aliased provider node').toBeDefined();
  1126. expect(defaultProv, 'default provider node').toBeDefined();
  1127. const bucket = cg.getNodesInFile('modules/app/main.tf').find((n) => n.qualifiedName === 'aws_s3_bucket.b');
  1128. expect(bucket).toBeDefined();
  1129. const bucketEdges = cg.getOutgoingEdges(bucket!.id);
  1130. expect(
  1131. bucketEdges.find((e) => e.target === aliased!.id),
  1132. 'provider = aws.east → aliased provider (ancestor walk)'
  1133. ).toBeDefined();
  1134. expect(bucketEdges.find((e) => e.target === defaultProv!.id), 'must not link the default provider').toBeUndefined();
  1135. // 4. moved block: the file references the live resource.
  1136. const renamed = cg.getNodesInFile('main.tf').find((n) => n.qualifiedName === 'aws_instance.renamed');
  1137. expect(renamed).toBeDefined();
  1138. const rootFile = cg.getNodesInFile('main.tf').find((n) => n.kind === 'file');
  1139. expect(
  1140. cg.getOutgoingEdges(rootFile!.id).find((e) => e.target === renamed!.id),
  1141. 'moved block → live resource edge'
  1142. ).toBeDefined();
  1143. } finally {
  1144. cg.close();
  1145. }
  1146. });
  1147. });