ui-server-api.test.ts 47 KB

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