frameworks-integration.test.ts 61 KB

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