frameworks.test.ts 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. import { describe, it, expect } from 'vitest';
  2. import type { FrameworkResolver, UnresolvedRef } from '../src/resolution/types';
  3. import type { Node } from '../src/types';
  4. describe('FrameworkResolver.extract interface', () => {
  5. it('extract() returns { nodes, references }', () => {
  6. const resolver: FrameworkResolver = {
  7. name: 'fake',
  8. detect: () => true,
  9. resolve: () => null,
  10. languages: ['python'],
  11. extract: (_filePath: string, _content: string) => ({
  12. nodes: [] as Node[],
  13. references: [] as UnresolvedRef[],
  14. }),
  15. };
  16. const result = resolver.extract!('foo.py', '');
  17. expect(result).toEqual({ nodes: [], references: [] });
  18. });
  19. });
  20. import { getApplicableFrameworks } from '../src/resolution/frameworks';
  21. import type { FrameworkResolver } from '../src/resolution/types';
  22. describe('getApplicableFrameworks', () => {
  23. const pyFw: FrameworkResolver = { name: 'py', languages: ['python'], detect: () => true, resolve: () => null };
  24. const jsFw: FrameworkResolver = { name: 'js', languages: ['javascript', 'typescript'], detect: () => true, resolve: () => null };
  25. const anyFw: FrameworkResolver = { name: 'any', detect: () => true, resolve: () => null };
  26. it('filters by language', () => {
  27. const result = getApplicableFrameworks([pyFw, jsFw, anyFw], 'python');
  28. expect(result.map(r => r.name)).toEqual(['py', 'any']);
  29. });
  30. it('returns anyFw-only when language has no matches', () => {
  31. const result = getApplicableFrameworks([pyFw, jsFw, anyFw], 'rust');
  32. expect(result.map(r => r.name)).toEqual(['any']);
  33. });
  34. });
  35. import { djangoResolver } from '../src/resolution/frameworks/python';
  36. describe('djangoResolver.extract', () => {
  37. it('extracts route node and reference for path() with CBV.as_view()', () => {
  38. const src = `
  39. from django.urls import path
  40. from users.views import UserListView
  41. urlpatterns = [
  42. path('users/', UserListView.as_view(), name='user-list'),
  43. ]
  44. `;
  45. const { nodes, references } = djangoResolver.extract!('users/urls.py', src);
  46. expect(nodes).toHaveLength(1);
  47. expect(nodes[0].kind).toBe('route');
  48. expect(nodes[0].name).toBe('users/');
  49. expect(references).toHaveLength(1);
  50. expect(references[0].referenceName).toBe('UserListView');
  51. expect(references[0].referenceKind).toBe('references');
  52. expect(references[0].fromNodeId).toBe(nodes[0].id);
  53. });
  54. it('extracts route for path() with dotted module.Class.as_view()', () => {
  55. const src = `from django.urls import path\nfrom api.v1 import views as api_v1_views\nurlpatterns = [path('api/', api_v1_views.UserListView.as_view())]\n`;
  56. const { nodes, references } = djangoResolver.extract!('api/urls.py', src);
  57. expect(nodes).toHaveLength(1);
  58. expect(references[0].referenceName).toBe('UserListView');
  59. });
  60. it('extracts route for path() with bare function view', () => {
  61. const src = `from django.urls import path\nurlpatterns = [path('home/', home_view, name='home')]\n`;
  62. const { nodes, references } = djangoResolver.extract!('home/urls.py', src);
  63. expect(references[0].referenceName).toBe('home_view');
  64. });
  65. it('extracts route for path() with include()', () => {
  66. const src = `from django.urls import path, include\nurlpatterns = [path('api/', include('api.urls'))]\n`;
  67. const { nodes, references } = djangoResolver.extract!('root/urls.py', src);
  68. expect(nodes).toHaveLength(1);
  69. expect(nodes[0].kind).toBe('route');
  70. expect(references[0].referenceName).toBe('api.urls');
  71. expect(references[0].referenceKind).toBe('imports');
  72. });
  73. it('extracts routes for re_path and url', () => {
  74. const src = `from django.urls import re_path, url\nurlpatterns = [re_path(r'^users/$', UserView), url(r'^old/$', OldView)]\n`;
  75. const { nodes } = djangoResolver.extract!('legacy/urls.py', src);
  76. expect(nodes).toHaveLength(2);
  77. expect(nodes.map(n => n.name)).toEqual(['^users/$', '^old/$']);
  78. });
  79. it('returns empty result for a non-urls.py python file', () => {
  80. const src = `def foo(): return 1\n`;
  81. const { nodes, references } = djangoResolver.extract!('views.py', src);
  82. expect(nodes).toEqual([]);
  83. expect(references).toEqual([]);
  84. });
  85. });
  86. import { flaskResolver, fastapiResolver } from '../src/resolution/frameworks/python';
  87. describe('flaskResolver.extract', () => {
  88. it('extracts route and reference from @app.route', () => {
  89. const src = `
  90. @app.route('/users')
  91. def list_users():
  92. return []
  93. `;
  94. const { nodes, references } = flaskResolver.extract!('app.py', src);
  95. expect(nodes).toHaveLength(1);
  96. expect(nodes[0].kind).toBe('route');
  97. expect(nodes[0].name).toBe('GET /users');
  98. expect(references[0].referenceName).toBe('list_users');
  99. });
  100. it('extracts blueprint routes', () => {
  101. const src = `
  102. @users_bp.route('/<id>', methods=['POST'])
  103. def create_user(id):
  104. pass
  105. `;
  106. const { nodes, references } = flaskResolver.extract!('routes.py', src);
  107. expect(nodes[0].name).toBe('POST /<id>');
  108. expect(references[0].referenceName).toBe('create_user');
  109. });
  110. it('resolves the handler across an intervening decorator (@login_required)', () => {
  111. const src = `
  112. @bp.route('/profile')
  113. @login_required
  114. def profile():
  115. return render_template('profile.html')
  116. `;
  117. const { nodes, references } = flaskResolver.extract!('routes.py', src);
  118. expect(nodes[0].name).toBe('GET /profile');
  119. expect(references[0].referenceName).toBe('profile');
  120. });
  121. it('extracts stacked @x.route decorators bound to one view', () => {
  122. const src = `
  123. @bp.route('/', methods=['GET', 'POST'])
  124. @bp.route('/index', methods=['GET', 'POST'])
  125. @login_required
  126. def index():
  127. return render_template('index.html')
  128. `;
  129. const { nodes, references } = flaskResolver.extract!('routes.py', src);
  130. expect(nodes.map((n) => n.name)).toEqual(['GET /', 'GET /index']);
  131. expect(references.map((r) => r.referenceName)).toEqual(['index', 'index']);
  132. });
  133. it('extracts the method from a tuple methods=(...) (not just a list)', () => {
  134. const src = `
  135. @blueprint.route('/api/articles', methods=('POST',))
  136. def make_article():
  137. pass
  138. `;
  139. const { nodes, references } = flaskResolver.extract!('views.py', src);
  140. expect(nodes[0].name).toBe('POST /api/articles');
  141. expect(references[0].referenceName).toBe('make_article');
  142. });
  143. it('extracts Flask-RESTful api.add_resource(Resource, paths) → the Resource class', () => {
  144. const src = `
  145. api.add_resource(TodoResource, '/todos/<id>')
  146. api.add_org_resource(AlertResource, '/api/alerts/<id>', endpoint='alert')
  147. `;
  148. const { nodes, references } = flaskResolver.extract!('api.py', src);
  149. expect(nodes.map((n) => n.name)).toEqual(['ANY /todos/<id>', 'ANY /api/alerts/<id>']);
  150. expect(references.map((r) => r.referenceName)).toEqual(['TodoResource', 'AlertResource']);
  151. });
  152. });
  153. describe('fastapiResolver.extract', () => {
  154. it('extracts route and reference from @app.get', () => {
  155. const src = `
  156. @app.get('/users')
  157. async def list_users():
  158. return []
  159. `;
  160. const { nodes, references } = fastapiResolver.extract!('main.py', src);
  161. expect(nodes[0].name).toBe('GET /users');
  162. expect(references[0].referenceName).toBe('list_users');
  163. });
  164. it('extracts route from router.post', () => {
  165. const src = `
  166. @router.post('/items')
  167. def create_item(item: Item):
  168. pass
  169. `;
  170. const { nodes, references } = fastapiResolver.extract!('items.py', src);
  171. expect(nodes[0].name).toBe('POST /items');
  172. expect(references[0].referenceName).toBe('create_item');
  173. });
  174. it('extracts a route mounted at the router/prefix root (empty path)', () => {
  175. const src = `
  176. @router.get("", response_model=ListOfArticles, name="articles:list")
  177. async def list_articles():
  178. return []
  179. `;
  180. const { nodes, references } = fastapiResolver.extract!('articles.py', src);
  181. expect(nodes[0].name).toBe('GET /');
  182. expect(references[0].referenceName).toBe('list_articles');
  183. });
  184. it('extracts a multi-line decorator with an empty path', () => {
  185. const src = `
  186. @router.post(
  187. "",
  188. status_code=201,
  189. response_model=ArticleInResponse,
  190. )
  191. async def create_article():
  192. pass
  193. `;
  194. const { nodes, references } = fastapiResolver.extract!('articles.py', src);
  195. expect(nodes[0].name).toBe('POST /');
  196. expect(references[0].referenceName).toBe('create_article');
  197. });
  198. });
  199. import { expressResolver } from '../src/resolution/frameworks/express';
  200. describe('expressResolver.extract', () => {
  201. it('extracts route with inline handler reference', () => {
  202. const src = `app.get('/users', listUsers);\n`;
  203. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  204. expect(nodes).toHaveLength(1);
  205. expect(nodes[0].name).toBe('GET /users');
  206. expect(references[0].referenceName).toBe('listUsers');
  207. });
  208. it('extracts route with router.post and middleware chain', () => {
  209. const src = `router.post('/items', auth, createItem);\n`;
  210. const { nodes, references } = expressResolver.extract!('items.ts', src);
  211. expect(nodes[0].name).toBe('POST /items');
  212. // Multiple handlers: prefer the LAST one (convention: middleware first, handler last)
  213. expect(references[0].referenceName).toBe('createItem');
  214. });
  215. it('extracts route with controller method reference', () => {
  216. const src = `app.get('/x', userController.list);\n`;
  217. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  218. expect(references[0].referenceName).toBe('list');
  219. });
  220. });
  221. import { nestjsResolver } from '../src/resolution/frameworks/nestjs';
  222. describe('nestjsResolver.extract — HTTP', () => {
  223. it('joins @Controller prefix with @Get and links the handler', () => {
  224. const src = `
  225. @Controller('users')
  226. export class UsersController {
  227. @Get()
  228. findAll() { return []; }
  229. }
  230. `;
  231. const { nodes, references } = nestjsResolver.extract!('users.controller.ts', src);
  232. expect(nodes).toHaveLength(1);
  233. expect(nodes[0].kind).toBe('route');
  234. expect(nodes[0].name).toBe('GET /users');
  235. expect(references[0].referenceName).toBe('findAll');
  236. expect(references[0].referenceKind).toBe('references');
  237. expect(references[0].fromNodeId).toBe(nodes[0].id);
  238. });
  239. it('joins controller prefix with a method-level path param', () => {
  240. const src = `
  241. @Controller('cats')
  242. export class CatsController {
  243. @Get(':id')
  244. findOne(@Param('id') id: string) { return id; }
  245. }
  246. `;
  247. const { nodes, references } = nestjsResolver.extract!('cats.controller.ts', src);
  248. expect(nodes[0].name).toBe('GET /cats/:id');
  249. expect(references[0].referenceName).toBe('findOne');
  250. });
  251. it('handles an empty @Controller() and empty @Post()', () => {
  252. const src = `
  253. @Controller()
  254. export class AppController {
  255. @Post()
  256. create() {}
  257. }
  258. `;
  259. const { nodes, references } = nestjsResolver.extract!('app.controller.ts', src);
  260. expect(nodes[0].name).toBe('POST /');
  261. expect(references[0].referenceName).toBe('create');
  262. });
  263. it('covers HTTP verbs and skips intervening method decorators', () => {
  264. const src = `
  265. @Controller('todos')
  266. export class TodosController {
  267. @Put(':id')
  268. @UseGuards(AuthGuard)
  269. update(@Param('id') id: string) {}
  270. @Delete(':id')
  271. async remove(@Param('id') id: string) {}
  272. }
  273. `;
  274. const { nodes, references } = nestjsResolver.extract!('todos.controller.ts', src);
  275. expect(nodes.map((n) => n.name)).toEqual(['PUT /todos/:id', 'DELETE /todos/:id']);
  276. expect(references.map((r) => r.referenceName)).toEqual(['update', 'remove']);
  277. });
  278. it('attributes methods to the right controller when a file has two', () => {
  279. const src = `
  280. @Controller('a')
  281. export class AController {
  282. @Get('x')
  283. ax() {}
  284. }
  285. @Controller('b')
  286. export class BController {
  287. @Get('y')
  288. by() {}
  289. }
  290. `;
  291. const { nodes } = nestjsResolver.extract!('multi.controller.ts', src);
  292. expect(nodes.map((n) => n.name)).toEqual(['GET /a/x', 'GET /b/y']);
  293. });
  294. });
  295. describe('nestjsResolver.extract — GraphQL', () => {
  296. it('emits QUERY/MUTATION nodes from a resolver, defaulting to the method name', () => {
  297. const src = `
  298. @Resolver(() => User)
  299. export class UsersResolver {
  300. @Query(() => [User])
  301. users() { return []; }
  302. @Mutation(() => User)
  303. createUser(@Args('input') input: CreateUserInput) {}
  304. }
  305. `;
  306. const { nodes, references } = nestjsResolver.extract!('users.resolver.ts', src);
  307. expect(nodes.map((n) => n.name)).toEqual(['QUERY users', 'MUTATION createUser']);
  308. expect(references.map((r) => r.referenceName)).toEqual(['users', 'createUser']);
  309. });
  310. it('uses an explicit operation name when given', () => {
  311. const src = `
  312. @Resolver()
  313. export class CatsResolver {
  314. @Query(() => Cat, { name: 'cat' })
  315. getCat() {}
  316. }
  317. `;
  318. const { nodes } = nestjsResolver.extract!('cats.resolver.ts', src);
  319. expect(nodes[0].name).toBe('QUERY cat');
  320. });
  321. it('does NOT treat the REST @Query() parameter decorator as a GraphQL op', () => {
  322. const src = `
  323. @Controller('search')
  324. export class SearchController {
  325. @Get()
  326. search(@Query() query: SearchDto) { return query; }
  327. }
  328. `;
  329. const { nodes } = nestjsResolver.extract!('search.controller.ts', src);
  330. // Only the HTTP route — the @Query() param decorator must be ignored.
  331. expect(nodes.map((n) => n.name)).toEqual(['GET /search']);
  332. });
  333. });
  334. describe('nestjsResolver.extract — microservices & websockets', () => {
  335. it('extracts @MessagePattern and @EventPattern handlers', () => {
  336. const src = `
  337. @Controller()
  338. export class MathController {
  339. @MessagePattern({ cmd: 'sum' })
  340. accumulate(data: number[]) {}
  341. @EventPattern('user.created')
  342. handleUserCreated(data: any) {}
  343. }
  344. `;
  345. const { nodes, references } = nestjsResolver.extract!('math.controller.ts', src);
  346. expect(nodes.map((n) => n.name)).toEqual(['MESSAGE sum', 'EVENT user.created']);
  347. expect(references.map((r) => r.referenceName)).toEqual(['accumulate', 'handleUserCreated']);
  348. });
  349. it('extracts @SubscribeMessage handlers with the gateway namespace', () => {
  350. const src = `
  351. @WebSocketGateway({ namespace: 'chat' })
  352. export class ChatGateway {
  353. @SubscribeMessage('message')
  354. handleMessage(@MessageBody() data: string) {}
  355. }
  356. `;
  357. const { nodes, references } = nestjsResolver.extract!('chat.gateway.ts', src);
  358. expect(nodes[0].name).toBe('WS chat:message');
  359. expect(references[0].referenceName).toBe('handleMessage');
  360. });
  361. it('extracts @SubscribeMessage without a namespace', () => {
  362. const src = `
  363. @WebSocketGateway()
  364. export class EventsGateway {
  365. @SubscribeMessage('events')
  366. onEvent() {}
  367. }
  368. `;
  369. const { nodes } = nestjsResolver.extract!('events.gateway.ts', src);
  370. expect(nodes[0].name).toBe('WS events');
  371. });
  372. it('returns empty for a non-JS/TS file', () => {
  373. const { nodes, references } = nestjsResolver.extract!('thing.py', '@Controller("x")');
  374. expect(nodes).toEqual([]);
  375. expect(references).toEqual([]);
  376. });
  377. });
  378. describe('nestjsResolver.detect', () => {
  379. const baseContext = {
  380. getNodesInFile: () => [],
  381. getNodesByName: () => [],
  382. getNodesByQualifiedName: () => [],
  383. getNodesByKind: () => [],
  384. fileExists: () => false,
  385. getProjectRoot: () => '/test',
  386. getAllFiles: () => [],
  387. getNodesByLowerName: () => [],
  388. getImportMappings: () => [],
  389. };
  390. it('detects @nestjs/* in package.json', () => {
  391. const context = {
  392. ...baseContext,
  393. readFile: (p: string) =>
  394. p === 'package.json'
  395. ? JSON.stringify({ dependencies: { '@nestjs/common': '^10.0.0' } })
  396. : null,
  397. };
  398. expect(nestjsResolver.detect(context as any)).toBe(true);
  399. });
  400. it('detects @Controller in a *.controller.ts file when package.json is absent', () => {
  401. const context = {
  402. ...baseContext,
  403. getAllFiles: () => ['src/users.controller.ts'],
  404. readFile: (p: string) =>
  405. p === 'src/users.controller.ts'
  406. ? `@Controller('users')\nexport class UsersController {}`
  407. : null,
  408. };
  409. expect(nestjsResolver.detect(context as any)).toBe(true);
  410. });
  411. it('returns false for a non-Nest project', () => {
  412. const context = {
  413. ...baseContext,
  414. readFile: (p: string) =>
  415. p === 'package.json' ? JSON.stringify({ dependencies: { express: '^4' } }) : null,
  416. };
  417. expect(nestjsResolver.detect(context as any)).toBe(false);
  418. });
  419. });
  420. describe('nestjsResolver.resolve', () => {
  421. const baseContext = {
  422. getNodesInFile: () => [],
  423. getNodesByName: () => [],
  424. getNodesByQualifiedName: () => [],
  425. getNodesByKind: () => [],
  426. fileExists: () => false,
  427. readFile: () => null,
  428. getProjectRoot: () => '/test',
  429. getAllFiles: () => [],
  430. getNodesByLowerName: () => [],
  431. getImportMappings: () => [],
  432. };
  433. it('resolves an injected *Service reference to the class in a *.service.ts file', () => {
  434. const svcNode: Node = {
  435. id: 'class:src/users/users.service.ts:UsersService:3',
  436. kind: 'class',
  437. name: 'UsersService',
  438. qualifiedName: 'src/users/users.service.ts::UsersService',
  439. filePath: 'src/users/users.service.ts',
  440. language: 'typescript',
  441. startLine: 3,
  442. endLine: 3,
  443. startColumn: 0,
  444. endColumn: 0,
  445. updatedAt: Date.now(),
  446. };
  447. const context = {
  448. ...baseContext,
  449. getNodesByName: (n: string) => (n === 'UsersService' ? [svcNode] : []),
  450. };
  451. const ref = {
  452. fromNodeId: 'class:src/users/users.controller.ts:UsersController:5',
  453. referenceName: 'UsersService',
  454. referenceKind: 'references' as const,
  455. line: 6,
  456. column: 4,
  457. filePath: 'src/users/users.controller.ts',
  458. language: 'typescript' as const,
  459. };
  460. const result = nestjsResolver.resolve(ref, context as any);
  461. expect(result?.targetNodeId).toBe(svcNode.id);
  462. expect(result?.resolvedBy).toBe('framework');
  463. expect(result?.confidence).toBeGreaterThanOrEqual(0.85);
  464. });
  465. it('returns null for a name without a provider suffix', () => {
  466. const ref = {
  467. fromNodeId: 'x',
  468. referenceName: 'doThing',
  469. referenceKind: 'references' as const,
  470. line: 1,
  471. column: 1,
  472. filePath: 'a.ts',
  473. language: 'typescript' as const,
  474. };
  475. expect(nestjsResolver.resolve(ref, baseContext as any)).toBeNull();
  476. });
  477. });
  478. import { laravelResolver } from '../src/resolution/frameworks/laravel';
  479. describe('laravelResolver.extract', () => {
  480. it('extracts route with controller tuple syntax', () => {
  481. const src = `Route::get('/users', [UserController::class, 'index']);\n`;
  482. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  483. expect(nodes[0].name).toBe('GET /users');
  484. expect(references[0].referenceName).toBe('UserController@index');
  485. });
  486. it('extracts route with Controller@action syntax', () => {
  487. const src = `Route::post('/users', 'UserController@store');\n`;
  488. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  489. expect(references[0].referenceName).toBe('UserController@store');
  490. });
  491. it('extracts resource route', () => {
  492. const src = `Route::resource('users', UserController::class);\n`;
  493. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  494. expect(nodes[0].kind).toBe('route');
  495. expect(references[0].referenceName).toBe('UserController');
  496. });
  497. });
  498. import { railsResolver } from '../src/resolution/frameworks/ruby';
  499. describe('railsResolver.extract', () => {
  500. it('extracts route with controller#action syntax', () => {
  501. const src = `get '/users', to: 'users#index'\n`;
  502. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  503. expect(nodes[0].name).toBe('GET /users');
  504. expect(references[0].referenceName).toBe('users#index');
  505. });
  506. it('extracts route without to: keyword', () => {
  507. const src = `post '/items' => 'items#create'\n`;
  508. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  509. expect(references[0].referenceName).toBe('items#create');
  510. });
  511. });
  512. import { springResolver } from '../src/resolution/frameworks/java';
  513. describe('springResolver.extract', () => {
  514. it('extracts route with @GetMapping and next method', () => {
  515. const src = `
  516. @GetMapping("/users")
  517. public List<User> listUsers() {
  518. return users;
  519. }
  520. `;
  521. const { nodes, references } = springResolver.extract!('UserController.java', src);
  522. expect(nodes[0].name).toBe('GET /users');
  523. expect(references[0].referenceName).toBe('listUsers');
  524. });
  525. it('extracts a Kotlin @GetMapping with a fun handler', () => {
  526. const src = `
  527. @GetMapping("/vets")
  528. fun showVetList(model: MutableMap<String, Any>): String {
  529. return "vets"
  530. }
  531. `;
  532. const { nodes, references } = springResolver.extract!('VetController.kt', src);
  533. expect(nodes[0].name).toBe('GET /vets');
  534. expect(references[0].referenceName).toBe('showVetList');
  535. expect(nodes[0].language).toBe('kotlin');
  536. });
  537. it('joins a Kotlin class @RequestMapping prefix and skips a stacked annotation', () => {
  538. const src = `
  539. @RestController
  540. @RequestMapping("/owners")
  541. class OwnerController {
  542. @GetMapping("/{ownerId}")
  543. @ResponseBody
  544. fun showOwner(@PathVariable ownerId: Int): String {
  545. return "owner"
  546. }
  547. }
  548. `;
  549. const { nodes, references } = springResolver.extract!('OwnerController.kt', src);
  550. expect(nodes[0].name).toBe('GET /owners/{ownerId}');
  551. expect(references[0].referenceName).toBe('showOwner');
  552. });
  553. });
  554. import { playResolver } from '../src/resolution/frameworks/play';
  555. import { isSourceFile, isPlayRoutesFile } from '../src/extraction/grammars';
  556. describe('playResolver.extract (conf/routes)', () => {
  557. it('extracts METHOD /path Controller.action routes, dropping the package + args', () => {
  558. const src = `# Routes
  559. GET / controllers.Application.index
  560. GET /computers controllers.Application.list(p: Int ?= 0, s: Int ?= 2)
  561. POST /computers controllers.Application.save
  562. -> /v1/posts v1.post.PostRouter
  563. `;
  564. const { nodes, references } = playResolver.extract!('conf/routes', src);
  565. expect(nodes.map((n) => n.name)).toEqual([
  566. 'GET /',
  567. 'GET /computers',
  568. 'POST /computers',
  569. ]); // the `->` include is skipped
  570. expect(references.map((r) => r.referenceName)).toEqual([
  571. 'Application.index',
  572. 'Application.list',
  573. 'Application.save',
  574. ]);
  575. });
  576. it('only runs on Play routes files', () => {
  577. expect(playResolver.extract!('app/Foo.scala', 'GET / controllers.X.y').nodes).toHaveLength(0);
  578. });
  579. });
  580. describe('Play routes file detection', () => {
  581. it('recognizes conf/routes (extensionless) and *.routes as source files', () => {
  582. expect(isPlayRoutesFile('conf/routes')).toBe(true);
  583. expect(isPlayRoutesFile('myapp/conf/routes')).toBe(true);
  584. expect(isPlayRoutesFile('conf/admin.routes')).toBe(true);
  585. expect(isSourceFile('conf/routes')).toBe(true);
  586. expect(isPlayRoutesFile('src/routes.ts')).toBe(false);
  587. });
  588. });
  589. import { goResolver } from '../src/resolution/frameworks/go';
  590. describe('goResolver.extract', () => {
  591. it('extracts route from r.GET', () => {
  592. const src = `r.GET("/users", listUsers)\n`;
  593. const { nodes, references } = goResolver.extract!('main.go', src);
  594. expect(nodes[0].name).toBe('GET /users');
  595. expect(references[0].referenceName).toBe('listUsers');
  596. });
  597. it('extracts route from router.HandleFunc', () => {
  598. const src = `router.HandleFunc("/items", createItem)\n`;
  599. const { nodes, references } = goResolver.extract!('main.go', src);
  600. expect(references[0].referenceName).toBe('createItem');
  601. });
  602. });
  603. import { rustResolver } from '../src/resolution/frameworks/rust';
  604. describe('rustResolver.extract', () => {
  605. it('extracts route from axum .route with get()', () => {
  606. const src = `let app = Router::new().route("/users", get(list_users));\n`;
  607. const { nodes, references } = rustResolver.extract!('main.rs', src);
  608. expect(nodes[0].name).toBe('GET /users');
  609. expect(references[0].referenceName).toBe('list_users');
  610. });
  611. it('extracts every method from a chained axum .route (get().put())', () => {
  612. const src = `let app = Router::new().route("/user", get(get_current_user).put(update_user));\n`;
  613. const { nodes, references } = rustResolver.extract!('main.rs', src);
  614. expect(nodes.map((n) => n.name)).toEqual(['GET /user', 'PUT /user']);
  615. expect(references.map((r) => r.referenceName)).toEqual([
  616. 'get_current_user',
  617. 'update_user',
  618. ]);
  619. });
  620. it('extracts a multi-line axum .route with a namespaced handler', () => {
  621. const src = `
  622. let app = Router::new()
  623. .route(
  624. "/articles/feed",
  625. get(listing::feed_articles),
  626. );
  627. `;
  628. const { nodes, references } = rustResolver.extract!('main.rs', src);
  629. expect(nodes[0].name).toBe('GET /articles/feed');
  630. expect(references[0].referenceName).toBe('feed_articles');
  631. });
  632. it('extracts actix web::resource().route(web::METHOD().to(handler))', () => {
  633. const src = `App::new().service(web::resource("/user/{id}").route(web::get().to(get_user)))\n`;
  634. const { nodes, references } = rustResolver.extract!('main.rs', src);
  635. expect(nodes[0].name).toBe('GET /user/{id}');
  636. expect(references[0].referenceName).toBe('get_user');
  637. });
  638. it('extracts actix web::resource("/").to(handler) (all methods)', () => {
  639. const src = `App::new().service(web::resource("/").to(index))\n`;
  640. const { nodes, references } = rustResolver.extract!('main.rs', src);
  641. expect(nodes[0].name).toBe('ANY /');
  642. expect(references[0].referenceName).toBe('index');
  643. });
  644. it('extracts actix App-level .route("/path", web::METHOD().to(handler))', () => {
  645. const src = `App::new().route("/health", web::get().to(health_check))\n`;
  646. const { nodes, references } = rustResolver.extract!('main.rs', src);
  647. expect(nodes[0].name).toBe('GET /health');
  648. expect(references[0].referenceName).toBe('health_check');
  649. });
  650. });
  651. describe('rustResolver.resolve cargo workspace crates', () => {
  652. it('resolves crate name from workspace member lib.rs', () => {
  653. const workspaceCargo = `
  654. [workspace]
  655. members = ["crates/mytool-core", "crates/mytool-fetcher"]
  656. `;
  657. const coreCargo = `
  658. [package]
  659. name = "mytool-core"
  660. version = "0.1.0"
  661. `;
  662. const libNode: Node = {
  663. id: 'module:crates/mytool-core/src/lib.rs:mytool_core:1',
  664. kind: 'module',
  665. name: 'mytool_core',
  666. qualifiedName: 'crates/mytool-core/src/lib.rs::mytool_core',
  667. filePath: 'crates/mytool-core/src/lib.rs',
  668. language: 'rust',
  669. startLine: 1,
  670. endLine: 1,
  671. startColumn: 0,
  672. endColumn: 0,
  673. updatedAt: Date.now(),
  674. };
  675. const context = {
  676. getNodesInFile: (fp: string) => (fp === 'crates/mytool-core/src/lib.rs' ? [libNode] : []),
  677. getNodesByName: () => [],
  678. getNodesByQualifiedName: () => [],
  679. getNodesByKind: () => [],
  680. fileExists: (p: string) => (
  681. p === 'Cargo.toml' ||
  682. p === 'crates/mytool-core/Cargo.toml' ||
  683. p === 'crates/mytool-core/src/lib.rs'
  684. ),
  685. readFile: (p: string) => {
  686. if (p === 'Cargo.toml') return workspaceCargo;
  687. if (p === 'crates/mytool-core/Cargo.toml') return coreCargo;
  688. return null;
  689. },
  690. getProjectRoot: () => '/test',
  691. getAllFiles: () => [
  692. 'Cargo.toml',
  693. 'crates/mytool-core/Cargo.toml',
  694. 'crates/mytool-core/src/lib.rs',
  695. ],
  696. getNodesByLowerName: () => [],
  697. getImportMappings: () => [],
  698. };
  699. const ref = {
  700. fromNodeId: 'fn:crates/mytool-fetcher/src/main.rs:main:1',
  701. referenceName: 'mytool_core',
  702. referenceKind: 'references' as const,
  703. line: 1,
  704. column: 1,
  705. filePath: 'crates/mytool-fetcher/src/main.rs',
  706. language: 'rust' as const,
  707. };
  708. const result = rustResolver.resolve(ref, context);
  709. expect(result?.targetNodeId).toBe(libNode.id);
  710. expect(result?.resolvedBy).toBe('framework');
  711. // Workspace-manifest hits are unambiguous and must beat name-matcher's
  712. // self-file matches (0.7) so cross-crate `imports` edges materialize.
  713. expect(result?.confidence).toBeGreaterThanOrEqual(0.9);
  714. });
  715. it('resolves crate name from workspace member main.rs when lib.rs is absent', () => {
  716. const workspaceCargo = `
  717. [workspace]
  718. members = [
  719. "crates/mytool-runner",
  720. ]
  721. `;
  722. const runnerCargo = `
  723. [package]
  724. name = "mytool-runner"
  725. version = "0.1.0"
  726. `;
  727. const mainNode: Node = {
  728. id: 'module:crates/mytool-runner/src/main.rs:mytool_runner:1',
  729. kind: 'module',
  730. name: 'mytool_runner',
  731. qualifiedName: 'crates/mytool-runner/src/main.rs::mytool_runner',
  732. filePath: 'crates/mytool-runner/src/main.rs',
  733. language: 'rust',
  734. startLine: 1,
  735. endLine: 1,
  736. startColumn: 0,
  737. endColumn: 0,
  738. updatedAt: Date.now(),
  739. };
  740. const context = {
  741. getNodesInFile: (fp: string) => (fp === 'crates/mytool-runner/src/main.rs' ? [mainNode] : []),
  742. getNodesByName: () => [],
  743. getNodesByQualifiedName: () => [],
  744. getNodesByKind: () => [],
  745. fileExists: (p: string) => (
  746. p === 'Cargo.toml' ||
  747. p === 'crates/mytool-runner/Cargo.toml' ||
  748. p === 'crates/mytool-runner/src/main.rs'
  749. ),
  750. readFile: (p: string) => {
  751. if (p === 'Cargo.toml') return workspaceCargo;
  752. if (p === 'crates/mytool-runner/Cargo.toml') return runnerCargo;
  753. return null;
  754. },
  755. getProjectRoot: () => '/test',
  756. getAllFiles: () => [
  757. 'Cargo.toml',
  758. 'crates/mytool-runner/Cargo.toml',
  759. 'crates/mytool-runner/src/main.rs',
  760. ],
  761. getNodesByLowerName: () => [],
  762. getImportMappings: () => [],
  763. };
  764. const ref = {
  765. fromNodeId: 'fn:crates/mytool-runner/src/main.rs:main:1',
  766. referenceName: 'mytool_runner',
  767. referenceKind: 'references' as const,
  768. line: 1,
  769. column: 1,
  770. filePath: 'crates/mytool-runner/src/main.rs',
  771. language: 'rust' as const,
  772. };
  773. const result = rustResolver.resolve(ref, context);
  774. expect(result?.targetNodeId).toBe(mainNode.id);
  775. expect(result?.resolvedBy).toBe('framework');
  776. });
  777. it('resolves crate name when members uses a glob (crates/*)', () => {
  778. const workspaceCargo = `
  779. [workspace]
  780. members = ["crates/*"]
  781. `;
  782. const fooCargo = `
  783. [package]
  784. name = "mytool-foo"
  785. version = "0.1.0"
  786. `;
  787. const barCargo = `
  788. [package]
  789. name = "mytool-bar"
  790. version = "0.1.0"
  791. `;
  792. const fooLib: Node = {
  793. id: 'module:crates/mytool-foo/src/lib.rs:mytool_foo:1',
  794. kind: 'module',
  795. name: 'mytool_foo',
  796. qualifiedName: 'crates/mytool-foo/src/lib.rs::mytool_foo',
  797. filePath: 'crates/mytool-foo/src/lib.rs',
  798. language: 'rust',
  799. startLine: 1,
  800. endLine: 1,
  801. startColumn: 0,
  802. endColumn: 0,
  803. updatedAt: Date.now(),
  804. };
  805. const barLib: Node = {
  806. id: 'module:crates/mytool-bar/src/lib.rs:mytool_bar:1',
  807. kind: 'module',
  808. name: 'mytool_bar',
  809. qualifiedName: 'crates/mytool-bar/src/lib.rs::mytool_bar',
  810. filePath: 'crates/mytool-bar/src/lib.rs',
  811. language: 'rust',
  812. startLine: 1,
  813. endLine: 1,
  814. startColumn: 0,
  815. endColumn: 0,
  816. updatedAt: Date.now(),
  817. };
  818. const filesByPath: Record<string, string> = {
  819. 'Cargo.toml': workspaceCargo,
  820. 'crates/mytool-foo/Cargo.toml': fooCargo,
  821. 'crates/mytool-bar/Cargo.toml': barCargo,
  822. };
  823. const nodesByFile: Record<string, Node[]> = {
  824. 'crates/mytool-foo/src/lib.rs': [fooLib],
  825. 'crates/mytool-bar/src/lib.rs': [barLib],
  826. };
  827. const dirsByPath: Record<string, string[]> = {
  828. '.': ['crates'],
  829. crates: ['mytool-foo', 'mytool-bar'],
  830. 'crates/mytool-foo': ['src'],
  831. 'crates/mytool-bar': ['src'],
  832. };
  833. const context = {
  834. getNodesInFile: (fp: string) => nodesByFile[fp] ?? [],
  835. getNodesByName: () => [],
  836. getNodesByQualifiedName: () => [],
  837. getNodesByKind: () => [],
  838. fileExists: (p: string) => (
  839. Object.prototype.hasOwnProperty.call(filesByPath, p) ||
  840. Object.prototype.hasOwnProperty.call(nodesByFile, p)
  841. ),
  842. readFile: (p: string) => filesByPath[p] ?? null,
  843. getProjectRoot: () => '/test',
  844. getAllFiles: () => [
  845. 'Cargo.toml',
  846. ...Object.keys(filesByPath).filter((p) => p !== 'Cargo.toml'),
  847. ...Object.keys(nodesByFile),
  848. ],
  849. getNodesByLowerName: () => [],
  850. getImportMappings: () => [],
  851. listDirectories: (rel: string) => dirsByPath[rel] ?? [],
  852. };
  853. const fooRef = {
  854. fromNodeId: 'fn:crates/mytool-bar/src/lib.rs:other:1',
  855. referenceName: 'mytool_foo',
  856. referenceKind: 'references' as const,
  857. line: 1,
  858. column: 1,
  859. filePath: 'crates/mytool-bar/src/lib.rs',
  860. language: 'rust' as const,
  861. };
  862. const barRef = {
  863. fromNodeId: 'fn:crates/mytool-foo/src/lib.rs:other:1',
  864. referenceName: 'mytool_bar',
  865. referenceKind: 'references' as const,
  866. line: 1,
  867. column: 1,
  868. filePath: 'crates/mytool-foo/src/lib.rs',
  869. language: 'rust' as const,
  870. };
  871. expect(rustResolver.resolve(fooRef, context)?.targetNodeId).toBe(fooLib.id);
  872. expect(rustResolver.resolve(barRef, context)?.targetNodeId).toBe(barLib.id);
  873. });
  874. it('resolves crate name when members uses a name glob at root (helix-*)', () => {
  875. const workspaceCargo = `
  876. [workspace]
  877. members = ["helix-*"]
  878. `;
  879. const coreCargo = `
  880. [package]
  881. name = "helix-core"
  882. version = "0.1.0"
  883. `;
  884. const coreLib: Node = {
  885. id: 'module:helix-core/src/lib.rs:helix_core:1',
  886. kind: 'module',
  887. name: 'helix_core',
  888. qualifiedName: 'helix-core/src/lib.rs::helix_core',
  889. filePath: 'helix-core/src/lib.rs',
  890. language: 'rust',
  891. startLine: 1,
  892. endLine: 1,
  893. startColumn: 0,
  894. endColumn: 0,
  895. updatedAt: Date.now(),
  896. };
  897. const filesByPath: Record<string, string> = {
  898. 'Cargo.toml': workspaceCargo,
  899. 'helix-core/Cargo.toml': coreCargo,
  900. };
  901. const nodesByFile: Record<string, Node[]> = {
  902. 'helix-core/src/lib.rs': [coreLib],
  903. };
  904. const dirsByPath: Record<string, string[]> = {
  905. '.': ['helix-core', 'docs', 'target'],
  906. 'helix-core': ['src'],
  907. };
  908. const context = {
  909. getNodesInFile: (fp: string) => nodesByFile[fp] ?? [],
  910. getNodesByName: () => [],
  911. getNodesByQualifiedName: () => [],
  912. getNodesByKind: () => [],
  913. fileExists: (p: string) => (
  914. Object.prototype.hasOwnProperty.call(filesByPath, p) ||
  915. Object.prototype.hasOwnProperty.call(nodesByFile, p)
  916. ),
  917. readFile: (p: string) => filesByPath[p] ?? null,
  918. getProjectRoot: () => '/test',
  919. getAllFiles: () => [
  920. 'Cargo.toml',
  921. ...Object.keys(filesByPath).filter((p) => p !== 'Cargo.toml'),
  922. ...Object.keys(nodesByFile),
  923. ],
  924. getNodesByLowerName: () => [],
  925. getImportMappings: () => [],
  926. listDirectories: (rel: string) => dirsByPath[rel] ?? [],
  927. };
  928. const ref = {
  929. fromNodeId: 'fn:helix-core/src/lib.rs:other:1',
  930. referenceName: 'helix_core',
  931. referenceKind: 'references' as const,
  932. line: 1,
  933. column: 1,
  934. filePath: 'helix-core/src/lib.rs',
  935. language: 'rust' as const,
  936. };
  937. expect(rustResolver.resolve(ref, context)?.targetNodeId).toBe(coreLib.id);
  938. });
  939. });
  940. import { aspnetResolver } from '../src/resolution/frameworks/csharp';
  941. describe('aspnetResolver.extract', () => {
  942. it('extracts route from [HttpGet] attribute', () => {
  943. const src = `
  944. [HttpGet("/users")]
  945. public IActionResult ListUsers()
  946. {
  947. return Ok();
  948. }
  949. `;
  950. const { nodes, references } = aspnetResolver.extract!('UserController.cs', src);
  951. expect(nodes[0].name).toBe('GET /users');
  952. expect(references[0].referenceName).toBe('ListUsers');
  953. });
  954. });
  955. import { vaporResolver } from '../src/resolution/frameworks/swift';
  956. describe('vaporResolver.extract', () => {
  957. it('extracts route from app.get with use:', () => {
  958. const src = `app.get("users", use: listUsers)\n`;
  959. const { nodes, references } = vaporResolver.extract!('routes.swift', src);
  960. expect(nodes[0].name).toBe('GET /users');
  961. expect(references[0].referenceName).toBe('listUsers');
  962. });
  963. it('extracts grouped RouteCollection routes with the group prefix and no path arg', () => {
  964. const src = `
  965. func boot(routes: RoutesBuilder) throws {
  966. let todos = routes.grouped("todos")
  967. todos.get(use: index)
  968. todos.post(use: create)
  969. todos.group(":todoID") { todo in
  970. todo.delete(use: delete)
  971. }
  972. }
  973. `;
  974. const { nodes, references } = vaporResolver.extract!('TodoController.swift', src);
  975. expect(nodes.map((n) => n.name).sort()).toEqual([
  976. 'DELETE /todos/:todoID',
  977. 'GET /todos',
  978. 'POST /todos',
  979. ]);
  980. expect(references.map((r) => r.referenceName).sort()).toEqual([
  981. 'create',
  982. 'delete',
  983. 'index',
  984. ]);
  985. });
  986. it('handles use: self.handler and non-string path segments', () => {
  987. const src = `router.get("users", User.parameter, "edit", use: self.editUserHandler)\n`;
  988. const { nodes, references } = vaporResolver.extract!('UserController.swift', src);
  989. expect(nodes[0].name).toBe('GET /users/edit');
  990. expect(references[0].referenceName).toBe('editUserHandler');
  991. });
  992. it('ignores non-route .get calls that lack use: (e.g. Environment.get)', () => {
  993. const src = `let host = Environment.get("DATABASE_HOST") ?? "localhost"\n`;
  994. const { nodes } = vaporResolver.extract!('configure.swift', src);
  995. expect(nodes).toHaveLength(0);
  996. });
  997. });
  998. import { reactResolver } from '../src/resolution/frameworks/react';
  999. import { svelteResolver } from '../src/resolution/frameworks/svelte';
  1000. describe('reactResolver.extract — React Router', () => {
  1001. it('extracts a v6 <Route path element={<Comp/>}>', () => {
  1002. const src = `<Route path="/users" element={<UsersPage/>}/>`;
  1003. const { nodes, references } = reactResolver.extract!('App.tsx', src);
  1004. const route = nodes.find((n) => n.kind === 'route');
  1005. expect(route?.name).toBe('/users');
  1006. expect(references[0]?.referenceName).toBe('UsersPage');
  1007. });
  1008. it('extracts a v5 <Route path component={Comp}> with attributes in any order', () => {
  1009. const src = `<Route exact path="/login" component={Login} />`;
  1010. const { nodes, references } = reactResolver.extract!('App.jsx', src);
  1011. const route = nodes.find((n) => n.kind === 'route');
  1012. expect(route?.name).toBe('/login');
  1013. expect(references[0]?.referenceName).toBe('Login');
  1014. });
  1015. it('does not treat the <Routes> container as a route', () => {
  1016. const src = `<Routes><Route path="/x" element={<X/>}/></Routes>`;
  1017. const routes = reactResolver.extract!('App.tsx', src).nodes.filter((n) => n.kind === 'route');
  1018. expect(routes).toHaveLength(1);
  1019. expect(routes[0]?.name).toBe('/x');
  1020. });
  1021. it('extracts createBrowserRouter object routes ({ path, element/Component })', () => {
  1022. const src = `const router = createBrowserRouter([
  1023. { path: "/dashboard", element: <Dashboard /> },
  1024. { path: "/login", Component: Login },
  1025. ]);`;
  1026. const { nodes, references } = reactResolver.extract!('router.tsx', src);
  1027. const routes = nodes.filter((n) => n.kind === 'route');
  1028. expect(routes.map((n) => n.name).sort()).toEqual(['/dashboard', '/login']);
  1029. expect(references.map((r) => r.referenceName).sort()).toEqual(['Dashboard', 'Login']);
  1030. });
  1031. it('does not treat config files or a nextjs-pages dir as Next.js routes', () => {
  1032. const cfg = reactResolver.extract!('apps/nextjs-pages/next.config.mjs', 'export default {}');
  1033. expect(cfg.nodes.filter((n) => n.kind === 'route')).toHaveLength(0);
  1034. const vite = reactResolver.extract!('src/pages/vite.config.ts', 'export default {}');
  1035. expect(vite.nodes.filter((n) => n.kind === 'route')).toHaveLength(0);
  1036. // a real page still works
  1037. const page = reactResolver.extract!('src/pages/about.tsx', 'export default function About(){return null}');
  1038. expect(page.nodes.filter((n) => n.kind === 'route').map((n) => n.name)).toEqual(['/about']);
  1039. });
  1040. });
  1041. describe('svelteResolver.extract (smoke)', () => {
  1042. it('returns { nodes, references } shape', () => {
  1043. const result = svelteResolver.extract!('+page.svelte', '');
  1044. expect(result).toHaveProperty('nodes');
  1045. expect(result).toHaveProperty('references');
  1046. });
  1047. });
  1048. // Regression tests: commented-out and docstring route examples must NOT
  1049. // surface as phantom route nodes. These would have failed before the
  1050. // strip-comments wiring (the regex would happily scan comments/docstrings).
  1051. describe('framework extractors ignore commented-out routes', () => {
  1052. it('django: skips line-comment and docstring routes', () => {
  1053. const src = `
  1054. # urls.py example:
  1055. # path('/admin/', AdminPanel.as_view())
  1056. """
  1057. Other routing example:
  1058. path('/users/', UserListView.as_view())
  1059. """
  1060. urlpatterns = [path('/real/', RealView.as_view())]
  1061. `;
  1062. const result = djangoResolver.extract!('app/urls.py', src);
  1063. const urls = result.nodes.map((n) => n.name);
  1064. expect(urls).toEqual(['/real/']);
  1065. });
  1066. it('flask: skips commented-out @app.route', () => {
  1067. const src = `
  1068. # @app.route('/fake')
  1069. # def fake_view():
  1070. # return ''
  1071. @app.route('/real')
  1072. def real_view():
  1073. return ''
  1074. `;
  1075. const { nodes, references } = flaskResolver.extract!('app.py', src);
  1076. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1077. expect(references.map((r) => r.referenceName)).toEqual(['real_view']);
  1078. });
  1079. it('fastapi: skips docstring example routes', () => {
  1080. const src = `
  1081. """
  1082. Example:
  1083. @app.get('/in-docstring')
  1084. async def doc():
  1085. pass
  1086. """
  1087. @app.get('/real')
  1088. async def real_handler():
  1089. return {}
  1090. `;
  1091. const { nodes, references } = fastapiResolver.extract!('main.py', src);
  1092. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1093. expect(references.map((r) => r.referenceName)).toEqual(['real_handler']);
  1094. });
  1095. it('express: skips // and /* */ commented routes', () => {
  1096. const src = `
  1097. // app.get('/fake', fakeHandler);
  1098. /* router.post('/also-fake', otherHandler); */
  1099. app.get('/real', realHandler);
  1100. `;
  1101. const { nodes, references } = expressResolver.extract!('routes.ts', src);
  1102. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1103. expect(references.map((r) => r.referenceName)).toEqual(['realHandler']);
  1104. });
  1105. it('laravel: skips // # and /* */ commented Route::* calls', () => {
  1106. const src = `<?php
  1107. // Route::get('/fake', [FakeController::class, 'index']);
  1108. # Route::get('/also-fake', 'FakeController@show');
  1109. /* Route::post('/another-fake', [X::class, 'y']); */
  1110. Route::get('/real', [RealController::class, 'index']);
  1111. `;
  1112. const { nodes, references } = laravelResolver.extract!('routes/web.php', src);
  1113. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1114. expect(references.map((r) => r.referenceName)).toEqual(['RealController@index']);
  1115. });
  1116. it('rails: skips =begin/=end and # commented routes', () => {
  1117. const src = `
  1118. # get '/fake', to: 'fake#index'
  1119. =begin
  1120. get '/also-fake', to: 'fake#show'
  1121. =end
  1122. get '/real', to: 'real#index'
  1123. `;
  1124. const { nodes, references } = railsResolver.extract!('config/routes.rb', src);
  1125. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1126. expect(references.map((r) => r.referenceName)).toEqual(['real#index']);
  1127. });
  1128. it('spring: skips // and /* */ commented @GetMapping', () => {
  1129. const src = `
  1130. // @GetMapping("/fake")
  1131. // public List<X> fake() { return null; }
  1132. /* @PostMapping("/also-fake")
  1133. public void alsoFake() {} */
  1134. @GetMapping("/real")
  1135. public List<User> listUsers() { return users; }
  1136. `;
  1137. const { nodes, references } = springResolver.extract!('UserController.java', src);
  1138. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1139. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1140. });
  1141. it('go: skips // and /* */ commented router.METHOD calls', () => {
  1142. const src = `
  1143. // r.GET("/fake", fakeHandler)
  1144. /* r.POST("/also-fake", anotherHandler) */
  1145. r.GET("/real", listUsers)
  1146. `;
  1147. const { nodes, references } = goResolver.extract!('main.go', src);
  1148. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1149. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1150. });
  1151. it('rust: skips // and nested /* */ commented .route() calls', () => {
  1152. const src = `
  1153. // .route("/fake", get(fake_handler))
  1154. /* outer /* inner .route("/inner-fake", get(x)) */ still .route("/outer-fake", get(y)) */
  1155. let app = Router::new().route("/real", get(list_users));
  1156. `;
  1157. const { nodes, references } = rustResolver.extract!('main.rs', src);
  1158. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1159. expect(references.map((r) => r.referenceName)).toEqual(['list_users']);
  1160. });
  1161. it('aspnet: skips // and /* */ commented [HttpGet] attributes', () => {
  1162. const src = `
  1163. // [HttpGet("/fake")]
  1164. // public IActionResult Fake() { return Ok(); }
  1165. /* [HttpPost("/also-fake")]
  1166. public IActionResult AlsoFake() { return Ok(); } */
  1167. [HttpGet("/real")]
  1168. public IActionResult ListUsers() { return Ok(); }
  1169. `;
  1170. const { nodes, references } = aspnetResolver.extract!('UserController.cs', src);
  1171. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1172. expect(references.map((r) => r.referenceName)).toEqual(['ListUsers']);
  1173. });
  1174. it('vapor: skips // and /* */ commented app.METHOD calls', () => {
  1175. const src = `
  1176. // app.get("fake", use: fakeHandler)
  1177. /* app.post("also-fake", use: anotherHandler) */
  1178. app.get("real", use: listUsers)
  1179. `;
  1180. const { nodes, references } = vaporResolver.extract!('routes.swift', src);
  1181. expect(nodes.map((n) => n.name)).toEqual(['GET /real']);
  1182. expect(references.map((r) => r.referenceName)).toEqual(['listUsers']);
  1183. });
  1184. it('nestjs: skips // and /* */ commented decorators', () => {
  1185. const src = `
  1186. @Controller('users')
  1187. export class UsersController {
  1188. // @Get('fake')
  1189. // fake() {}
  1190. /* @Post('also-fake')
  1191. alsoFake() {} */
  1192. @Get('real')
  1193. real() {}
  1194. }
  1195. `;
  1196. const { nodes, references } = nestjsResolver.extract!('users.controller.ts', src);
  1197. expect(nodes.map((n) => n.name)).toEqual(['GET /users/real']);
  1198. expect(references.map((r) => r.referenceName)).toEqual(['real']);
  1199. });
  1200. });