1
0

ui-server-api.test.ts 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /**
  2. * The `codegraph ui` read-only JSON API (CG-42).
  3. *
  4. * Everything runs against a real indexed fixture project over a real loopback
  5. * server — no mocks — because the properties worth pinning are the ones that
  6. * only exist end to end: the drift verdict comes from hashing bytes on disk
  7. * against what the index stored, the refusals come from the same chokepoint the
  8. * static server uses, and the caps only matter once a symbol really does have
  9. * hundreds of callers.
  10. *
  11. * The fixture is built to produce each of those: a call chain three deep, a
  12. * test file that reaches it, a type used only as a type, an import that cannot
  13. * resolve, and one deliberately hot function with 500 callers.
  14. */
  15. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  16. import * as http from 'http';
  17. import * as fs from 'fs';
  18. import * as os from 'os';
  19. import * as path from 'path';
  20. import CodeGraph from '../src/index';
  21. import { createGraphApi, startUiServer, type GraphApi, type UiServerHandle } from '../src/ui-server';
  22. interface Response {
  23. status: number;
  24. headers: http.IncomingHttpHeaders;
  25. body: string;
  26. }
  27. let server: UiServerHandle;
  28. let api: GraphApi;
  29. let tempDir: string;
  30. let projectRoot: string;
  31. let viewerDir: string;
  32. /**
  33. * One request against a live server, with the loopback `Host` the boundary
  34. * wants. Written with `http.request` rather than `fetch` so the `Host` header
  35. * is ours to set — undici treats it as forbidden.
  36. */
  37. function requestOn(port: number, requestPath: string, method = 'GET'): Promise<Response> {
  38. return new Promise((resolve, reject) => {
  39. const req = http.request(
  40. {
  41. host: '127.0.0.1',
  42. port,
  43. path: requestPath,
  44. method,
  45. headers: { Host: `127.0.0.1:${port}` },
  46. setHost: false,
  47. },
  48. (res) => {
  49. const chunks: Buffer[] = [];
  50. res.on('data', (c: Buffer) => chunks.push(c));
  51. res.on('end', () =>
  52. resolve({
  53. status: res.statusCode ?? 0,
  54. headers: res.headers,
  55. body: Buffer.concat(chunks).toString('utf-8'),
  56. })
  57. );
  58. }
  59. );
  60. req.on('error', reject);
  61. req.end();
  62. });
  63. }
  64. /** The same, against the main fixture's server. */
  65. function request(requestPath: string, method = 'GET'): Promise<Response> {
  66. return requestOn(server.port, requestPath, method);
  67. }
  68. /**
  69. * Payloads are read as `any` on purpose: these tests assert the JSON contract
  70. * the viewer sees over the wire, so typing them against the server's own
  71. * interfaces would only prove the server agrees with itself.
  72. */
  73. async function getJson(requestPath: string): Promise<any> {
  74. const res = await request(requestPath);
  75. expect(res.headers['content-type']).toBe('application/json; charset=utf-8');
  76. return JSON.parse(res.body);
  77. }
  78. async function getStatusAndJson(requestPath: string): Promise<{ status: number; body: any }> {
  79. const res = await request(requestPath);
  80. expect(res.headers['content-type']).toBe('application/json; charset=utf-8');
  81. return { status: res.status, body: JSON.parse(res.body) };
  82. }
  83. /** Find a symbol in the fixture by name, through the API itself. */
  84. async function idOf(name: string, kind?: string): Promise<string> {
  85. const search = await getJson(`/api/search?q=${encodeURIComponent(name)}`);
  86. const hit = search.results.items.find(
  87. (r: any) => r.name === name && (kind === undefined || r.kind === kind)
  88. );
  89. expect(hit, `no ${kind ?? 'symbol'} named ${name} in the fixture`).toBeTruthy();
  90. return hit.id as string;
  91. }
  92. beforeAll(async () => {
  93. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-ui-api-'));
  94. projectRoot = path.join(tempDir, 'project');
  95. const srcDir = path.join(projectRoot, 'src');
  96. const testsDir = path.join(projectRoot, '__tests__');
  97. fs.mkdirSync(srcDir, { recursive: true });
  98. fs.mkdirSync(testsDir, { recursive: true });
  99. fs.writeFileSync(
  100. path.join(srcDir, 'types.ts'),
  101. `export interface Config {
  102. ttlMs: number;
  103. label: string;
  104. }
  105. export type CacheKey = string;
  106. `
  107. );
  108. fs.writeFileSync(
  109. path.join(srcDir, 'cache.ts'),
  110. `import { Config, CacheKey } from './types';
  111. export class Cache {
  112. private store = new Map<string, string>();
  113. private config: Config;
  114. constructor(config: Config) {
  115. this.config = config;
  116. }
  117. read(key: CacheKey): string | undefined {
  118. return this.store.get(key);
  119. }
  120. write(key: CacheKey, value: string): void {
  121. this.store.set(key, value);
  122. }
  123. }
  124. `
  125. );
  126. fs.writeFileSync(
  127. path.join(srcDir, 'service.ts'),
  128. `import { Cache } from './cache';
  129. import { Config } from './types';
  130. // Not in the index: a package that was never installed here.
  131. import { serialize } from 'some-external-package';
  132. export class Service {
  133. private cache: Cache;
  134. constructor(config: Config) {
  135. this.cache = new Cache(config);
  136. }
  137. load(key: string): string {
  138. const hit = this.cache.read(key);
  139. if (hit !== undefined) return hit;
  140. const fresh = serialize(key);
  141. this.cache.write(key, fresh);
  142. return fresh;
  143. }
  144. }
  145. `
  146. );
  147. fs.writeFileSync(
  148. path.join(srcDir, 'handler.ts'),
  149. `import { Service } from './service';
  150. export function handleRequest(service: Service, key: string): string {
  151. return service.load(key);
  152. }
  153. `
  154. );
  155. // Module-level statements: the engine records them as edges out of the FILE
  156. // node, which is the only reason `/api/entrypoints` can see an executable
  157. // root at all. Nothing else in the fixture runs anything on the way down.
  158. fs.writeFileSync(
  159. path.join(srcDir, 'main.ts'),
  160. `import { Service } from './service';
  161. import { handleRequest } from './handler';
  162. const service = new Service({ ttlMs: 5, label: 'main' });
  163. const first = handleRequest(service, 'boot');
  164. const second = service.load('warm');
  165. export const started = [first, second];
  166. `
  167. );
  168. // 500 callers into one function: the N+1 and capping behaviour only shows up
  169. // at this scale, and the fixture keeps CI honest without needing the engine's
  170. // own index to be present.
  171. const callers = Array.from(
  172. { length: 500 },
  173. (_, i) => `export function caller${i}(): number {\n return hot(${i});\n}`
  174. ).join('\n\n');
  175. fs.writeFileSync(
  176. path.join(srcDir, 'hot.ts'),
  177. `export function hot(n: number): number {
  178. return n * 2;
  179. }
  180. ${callers}
  181. `
  182. );
  183. // CRLF on purpose: tree-sitter numbers rows by `\n`, so a CRLF file must come
  184. // back with the same line numbers the graph recorded — and without the stray
  185. // `\r` rendering at the end of every line. This is what a Windows checkout
  186. // with core.autocrlf looks like, and it is decided by bytes, not by the OS.
  187. fs.writeFileSync(
  188. path.join(srcDir, 'crlf.ts'),
  189. ['export function windowsStyle(n: number): number {', ' return n + 1;', '}', ''].join('\r\n')
  190. );
  191. fs.writeFileSync(
  192. path.join(testsDir, 'service.test.ts'),
  193. `import { Service } from '../src/service';
  194. export function testLoadsThroughCache(): void {
  195. const service = new Service({ ttlMs: 1, label: 'x' });
  196. service.load('k');
  197. }
  198. // Module level, on purpose: a test file that RUNS something must still be
  199. // excluded from the entry points.
  200. testLoadsThroughCache();
  201. `
  202. );
  203. const cg = CodeGraph.initSync(projectRoot, {
  204. config: { include: ['src/**/*.ts', '__tests__/**/*.ts'], exclude: [] },
  205. });
  206. await cg.indexAll();
  207. cg.resolveReferences();
  208. // Hand the index over: the API opens its own read-only connection, which is
  209. // also what happens in production (the CLI never shares an instance).
  210. cg.close();
  211. viewerDir = path.join(tempDir, 'viewer');
  212. fs.mkdirSync(viewerDir, { recursive: true });
  213. fs.writeFileSync(path.join(viewerDir, 'index.html'), '<!doctype html><div id="app"></div>');
  214. api = createGraphApi({ projectRoot });
  215. server = await startUiServer({ projectRoot, viewerDir, port: 0, api: api.handler });
  216. }, 120_000);
  217. afterAll(async () => {
  218. api?.close();
  219. await server?.close();
  220. if (tempDir && fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true, force: true });
  221. });
  222. describe('GET /api', () => {
  223. it('lists the endpoints it answers', async () => {
  224. const body = await getJson('/api');
  225. // Not a blanket claim any more (CG-60): saved trails are the one thing
  226. // this server writes, and it names it rather than implying there is none.
  227. expect(body.readOnly).toBe(false);
  228. expect(body.writes).toEqual(['POST /api/trails', 'DELETE /api/trails/<id>']);
  229. const paths = body.endpoints.map((e: any) => e.path);
  230. expect(paths).toEqual(
  231. expect.arrayContaining([
  232. '/api/stats',
  233. '/api/search',
  234. '/api/node/<id>',
  235. '/api/source',
  236. '/api/file/<path>',
  237. '/api/routes',
  238. ])
  239. );
  240. });
  241. it('404s an unknown endpoint as JSON, never as the app shell', async () => {
  242. const { status, body } = await getStatusAndJson('/api/nope');
  243. expect(status).toBe(404);
  244. expect(body.code).toBe('not-found');
  245. });
  246. it('answers HEAD with the headers and no body', async () => {
  247. const res = await request('/api/stats', 'HEAD');
  248. expect(res.status).toBe(200);
  249. expect(res.headers['content-type']).toBe('application/json; charset=utf-8');
  250. expect(Number(res.headers['content-length'])).toBeGreaterThan(0);
  251. expect(res.body).toBe('');
  252. });
  253. });
  254. describe('GET /api/stats', () => {
  255. it('reports the project, the index state and the graph counts', async () => {
  256. const body = await getJson('/api/stats');
  257. expect(body.project.root).toBe(projectRoot);
  258. expect(body.project.name).toBe('project');
  259. expect(body.index.state).toBe('complete');
  260. expect(body.index.stale).toBe(false);
  261. expect(typeof body.index.lastIndexedAt).toBe('number');
  262. expect(body.index.backend).toBe('node-sqlite');
  263. expect(typeof body.index.extractionVersion).toBe('number');
  264. expect(body.graph.nodes).toBeGreaterThan(0);
  265. expect(body.graph.edges).toBeGreaterThan(0);
  266. expect(body.graph.files).toBeGreaterThanOrEqual(6);
  267. expect(body.graph.nodesByKind.class).toBeGreaterThanOrEqual(2);
  268. expect(body.graph.filesByLanguage.typescript).toBeGreaterThanOrEqual(6);
  269. // The thresholds travel with the data so the viewer's copy cannot drift.
  270. expect(body.thresholds).toEqual({ hub: 40, uncertainBelow: 0.6 });
  271. });
  272. it('reports a blast-radius scale the widest symbol in the index reaches', async () => {
  273. const body = await getJson('/api/stats');
  274. const scale = body.blastScale;
  275. // `hot` is called by 500 distinct functions and nothing else in the fixture
  276. // comes close, so the exact maximum is knowable here.
  277. expect(scale.maxDirect).toBe(500);
  278. // Its radius is at least its own callers; the sample is capped, so the
  279. // count is a floor and the flag says so rather than claiming exhaustive.
  280. expect(scale.maxWithinHops).toBeGreaterThanOrEqual(500);
  281. expect(scale.hops).toBe(3);
  282. expect(scale.sampled).toBeGreaterThan(0);
  283. expect(scale.sampled).toBeLessThanOrEqual(24);
  284. expect(scale.estimated).toBe(true);
  285. });
  286. it('serves the scale from cache — the second call does not re-traverse', async () => {
  287. const first = await getJson('/api/stats');
  288. const started = Date.now();
  289. const second = await getJson('/api/stats');
  290. expect(second.blastScale).toEqual(first.blastScale);
  291. // 24 depth-3 traversals over a 500-caller graph are not free; a cached
  292. // answer is. The margin is wide because this is a smoke test for the
  293. // memo existing at all, not a benchmark.
  294. expect(Date.now() - started).toBeLessThan(250);
  295. });
  296. });
  297. describe('GET /api/search', () => {
  298. it('ranks exact over prefix over substring, and groups by kind', async () => {
  299. const body = await getJson('/api/search?q=Cache');
  300. const first = body.results.items[0];
  301. expect(first.name).toBe('Cache');
  302. expect(first.kind).toBe('class');
  303. expect(first.matchKind).toBe('exact');
  304. const ranks = body.results.items.map((r: any) => r.matchKind);
  305. const order = ['exact', 'prefix', 'substring', 'qualified', 'file', 'related'];
  306. const asNumbers = ranks.map((r: string) => order.indexOf(r));
  307. expect(asNumbers).toEqual([...asNumbers].sort((a, b) => a - b));
  308. // Flattening the groups reproduces the flat ranking, so the palette can use
  309. // either without them disagreeing.
  310. const flattened = body.groups.flatMap((g: any) => g.items.map((i: any) => i.id));
  311. expect(new Set(flattened)).toEqual(new Set(body.results.items.map((r: any) => r.id)));
  312. for (const group of body.groups) expect(group.count).toBe(group.items.length);
  313. });
  314. it('returns a signature and a file:line for every result', async () => {
  315. const body = await getJson('/api/search?q=handleRequest');
  316. const hit = body.results.items.find((r: any) => r.name === 'handleRequest');
  317. expect(hit.file).toBe('src/handler.ts');
  318. expect(hit.line).toBeGreaterThan(0);
  319. expect(hit.endLine).toBeGreaterThanOrEqual(hit.line);
  320. expect(hit.signature).toContain('service');
  321. expect(hit.qualifiedName).toBeTruthy();
  322. expect(hit.language).toBe('typescript');
  323. });
  324. it('finds a mid-name match FTS tokens cannot', async () => {
  325. const body = await getJson('/api/search?q=quest');
  326. const names = body.results.items.map((r: any) => r.name);
  327. expect(names).toContain('handleRequest');
  328. const hit = body.results.items.find((r: any) => r.name === 'handleRequest');
  329. expect(hit.matchKind).toBe('substring');
  330. });
  331. it('honours the kind: filter grammar', async () => {
  332. const body = await getJson('/api/search?q=' + encodeURIComponent('kind:class Cache'));
  333. expect(body.filters.kinds).toEqual(['class']);
  334. expect(body.results.items.every((r: any) => r.kind === 'class')).toBe(true);
  335. });
  336. it('marks test files so the palette can rank them down', async () => {
  337. const body = await getJson('/api/search?q=testLoadsThroughCache');
  338. const hit = body.results.items.find((r: any) => r.name === 'testLoadsThroughCache');
  339. expect(hit.test).toBe(true);
  340. });
  341. it('answers an empty search box with nothing, and a missing q with 400', async () => {
  342. const empty = await getStatusAndJson('/api/search?q=');
  343. expect(empty.status).toBe(200);
  344. expect(empty.body.results.total).toBe(0);
  345. expect(empty.body.groups).toEqual([]);
  346. const missing = await getStatusAndJson('/api/search');
  347. expect(missing.status).toBe(400);
  348. expect(missing.body.code).toBe('bad-request');
  349. });
  350. it('returns an empty result set for a name nothing has', async () => {
  351. const body = await getJson('/api/search?q=zzznotasymbolanywhere');
  352. expect(body.results.total).toBe(0);
  353. });
  354. });
  355. describe('GET /api/node/<id>', () => {
  356. it('returns the symbol, its ancestors and its members in source order', async () => {
  357. const body = await getJson(`/api/node/${await idOf('Cache', 'class')}`);
  358. expect(body.node.name).toBe('Cache');
  359. expect(body.node.kind).toBe('class');
  360. expect(body.node.file).toBe('src/cache.ts');
  361. expect(body.node.lines).toBe(body.node.endLine - body.node.line + 1);
  362. expect(body.node.exported).toBe(true);
  363. // Outermost first: the file, then anything between it and the symbol.
  364. expect(body.ancestors[0].kind).toBe('file');
  365. expect(body.ancestors[0].file).toBe('src/cache.ts');
  366. const members = body.members.items.map((m: any) => m.name);
  367. expect(members).toEqual(expect.arrayContaining(['read', 'write', 'store', 'config']));
  368. const lines = body.members.items.map((m: any) => m.line);
  369. expect(lines).toEqual([...lines].sort((a, b) => a - b));
  370. for (const member of body.members.items) {
  371. expect(member.parentId).toBe(body.node.id);
  372. expect(member.depth).toBe(1);
  373. }
  374. expect(body.members.total).toBe(body.members.shown);
  375. });
  376. it('gives every member its own fan-in and fan-out — the outline is the body', async () => {
  377. const body = await getJson(`/api/node/${await idOf('Cache', 'class')}`);
  378. const byName = new Map(body.members.items.map((m: any) => [m.name, m]));
  379. for (const member of body.members.items) {
  380. expect(typeof member.fanIn).toBe('number');
  381. expect(typeof member.fanOut).toBe('number');
  382. expect(member.fanIn).toBeGreaterThanOrEqual(0);
  383. expect(member.fanOut).toBeGreaterThanOrEqual(0);
  384. }
  385. // `Service.load` calls both, and `Cache` contains them: at least the
  386. // containment edge plus one call each. Without these numbers a 700-line
  387. // class's outline cannot say which member carries weight.
  388. expect((byName.get('read') as any).fanIn).toBeGreaterThanOrEqual(2);
  389. expect((byName.get('write') as any).fanIn).toBeGreaterThanOrEqual(2);
  390. // The class itself calls nothing — its methods do, which is exactly why
  391. // the per-member counts have to come from the members.
  392. expect(body.counts.callees).toBe(0);
  393. expect(body.members.items.some((m: any) => m.fanOut > 0)).toBe(true);
  394. });
  395. it('nests a file outline one level deeper, so a class shows its methods', async () => {
  396. const body = await getJson(`/api/node/${await idOf('cache.ts', 'file')}`);
  397. const byDepth = new Map<number, string[]>();
  398. for (const member of body.members.items) {
  399. byDepth.set(member.depth, [...(byDepth.get(member.depth) ?? []), member.name]);
  400. }
  401. expect(byDepth.get(1)).toContain('Cache');
  402. expect(byDepth.get(2)).toEqual(expect.arrayContaining(['read', 'write']));
  403. });
  404. it('groups incoming edges by the calling symbol, with their call sites', async () => {
  405. const readId = await idOf('read', 'method');
  406. const body = await getJson(`/api/node/${readId}`);
  407. const fromLoad = body.incoming.items.find((r: any) => r.node.name === 'load');
  408. expect(fromLoad, 'Service.load should call Cache.read').toBeTruthy();
  409. expect(fromLoad.node.file).toBe('src/service.ts');
  410. expect(fromLoad.edgeKinds).toContain('calls');
  411. expect(fromLoad.edgeCount).toBeGreaterThanOrEqual(1);
  412. expect(fromLoad.lines.length).toBeGreaterThanOrEqual(1);
  413. expect(fromLoad.lines).toEqual([...fromLoad.lines].sort((a: number, b: number) => a - b));
  414. expect(typeof fromLoad.fanIn).toBe('number');
  415. expect(fromLoad.hub).toBe(false);
  416. });
  417. it('carries every edge attribute the viewer draws with', async () => {
  418. const body = await getJson(`/api/node/${await idOf('read', 'method')}`);
  419. const relation = body.incoming.items.find((r: any) => r.node.name === 'load');
  420. const edge = relation.edges[0];
  421. expect(edge.kind).toBe('calls');
  422. expect(typeof edge.line).toBe('number');
  423. expect(typeof edge.col).toBe('number');
  424. expect(typeof edge.confidence).toBe('number');
  425. expect(typeof edge.resolvedBy).toBe('string');
  426. // Confidence decides the uncertain fold; the group agrees with its edges.
  427. expect(relation.confidence).toBe(
  428. Math.max(...relation.edges.map((e: any) => e.confidence ?? -1))
  429. );
  430. expect(relation.uncertain).toBe(relation.confidence < 0.6);
  431. expect(relation.synthesized).toBe(false);
  432. });
  433. it('groups outgoing edges by the called symbol, ordered by call site', async () => {
  434. const body = await getJson(`/api/node/${await idOf('load', 'method')}`);
  435. const names = body.outgoing.items.map((r: any) => r.node.name);
  436. expect(names).toEqual(expect.arrayContaining(['read', 'write']));
  437. const firstLines = body.outgoing.items
  438. .map((r: any) => r.lines[0])
  439. .filter((l: number | undefined) => l !== undefined);
  440. expect(firstLines).toEqual([...firstLines].sort((a, b) => a - b));
  441. });
  442. it('splits type references out of the callee rail', async () => {
  443. // Type edges attach to the MEMBER that names the type, not to its class:
  444. // `Service`'s constructor is where `Config` and `new Cache(...)` both live,
  445. // which makes it the one place both halves of the split are visible.
  446. const service = await getJson(`/api/node/${await idOf('Service', 'class')}`);
  447. const ctor = service.members.items.find((m: any) => m.name === 'constructor');
  448. const body = await getJson(`/api/node/${ctor.id}`);
  449. const typeNames = body.typesUsed.map((t: any) => t.node.name);
  450. expect(typeNames).toContain('Config');
  451. expect(body.typesUsed.every((t: any) => t.edgeKinds.includes('references'))).toBe(true);
  452. // A type reference is not also a callee row...
  453. expect(body.outgoing.items.map((r: any) => r.node.name)).not.toContain('Config');
  454. // ...but a class reached by any other edge kind still is: `new Cache(...)`
  455. // is an `instantiates` edge, and moving it would hide a real dependency.
  456. const instantiated = body.outgoing.items.find((r: any) => r.node.name === 'Cache');
  457. expect(instantiated).toBeTruthy();
  458. expect(instantiated.edgeKinds).toContain('instantiates');
  459. });
  460. it('summarizes which tests reach the symbol', async () => {
  461. const reached = await getJson(`/api/node/${await idOf('load', 'method')}`);
  462. expect(reached.tests.reached).toBe(true);
  463. expect(reached.tests.hops).toBe(1);
  464. expect(reached.tests.files).toContain('__tests__/service.test.ts');
  465. expect(reached.tests.fileCount).toBeGreaterThanOrEqual(1);
  466. expect(reached.tests.files.length).toBeLessThanOrEqual(6);
  467. expect(reached.tests.exhaustive).toBe(true);
  468. const unreached = await getJson(`/api/node/${await idOf('hot', 'function')}`);
  469. expect(unreached.tests.reached).toBe(false);
  470. expect(unreached.tests.hops).toBeNull();
  471. expect(unreached.tests.files).toEqual([]);
  472. });
  473. it('counts the calls that leave the index instead of hiding them', async () => {
  474. const body = await getJson(`/api/node/${await idOf('load', 'method')}`);
  475. expect(body.outsideIndex.total).toBeGreaterThan(0);
  476. const names = body.outsideIndex.samples.map((s: any) => s.name);
  477. expect(names).toContain('serialize');
  478. for (const sample of body.outsideIndex.samples) {
  479. expect(typeof sample.line).toBe('number');
  480. expect(typeof sample.kind).toBe('string');
  481. }
  482. });
  483. it('summarizes the blast radius at three hops', async () => {
  484. const body = await getJson(`/api/node/${await idOf('read', 'method')}`);
  485. expect(body.blast.hops).toBe(3);
  486. expect(body.blast.direct).toBe(body.counts.callers);
  487. // load → handleRequest / the test both sit inside three hops of Cache.read.
  488. expect(body.blast.withinHops).toBeGreaterThan(body.blast.direct);
  489. expect(body.blast.files).toBeGreaterThanOrEqual(2);
  490. expect(body.blast.testFiles).toBeGreaterThanOrEqual(1);
  491. expect(body.blast.routes).toBe(0);
  492. expect(body.blast.topFiles[0].symbols).toBeGreaterThanOrEqual(1);
  493. });
  494. it('keeps every count equal to the list it labels', async () => {
  495. const body = await getJson(`/api/node/${await idOf('read', 'method')}`);
  496. expect(body.counts.callers).toBe(body.incoming.total);
  497. expect(body.counts.callees).toBe(body.outgoing.total);
  498. expect(body.counts.typesUsed).toBe(body.typesUsed.length);
  499. expect(body.counts.members).toBe(body.members.total);
  500. expect(body.blast.direct).toBe(body.counts.callers);
  501. });
  502. it('reports fan-in, fan-out and the hub flag', async () => {
  503. const quiet = await getJson(`/api/node/${await idOf('write', 'method')}`);
  504. expect(quiet.counts.hub).toBe(false);
  505. expect(quiet.counts.callers).toBeLessThan(40);
  506. expect(quiet.counts.fanIn).toBeGreaterThanOrEqual(quiet.counts.callers);
  507. const hot = await getJson(`/api/node/${await idOf('hot', 'function')}`);
  508. expect(hot.counts.hub).toBe(true);
  509. expect(hot.counts.callers).toBeGreaterThanOrEqual(500);
  510. });
  511. it('flags nothing as drifted while the fixture is untouched', async () => {
  512. const body = await getJson(`/api/node/${await idOf('read', 'method')}`);
  513. expect(body.drift).toBe(false);
  514. });
  515. it('404s an id that names nothing, and 400s an empty one', async () => {
  516. const missing = await getStatusAndJson('/api/node/method:notarealid');
  517. expect(missing.status).toBe(404);
  518. expect(missing.body.code).toBe('not-found');
  519. expect(missing.body.hint).toBeTruthy();
  520. const empty = await getStatusAndJson('/api/node/');
  521. expect(empty.status).toBe(400);
  522. });
  523. });
  524. describe('GET /api/node/<id> — the type hierarchy block', () => {
  525. it('is null for a function, so the block costs a plain symbol nothing', async () => {
  526. const body = await getJson(`/api/node/${await idOf('hot', 'function')}`);
  527. expect(body.hierarchy).toBeNull();
  528. });
  529. it('is null for a class with nothing above or below it', async () => {
  530. const body = await getJson(`/api/node/${await idOf('Cache', 'class')}`);
  531. expect(body.hierarchy).toBeNull();
  532. });
  533. });
  534. describe('GET /api/node/<id> — the busiest symbol', () => {
  535. it('caps the caller list, keeps the true total, and stays fast', async () => {
  536. const hotId = await idOf('hot', 'function');
  537. await request(`/api/node/${hotId}`); // warm the connection and the caches
  538. const started = performance.now();
  539. const res = await request(`/api/node/${hotId}`);
  540. const elapsed = performance.now() - started;
  541. expect(res.status).toBe(200);
  542. const body = JSON.parse(res.body);
  543. expect(body.incoming.total).toBeGreaterThanOrEqual(500);
  544. expect(body.incoming.shown).toBe(300);
  545. expect(body.incoming.truncated).toBe(true);
  546. expect(body.incoming.items).toHaveLength(300);
  547. // Grouped: one row per calling symbol, each carrying its own call sites.
  548. expect(new Set(body.incoming.items.map((r: any) => r.node.id)).size).toBe(300);
  549. expect(body.counts.callers).toBeGreaterThanOrEqual(500);
  550. expect(body.blast.direct).toBe(body.counts.callers);
  551. // 500 callers resolved one query at a time would be nowhere near this.
  552. expect(elapsed).toBeLessThan(100);
  553. });
  554. });
  555. describe('GET /api/source', () => {
  556. it('returns the requested slice with the index line numbering', async () => {
  557. const body = await getJson('/api/source?file=src/cache.ts&from=1&to=3');
  558. expect(body.drift).toBe(false);
  559. expect(body.file).toBe('src/cache.ts');
  560. expect(body.language).toBe('typescript');
  561. expect(body.from).toBe(1);
  562. expect(body.to).toBe(3);
  563. expect(body.lines).toHaveLength(3);
  564. expect(body.lines[0]).toContain("import { Config, CacheKey } from './types'");
  565. expect(body.totalLines).toBeGreaterThan(3);
  566. expect(body.truncated).toBe(false);
  567. });
  568. it('serves the whole file when no range is given', async () => {
  569. const body = await getJson('/api/source?file=src/handler.ts');
  570. expect(body.from).toBe(1);
  571. expect(body.to).toBe(body.totalLines);
  572. expect(body.lines).toHaveLength(body.totalLines);
  573. });
  574. it('slices exactly the lines a symbol claims', async () => {
  575. const node = await getJson(`/api/node/${await idOf('handleRequest', 'function')}`);
  576. const body = await getJson(
  577. `/api/source?file=${node.node.file}&from=${node.node.line}&to=${node.node.endLine}`
  578. );
  579. expect(body.lines[0]).toContain('handleRequest');
  580. expect(body.lines).toHaveLength(node.node.lines);
  581. });
  582. it('carries the classified source beside the lines, one entry per line', async () => {
  583. const body = await getJson('/api/source?file=src/cache.ts&from=1&to=3');
  584. // Highlighting rides with the slice rather than behind its own endpoint:
  585. // the two are only ever wanted together, and a second round-trip would let
  586. // the code block paint unhighlighted source and then reflow it.
  587. expect(body.highlight).toBeTruthy();
  588. expect(body.highlight.classes).toEqual([
  589. 'other',
  590. 'ident',
  591. 'comment',
  592. 'string',
  593. 'keyword',
  594. 'number',
  595. 'type',
  596. 'def',
  597. ]);
  598. expect(body.highlight.lines).toHaveLength(body.lines.length);
  599. // Every line's tokens reproduce that line exactly — the code block renders
  600. // these, not the raw string.
  601. for (let i = 0; i < body.lines.length; i++) {
  602. const rebuilt = body.highlight.lines[i].map(([, text]: [number, string]) => text).join('');
  603. expect(rebuilt).toBe(body.lines[i]);
  604. }
  605. });
  606. it('refuses to slice a file that changed on disk after the last sync', async () => {
  607. const target = path.join(projectRoot, 'src', 'handler.ts');
  608. const original = fs.readFileSync(target);
  609. try {
  610. fs.writeFileSync(target, Buffer.concat([Buffer.from('// a new first line\n'), original]));
  611. const body = await getJson('/api/source?file=src/handler.ts&from=1&to=3');
  612. expect(body.drift).toBe(true);
  613. // The whole point: no slice, rather than a slice of the wrong lines.
  614. expect(body.lines).toBeUndefined();
  615. // And nothing to render it with either — a highlight with no source is
  616. // just a second way to draw the wrong lines.
  617. expect(body.highlight).toBeUndefined();
  618. expect(body.reason).toContain('changed on disk after the last index sync');
  619. // And every screen that renders indexed line ranges is told.
  620. const node = await getJson(`/api/node/${await idOf('handleRequest', 'function')}`);
  621. expect(node.drift).toBe(true);
  622. const file = await getJson('/api/file/src/handler.ts');
  623. expect(file.drift).toBe(true);
  624. } finally {
  625. fs.writeFileSync(target, original);
  626. }
  627. });
  628. it('does not call an identical rewrite drift', async () => {
  629. const target = path.join(projectRoot, 'src', 'handler.ts');
  630. const original = fs.readFileSync(target);
  631. // Same bytes, new mtime — what a checkout or a formatter no-op looks like.
  632. fs.writeFileSync(target, original);
  633. const body = await getJson('/api/source?file=src/handler.ts&from=1&to=2');
  634. expect(body.drift).toBe(false);
  635. expect(body.lines).toHaveLength(2);
  636. });
  637. it('keeps a CRLF file on the index line numbering, without the stray carriage returns', async () => {
  638. const node = await getJson(`/api/node/${await idOf('windowsStyle', 'function')}`);
  639. expect(node.node.file).toBe('src/crlf.ts');
  640. const body = await getJson('/api/source?file=src/crlf.ts');
  641. expect(body.drift).toBe(false);
  642. expect(body.totalLines).toBe(3);
  643. expect(body.lines).toEqual([
  644. 'export function windowsStyle(n: number): number {',
  645. ' return n + 1;',
  646. '}',
  647. ]);
  648. expect(body.lines.some((l: string) => l.includes('\r'))).toBe(false);
  649. // The symbol's indexed range still names its own body.
  650. const slice = await getJson(
  651. `/api/source?file=src/crlf.ts&from=${node.node.line}&to=${node.node.endLine}`
  652. );
  653. expect(slice.lines[0]).toContain('windowsStyle');
  654. });
  655. it('refuses a path that escapes the project', async () => {
  656. const traversal = await getStatusAndJson(
  657. '/api/source?file=' + encodeURIComponent('../../../etc/passwd')
  658. );
  659. expect(traversal.status).toBe(403);
  660. expect(traversal.body.code).toBe('refused');
  661. const absolute = await getStatusAndJson(
  662. '/api/source?file=' + encodeURIComponent('/etc/passwd')
  663. );
  664. expect(absolute.status).toBe(403);
  665. expect(absolute.body.code).toBe('refused');
  666. expect(absolute.body.error).toContain('absolute');
  667. });
  668. it('refuses a NUL byte in the path', async () => {
  669. const { status, body } = await getStatusAndJson(
  670. '/api/source?file=' + encodeURIComponent('src/cache.ts\u0000.png')
  671. );
  672. expect(status).toBe(403);
  673. expect(body.code).toBe('refused');
  674. });
  675. it('404s a file that exists but is not indexed', async () => {
  676. fs.writeFileSync(path.join(projectRoot, 'notes.md'), '# not indexed\n');
  677. const { status, body } = await getStatusAndJson('/api/source?file=notes.md');
  678. expect(status).toBe(404);
  679. expect(body.code).toBe('not-found');
  680. expect(body.hint).toContain('index');
  681. });
  682. it('rejects a range that names nothing', async () => {
  683. const past = await getStatusAndJson('/api/source?file=src/handler.ts&from=99999');
  684. expect(past.status).toBe(400);
  685. expect(past.body.error).toContain('past the end');
  686. const backwards = await getStatusAndJson('/api/source?file=src/handler.ts&from=10&to=4');
  687. expect(backwards.status).toBe(400);
  688. const nonNumeric = await getStatusAndJson('/api/source?file=src/handler.ts&from=abc');
  689. expect(nonNumeric.status).toBe(400);
  690. });
  691. });
  692. describe('GET /api/file/<path>', () => {
  693. it('returns the file record and its outline in source order', async () => {
  694. const body = await getJson('/api/file/src/cache.ts');
  695. expect(body.file.path).toBe('src/cache.ts');
  696. expect(body.file.language).toBe('typescript');
  697. expect(body.file.size).toBeGreaterThan(0);
  698. expect(body.file.contentHash).toMatch(/^[0-9a-f]{64}$/);
  699. expect(body.file.generated).toBe(false);
  700. expect(body.file.test).toBe(false);
  701. expect(body.file.id).toMatch(/^file:/);
  702. expect(body.drift).toBe(false);
  703. const lines = body.outline.items.map((o: any) => o.line);
  704. expect(lines).toEqual([...lines].sort((a, b) => a - b));
  705. const cacheRow = body.outline.items.find((o: any) => o.name === 'Cache');
  706. expect(cacheRow.depth).toBe(0);
  707. expect(cacheRow.parentId).toBeNull();
  708. const readRow = body.outline.items.find((o: any) => o.name === 'read');
  709. expect(readRow.depth).toBe(1);
  710. expect(readRow.parentId).toBe(cacheRow.id);
  711. expect(readRow.fanIn).toBeGreaterThanOrEqual(1);
  712. expect(typeof readRow.fanOut).toBe('number');
  713. // The file node is the subject, not a row; imports have their own rail.
  714. expect(body.outline.items.some((o: any) => o.kind === 'file')).toBe(false);
  715. expect(body.outline.items.some((o: any) => o.kind === 'import')).toBe(false);
  716. });
  717. it('maps imports and imported-by to files', async () => {
  718. const body = await getJson('/api/file/src/cache.ts');
  719. const importedByFiles = body.importedBy.items.map((r: any) => r.file);
  720. expect(importedByFiles).toContain('src/service.ts');
  721. const importFiles = body.imports.items.map((r: any) => r.file);
  722. expect(importFiles).toContain('src/types.ts');
  723. // Never itself: same-file `imports` edges (the import declarations) are dropped.
  724. expect(importFiles).not.toContain('src/cache.ts');
  725. expect(importedByFiles).not.toContain('src/cache.ts');
  726. const typesRow = body.imports.items.find((r: any) => r.file === 'src/types.ts');
  727. expect(typesRow.symbolCount).toBeGreaterThanOrEqual(1);
  728. expect(typesRow.symbols[0].name).toBeTruthy();
  729. expect(typesRow.symbols[0].id).toBeTruthy();
  730. expect(typesRow.test).toBe(false);
  731. });
  732. it('names the imports that never resolved rather than dropping them', async () => {
  733. const body = await getJson('/api/file/src/service.ts');
  734. const names = body.unresolvedImports.map((u: any) => u.name);
  735. expect(names).toContain('some-external-package');
  736. });
  737. it('reports the wider cross-file relationship too', async () => {
  738. const body = await getJson('/api/file/src/cache.ts');
  739. expect(body.dependents).toContain('src/service.ts');
  740. expect(body.dependencies).toContain('src/types.ts');
  741. });
  742. it('says whether the file runs anything at its top level', async () => {
  743. // `src/main.ts` instantiates a Service and calls two functions outside
  744. // every definition — code no outline row can show, because it belongs to
  745. // no symbol. `src/cache.ts` only defines things.
  746. const main = await getJson('/api/file/src/main.ts');
  747. expect(main.topLevel.calls).toBeGreaterThanOrEqual(2);
  748. const cache = await getJson('/api/file/src/cache.ts');
  749. expect(cache.topLevel.calls).toBe(0);
  750. });
  751. it('404s a file that is not in the index and refuses one outside the project', async () => {
  752. const missing = await getStatusAndJson('/api/file/src/nope.ts');
  753. expect(missing.status).toBe(404);
  754. expect(missing.body.code).toBe('not-found');
  755. const outside = await getStatusAndJson(
  756. '/api/file/' + encodeURIComponent('/etc/passwd')
  757. );
  758. expect(outside.status).toBe(403);
  759. expect(outside.body.code).toBe('refused');
  760. });
  761. });
  762. describe('GET /api/routes', () => {
  763. it('says plainly that this project is not a routed app', async () => {
  764. const body = await getJson('/api/routes');
  765. expect(body.routed).toBe(false);
  766. expect(body.entries).toEqual([]);
  767. expect(body.routeCount).toBe(0);
  768. expect(body.shown).toBe(0);
  769. expect(body.truncated).toBe(false);
  770. });
  771. it('refuses a limit the manifest cannot answer truthfully', async () => {
  772. // Below three, the engine's manifest reports every routed project as
  773. // unrouted — a wrong answer, so the parameter is refused instead.
  774. for (const limit of ['0', '2', '-1', 'abc']) {
  775. const { status, body } = await getStatusAndJson(`/api/routes?limit=${limit}`);
  776. expect(status, `limit=${limit}`).toBe(400);
  777. expect(body.code).toBe('bad-request');
  778. }
  779. });
  780. describe('a project that IS routed', () => {
  781. let routedApi: GraphApi;
  782. let routedServer: UiServerHandle;
  783. beforeAll(async () => {
  784. const routedRoot = path.join(tempDir, 'routed');
  785. fs.mkdirSync(path.join(routedRoot, 'src'), { recursive: true });
  786. fs.writeFileSync(
  787. path.join(routedRoot, 'src', 'routes.ts'),
  788. `import express from 'express';
  789. const app = express();
  790. export function listUsers(req: any, res: any): void { res.json([]); }
  791. export function getUser(req: any, res: any): void { res.json({}); }
  792. export function createUser(req: any, res: any): void { res.json({}); }
  793. export function deleteUser(req: any, res: any): void { res.json({}); }
  794. app.get('/users', listUsers);
  795. app.get('/users/:id', getUser);
  796. app.post('/users', createUser);
  797. app.delete('/users/:id', deleteUser);
  798. export default app;
  799. `
  800. );
  801. const routedCg = CodeGraph.initSync(routedRoot, {
  802. config: { include: ['src/**/*.ts'], exclude: [] },
  803. });
  804. await routedCg.indexAll();
  805. routedCg.resolveReferences();
  806. routedCg.close();
  807. routedApi = createGraphApi({ projectRoot: routedRoot });
  808. routedServer = await startUiServer({
  809. projectRoot: routedRoot,
  810. viewerDir,
  811. port: 0,
  812. api: routedApi.handler,
  813. });
  814. }, 120_000);
  815. afterAll(async () => {
  816. routedApi?.close();
  817. await routedServer?.close();
  818. });
  819. it('maps each URL to its handler, with a node id to navigate to', async () => {
  820. const res = await requestOn(routedServer.port, '/api/routes');
  821. const body = JSON.parse(res.body);
  822. expect(body.routed).toBe(true);
  823. expect(body.routeCount).toBe(4);
  824. expect(body.shown).toBe(4);
  825. expect(body.truncated).toBe(false);
  826. expect(body.topHandlerFile).toBe('src/routes.ts');
  827. expect(body.topHandlerFileCount).toBe(4);
  828. const urls = body.entries.map((e: any) => e.url);
  829. expect(urls).toEqual(
  830. expect.arrayContaining(['GET /users', 'GET /users/:id', 'POST /users', 'DELETE /users/:id'])
  831. );
  832. const listUsers = body.entries.find((e: any) => e.url === 'GET /users');
  833. expect(listUsers.handler).toBe('listUsers');
  834. expect(listUsers.handlerKind).toBe('function');
  835. expect(listUsers.file).toBe('src/routes.ts');
  836. expect(listUsers.line).toBeGreaterThan(0);
  837. // The manifest carries no ids of its own; resolving them is what makes a
  838. // route row clickable, so it has to actually resolve.
  839. expect(listUsers.handlerId).toBeTruthy();
  840. const handler = JSON.parse(
  841. (await requestOn(routedServer.port, `/api/node/${listUsers.handlerId}`)).body
  842. );
  843. expect(handler.node.name).toBe('listUsers');
  844. });
  845. it('offers its routes as entry points, ahead of anything derived', async () => {
  846. const res = await requestOn(routedServer.port, '/api/entrypoints');
  847. const body = JSON.parse(res.body);
  848. expect(body.routes.routed).toBe(true);
  849. expect(body.routes.routeCount).toBe(4);
  850. const urls = body.routes.items.items.map((e: any) => e.url);
  851. expect(urls).toEqual(
  852. expect.arrayContaining(['GET /users', 'GET /users/:id', 'POST /users', 'DELETE /users/:id'])
  853. );
  854. // A route row has to be navigable, or it is a label.
  855. expect(body.routes.items.items.every((e: any) => e.handlerId)).toBe(true);
  856. });
  857. it('honours the limit and says when it cut the list', async () => {
  858. const res = await requestOn(routedServer.port, '/api/routes?limit=3');
  859. const body = JSON.parse(res.body);
  860. expect(body.routed).toBe(true);
  861. expect(body.entries).toHaveLength(3);
  862. expect(body.shown).toBe(3);
  863. expect(body.truncated).toBe(true);
  864. // The headline count is the whole graph's, not the page's.
  865. expect(body.routeCount).toBe(4);
  866. });
  867. });
  868. });
  869. /**
  870. * The acceptance bar from the issue, against the engine's OWN index rather than
  871. * a fixture: `LRUCache.get` in `src/resolution/lru-cache.ts`, 500+ callers.
  872. *
  873. * `.codegraph/` is gitignored, so this only runs on a machine that has indexed
  874. * this repository. The fixture test above covers the same properties in CI; this
  875. * one is the check against the real, messy graph the number came from.
  876. */
  877. describe.runIf(CodeGraph.isInitialized(path.resolve(__dirname, '..')))(
  878. "the engine's own busiest symbol",
  879. () => {
  880. const repoRoot = path.resolve(__dirname, '..');
  881. let repoApi: GraphApi;
  882. let repoServer: UiServerHandle;
  883. beforeAll(async () => {
  884. repoApi = createGraphApi({ projectRoot: repoRoot });
  885. repoServer = await startUiServer({
  886. projectRoot: repoRoot,
  887. viewerDir,
  888. port: 0,
  889. api: repoApi.handler,
  890. });
  891. });
  892. afterAll(async () => {
  893. repoApi?.close();
  894. await repoServer?.close();
  895. });
  896. const repoGet = (requestPath: string): Promise<Response> =>
  897. requestOn(repoServer.port, requestPath);
  898. it('answers in under 100 ms with grouped, capped lists and correct counts', async () => {
  899. const search = JSON.parse(
  900. (await repoGet('/api/search?q=' + encodeURIComponent('LRUCache.get'))).body
  901. );
  902. const hit = search.results.items.find(
  903. (r: any) => r.name === 'get' && r.file.endsWith('src/resolution/lru-cache.ts')
  904. );
  905. expect(hit, 'LRUCache.get should be in the engine\'s own index').toBeTruthy();
  906. await repoGet(`/api/node/${hit.id}`); // warm
  907. const started = performance.now();
  908. const res = await repoGet(`/api/node/${hit.id}`);
  909. const elapsed = performance.now() - started;
  910. expect(res.status).toBe(200);
  911. const body = JSON.parse(res.body);
  912. expect(body.counts.fanIn).toBeGreaterThanOrEqual(500);
  913. expect(body.counts.hub).toBe(true);
  914. // Grouped by calling symbol, so the row count is the distinct-caller
  915. // count, never the edge count.
  916. expect(body.incoming.items).toHaveLength(body.incoming.shown);
  917. expect(body.incoming.shown).toBeLessThanOrEqual(300);
  918. expect(body.incoming.shown).toBe(Math.min(300, body.incoming.total));
  919. expect(body.incoming.truncated).toBe(body.incoming.total > 300);
  920. expect(new Set(body.incoming.items.map((r: any) => r.node.id)).size).toBe(
  921. body.incoming.shown
  922. );
  923. const edgesInRows = body.incoming.items.reduce(
  924. (sum: number, r: any) => sum + r.edgeCount,
  925. 0
  926. );
  927. expect(edgesInRows).toBeLessThanOrEqual(body.counts.fanIn);
  928. expect(body.blast.direct).toBe(body.counts.callers);
  929. expect(body.tests.reached).toBe(true);
  930. expect(elapsed).toBeLessThan(100);
  931. });
  932. }
  933. );
  934. describe('GET /api/entrypoints', () => {
  935. it('finds the file that runs something, and reports what it reaches', async () => {
  936. const body = await getJson('/api/entrypoints');
  937. const files = body.files.items.map((f: any) => f.file);
  938. expect(files).toContain('src/main.ts');
  939. const main = body.files.items.find((f: any) => f.file === 'src/main.ts');
  940. expect(main.kind).toBe('file');
  941. expect(main.id).toMatch(/^file:/);
  942. // `new Service(...)`, `handleRequest(...)` and `service.load(...)` all sit
  943. // at module level.
  944. expect(main.calls).toBeGreaterThanOrEqual(2);
  945. // It imports from service.ts and handler.ts, so it wires files together.
  946. expect(main.reaches).toBeGreaterThanOrEqual(2);
  947. expect(typeof main.dependents).toBe('number');
  948. });
  949. it('leaves test files out — "where do I start" never means a test', async () => {
  950. const body = await getJson('/api/entrypoints');
  951. for (const file of body.files.items) expect(file.test).toBe(false);
  952. // The fixture's test file calls its own helper at module level, so it IS a
  953. // candidate by the raw graph signal and is excluded deliberately.
  954. expect(body.files.items.map((f: any) => f.file)).not.toContain(
  955. '__tests__/service.test.ts'
  956. );
  957. for (const hub of body.hubs.items) expect(hub.test).toBe(false);
  958. });
  959. it('ranks the most depended-on symbols as hubs, with their dependent counts', async () => {
  960. const body = await getJson('/api/entrypoints');
  961. const hot = body.hubs.items.find((h: any) => h.name === 'hot');
  962. expect(hot, 'the 500-caller function should top the hubs').toBeTruthy();
  963. expect(hot.dependents).toBe(500);
  964. expect(body.hubs.items[0].name).toBe('hot');
  965. const counts = body.hubs.items.map((h: any) => h.dependents);
  966. expect(counts).toEqual([...counts].sort((a: number, b: number) => b - a));
  967. // A file or a bare import is structure, not somewhere to start reading.
  968. for (const hub of body.hubs.items) {
  969. expect(['file', 'import', 'export', 'parameter']).not.toContain(hub.kind);
  970. }
  971. });
  972. it('says a project without routes is not routed rather than failing', async () => {
  973. const body = await getJson('/api/entrypoints');
  974. expect(body.routes.routed).toBe(false);
  975. expect(body.routes.items.items).toEqual([]);
  976. expect(body.routes.routeCount).toBe(0);
  977. });
  978. it('honours limit, and keeps every list within it', async () => {
  979. const body = await getJson('/api/entrypoints?limit=1');
  980. expect(body.files.items.length).toBeLessThanOrEqual(1);
  981. expect(body.hubs.items.length).toBe(1);
  982. expect(body.hubs.total).toBeGreaterThanOrEqual(body.hubs.items.length);
  983. const bad = await getStatusAndJson('/api/entrypoints?limit=0');
  984. expect(bad.status).toBe(400);
  985. expect(bad.body.code).toBe('bad-request');
  986. });
  987. });
  988. describe('GET /api/nodes', () => {
  989. it('answers a batch of ids in the order asked, and says which are missing', async () => {
  990. const cacheId = await idOf('Cache', 'class');
  991. const loadId = await idOf('load', 'method');
  992. const body = await getJson(
  993. `/api/nodes?id=${encodeURIComponent(loadId)}&id=${encodeURIComponent(cacheId)}&id=method%3Anot-a-real-id`
  994. );
  995. expect(body.items.map((n: any) => n.id)).toEqual([loadId, cacheId]);
  996. expect(body.items[0].name).toBe('load');
  997. expect(body.items[1].name).toBe('Cache');
  998. expect(body.missing).toEqual(['method:not-a-real-id']);
  999. // The REF shape, not the Symbol view payload: a trail redraws six names,
  1000. // not six rail sets.
  1001. expect(body.items[0].incoming).toBeUndefined();
  1002. expect(body.items[0].file).toBe('src/service.ts');
  1003. });
  1004. it('de-duplicates ids rather than answering twice', async () => {
  1005. const cacheId = await idOf('Cache', 'class');
  1006. const encoded = encodeURIComponent(cacheId);
  1007. const body = await getJson(`/api/nodes?id=${encoded}&id=${encoded}`);
  1008. expect(body.items).toHaveLength(1);
  1009. });
  1010. it('refuses an empty or oversized request with guidance', async () => {
  1011. const none = await getStatusAndJson('/api/nodes');
  1012. expect(none.status).toBe(400);
  1013. expect(none.body.hint).toContain('id=');
  1014. const ids = Array.from({ length: 61 }, (_, i) => `id=method%3A${i}`).join('&');
  1015. const many = await getStatusAndJson(`/api/nodes?${ids}`);
  1016. expect(many.status).toBe(400);
  1017. expect(many.body.error).toContain('Too many ids');
  1018. });
  1019. });
  1020. describe('an index that is not there', () => {
  1021. it('answers with the same guidance the CLI prints, not a stack trace', async () => {
  1022. const emptyRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-ui-noindex-'));
  1023. const detached = createGraphApi({ projectRoot: emptyRoot });
  1024. const detachedServer = await startUiServer({
  1025. projectRoot: emptyRoot,
  1026. viewerDir,
  1027. port: 0,
  1028. api: detached.handler,
  1029. });
  1030. try {
  1031. const res = await requestOn(detachedServer.port, '/api/stats');
  1032. expect(res.status).toBe(503);
  1033. const body = JSON.parse(res.body);
  1034. expect(body.code).toBe('no-index');
  1035. expect(body.error).toContain('No CodeGraph index found');
  1036. expect(body.hint).toContain('codegraph init');
  1037. expect(body.error).not.toContain(' at ');
  1038. } finally {
  1039. detached.close();
  1040. await detachedServer.close();
  1041. fs.rmSync(emptyRoot, { recursive: true, force: true });
  1042. }
  1043. });
  1044. });