ui-package.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. /**
  2. * `@colbymchenry/codegraph-ui` — the package's own test (task CG-61).
  3. *
  4. * A minimal Svelte host mounts the three headline components from the package
  5. * entry against a MOCK adapter and asserts what lands in the document. That is
  6. * the whole promise of the package in one file: CodeGraph Pro renders these
  7. * same components over its own in-process engine reads, so if a screen can be
  8. * drawn from an object literal here, it can be drawn from a graph there.
  9. *
  10. * The import is `ui/src/index.ts` — the package entry itself, not the
  11. * components one by one — so a name dropped from the public surface fails here
  12. * rather than in the Pro app.
  13. *
  14. * Everything below is deliberately about the SEAM, not about the screens:
  15. * layout, geometry and the rails have their own suites (`ui-symbol-model`,
  16. * `ui-flow-model`, `ui-map-model`). What is being proved here is that no
  17. * component reaches past the adapter for anything.
  18. */
  19. import { readFileSync } from 'node:fs';
  20. import { join } from 'node:path';
  21. import { flushSync, mount, unmount } from 'svelte';
  22. import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
  23. import {
  24. ArchitectureMap,
  25. CodegraphUi,
  26. FlowStrip,
  27. SearchPalette,
  28. SymbolView,
  29. TrailBar,
  30. TypeHierarchy,
  31. createHttpAdapter,
  32. fileHref,
  33. flowHref,
  34. getGraphAdapter,
  35. hashNavigation,
  36. live,
  37. mapHref,
  38. setGraphAdapter,
  39. setNavigationDriver,
  40. symbolHref,
  41. trail,
  42. type GraphAdapter,
  43. type NavigationDriver,
  44. type WireFlowPayload,
  45. type WireMapPayload,
  46. type WireNodeRef,
  47. type WireSource,
  48. type WireStats,
  49. type WireHierarchy,
  50. type WireSymbolPayload,
  51. } from '../ui/src/index';
  52. /* ---------------------------------------------------------------- fixtures */
  53. const ROOT = join(import.meta.dirname, '..');
  54. function nodeRef(overrides: Partial<WireNodeRef> = {}): WireNodeRef {
  55. return {
  56. id: 'function:parseToken@src/auth/token.ts:12',
  57. kind: 'function',
  58. name: 'parseToken',
  59. qualifiedName: 'parseToken',
  60. file: 'src/auth/token.ts',
  61. line: 12,
  62. endLine: 18,
  63. language: 'typescript',
  64. test: false,
  65. ...overrides,
  66. };
  67. }
  68. const CALLER = nodeRef({
  69. id: 'function:handleCallback@src/auth/callback.ts:40',
  70. name: 'handleCallback',
  71. qualifiedName: 'handleCallback',
  72. file: 'src/auth/callback.ts',
  73. line: 40,
  74. endLine: 60,
  75. });
  76. const CALLEE = nodeRef({
  77. id: 'function:decodeJwt@src/auth/jwt.ts:3',
  78. name: 'decodeJwt',
  79. qualifiedName: 'decodeJwt',
  80. file: 'src/auth/jwt.ts',
  81. line: 3,
  82. endLine: 9,
  83. });
  84. const SYMBOL: WireSymbolPayload = {
  85. node: {
  86. ...nodeRef(),
  87. startColumn: 0,
  88. endColumn: 1,
  89. lines: 7,
  90. exported: true,
  91. },
  92. ancestors: [nodeRef({ id: 'file:src/auth/token.ts', kind: 'file', name: 'token.ts' })],
  93. members: { total: 0, shown: 0, truncated: false, items: [] },
  94. incoming: {
  95. total: 1,
  96. shown: 1,
  97. truncated: false,
  98. items: [
  99. {
  100. node: CALLER,
  101. edgeKinds: ['calls'],
  102. edges: [{ kind: 'calls', line: 44, col: 6, confidence: 1 }],
  103. edgeCount: 1,
  104. lines: [44],
  105. confidence: 1,
  106. uncertain: false,
  107. synthesized: false,
  108. },
  109. ],
  110. },
  111. outgoing: {
  112. total: 1,
  113. shown: 1,
  114. truncated: false,
  115. items: [
  116. {
  117. node: CALLEE,
  118. edgeKinds: ['calls'],
  119. edges: [{ kind: 'calls', line: 14, col: 10, confidence: 1 }],
  120. edgeCount: 1,
  121. lines: [14],
  122. confidence: 1,
  123. uncertain: false,
  124. synthesized: false,
  125. },
  126. ],
  127. },
  128. typesUsed: [],
  129. hierarchy: null,
  130. counts: { callers: 1, callees: 1, typesUsed: 0, fanIn: 1, fanOut: 1, members: 0, hub: false },
  131. tests: { reached: false, hops: null, fileCount: 0, files: [], exhaustive: true, hopsSearched: 3 },
  132. outsideIndex: { total: 0, byKind: {}, samples: [] },
  133. blast: {
  134. direct: 1,
  135. withinHops: 2,
  136. hops: 3,
  137. files: 2,
  138. testFiles: 0,
  139. routes: 0,
  140. topFiles: [{ file: 'src/auth/callback.ts', symbols: 1, test: false }],
  141. },
  142. drift: false,
  143. };
  144. const SOURCE_LINES = [
  145. 'export function parseToken(raw: string): Token {',
  146. ' // Normalize expiry before anything else reads it.',
  147. ' const claims = decodeJwt(raw);',
  148. ' return { ...claims, expiresAt: claims.exp * 1000 };',
  149. '}',
  150. ];
  151. const SOURCE: WireSource = {
  152. file: 'src/auth/token.ts',
  153. language: 'typescript',
  154. drift: false,
  155. showing: 'indexed',
  156. contentHash: 'abc123',
  157. indexedAt: 1_700_000_000_000,
  158. generated: false,
  159. totalLines: 40,
  160. from: 12,
  161. to: 18,
  162. lines: SOURCE_LINES,
  163. };
  164. const FLOW: WireFlowPayload = {
  165. query: { kind: 'directed', from: 'handleCallback', to: 'decodeJwt', symbols: [] },
  166. flows: [
  167. {
  168. id: 'flow-1',
  169. label: 'handleCallback → decodeJwt',
  170. partial: false,
  171. boundary: null,
  172. hops: [
  173. {
  174. node: CALLER,
  175. edge: null,
  176. callRef: { line: 44, col: 6, name: 'parseToken', targetId: SYMBOL.node.id, backwards: false },
  177. source: {
  178. file: 'src/auth/callback.ts',
  179. language: 'typescript',
  180. from: 44,
  181. to: 46,
  182. lines: [' const token = parseToken(raw);'],
  183. drift: false,
  184. },
  185. },
  186. {
  187. node: nodeRef(),
  188. edge: {
  189. kind: 'calls',
  190. line: 44,
  191. label: 'calls',
  192. upward: false,
  193. uncertain: false,
  194. synthesized: false,
  195. },
  196. callRef: null,
  197. source: {
  198. file: 'src/auth/token.ts',
  199. language: 'typescript',
  200. from: 12,
  201. to: 14,
  202. lines: SOURCE_LINES.slice(0, 3),
  203. drift: false,
  204. },
  205. },
  206. ],
  207. },
  208. ],
  209. ambiguous: [],
  210. unresolved: [],
  211. reason: null,
  212. index: { lastIndexedAt: 1_700_000_000_000, edges: 4, files: 3 },
  213. timing: { elapsedMs: 2 },
  214. };
  215. const MAP: WireMapPayload = {
  216. root: 'src',
  217. depth: 1,
  218. roots: [{ root: 'src', label: 'src', files: 3 }],
  219. modules: [
  220. {
  221. id: 'src/auth',
  222. label: 'auth',
  223. files: 2,
  224. symbols: 6,
  225. languages: [{ language: 'typescript', files: 2 }],
  226. test: false,
  227. facade: false,
  228. fileList: { total: 2, shown: 2, truncated: false, items: ['src/auth/token.ts', 'src/auth/callback.ts'] },
  229. },
  230. {
  231. id: 'src/http',
  232. label: 'http',
  233. files: 1,
  234. symbols: 3,
  235. languages: [{ language: 'typescript', files: 1 }],
  236. test: false,
  237. facade: false,
  238. fileList: { total: 1, shown: 1, truncated: false, items: ['src/http/server.ts'] },
  239. },
  240. ],
  241. links: [
  242. {
  243. source: 'src/http',
  244. target: 'src/auth',
  245. count: 9,
  246. declared: 7,
  247. byKind: [{ kind: 'calls', count: 9 }],
  248. topPairs: [{ from: 'src/http/server.ts', to: 'src/auth/token.ts', count: 9, declared: 7 }],
  249. },
  250. ],
  251. cycles: { total: 0, shown: 0, truncated: false, items: [] },
  252. excluded: { uncertainEdges: 0, confidenceBelow: 0.6 },
  253. index: { lastIndexedAt: 1_700_000_000_000, edges: 9, files: 3 },
  254. timing: { elapsedMs: 1, cached: false },
  255. };
  256. const STATS: WireStats = {
  257. project: { root: '/tmp/demo', name: 'demo' },
  258. index: {
  259. state: 'ready',
  260. lastIndexedAt: 1_700_000_000_000,
  261. stale: false,
  262. version: '1.0.0',
  263. extractionVersion: 1,
  264. backend: 'node-sqlite',
  265. journalMode: 'wal',
  266. pendingReferences: 0,
  267. generatedFiles: 0,
  268. watching: false,
  269. watcherDegraded: false,
  270. },
  271. graph: {
  272. nodes: 9,
  273. edges: 9,
  274. files: 3,
  275. nodesByKind: { function: 9 },
  276. edgesByKind: { calls: 9 },
  277. filesByLanguage: { typescript: 3 },
  278. dbSizeBytes: 1024,
  279. walSizeBytes: 0,
  280. },
  281. frameworks: [],
  282. thresholds: { hub: 40, uncertainBelow: 0.6 },
  283. blastScale: { maxDirect: 20, maxWithinHops: 60, hops: 3, sampled: 24, estimated: true },
  284. };
  285. /* ------------------------------------------------------------ mock adapter */
  286. /** Every method the components can reach, and a record of which ones they did. */
  287. function mockAdapter(): { adapter: GraphAdapter; calls: string[] } {
  288. const calls: string[] = [];
  289. const seen = <T>(name: string, value: T): Promise<T> => {
  290. calls.push(name);
  291. return Promise.resolve(value);
  292. };
  293. const adapter: GraphAdapter = {
  294. stats: () => seen('stats', STATS),
  295. search: () =>
  296. seen('search', {
  297. query: '',
  298. text: '',
  299. filters: { kinds: [], languages: [], paths: [], names: [] },
  300. results: { total: 0, shown: 0, truncated: false, items: [] },
  301. groups: [],
  302. }),
  303. node: (id) => {
  304. calls.push(`node:${id}`);
  305. return Promise.resolve(SYMBOL);
  306. },
  307. nodes: () => seen('nodes', { items: [], missing: [] }),
  308. source: (request) => {
  309. calls.push(`source:${request.file}`);
  310. return Promise.resolve(SOURCE);
  311. },
  312. file: () =>
  313. seen('file', {
  314. file: {
  315. path: 'src/auth/token.ts',
  316. language: 'typescript',
  317. size: 900,
  318. modifiedAt: 0,
  319. indexedAt: 0,
  320. contentHash: 'abc123',
  321. nodeCount: 3,
  322. generated: false,
  323. test: false,
  324. errors: [],
  325. id: 'file:src/auth/token.ts',
  326. },
  327. topLevel: { calls: 0 },
  328. drift: false,
  329. outline: { total: 0, shown: 0, truncated: false, items: [] },
  330. imports: { total: 0, shown: 0, truncated: false, items: [] },
  331. importedBy: { total: 0, shown: 0, truncated: false, items: [] },
  332. unresolvedImports: [],
  333. dependencies: [],
  334. dependents: [],
  335. }),
  336. fileCode: () =>
  337. seen('fileCode', {
  338. file: {
  339. path: 'src/auth/token.ts',
  340. language: 'typescript',
  341. size: 900,
  342. indexedAt: 0,
  343. contentHash: 'abc123',
  344. generated: false,
  345. test: false,
  346. errors: [],
  347. id: 'file:src/auth/token.ts',
  348. totalLines: 40,
  349. },
  350. drift: false,
  351. outline: { total: 0, shown: 0, truncated: false, items: [] },
  352. calls: { total: 0, shown: 0, truncated: false, items: [] },
  353. outside: { total: 0, shown: 0, truncated: false, items: [] },
  354. intraFileCalls: 0,
  355. timing: { elapsedMs: 1 },
  356. }),
  357. flow: () => seen('flow', FLOW),
  358. map: () => seen('map', MAP),
  359. routes: () =>
  360. seen('routes', {
  361. routed: false,
  362. routeCount: 0,
  363. shown: 0,
  364. truncated: false,
  365. topHandlerFile: null,
  366. topHandlerFileCount: 0,
  367. entries: [],
  368. }),
  369. entryPoints: () =>
  370. seen('entryPoints', {
  371. frameworks: [],
  372. routes: { routed: false, routeCount: 0, items: { total: 0, shown: 0, truncated: false, items: [] } },
  373. files: { total: 0, shown: 0, truncated: false, items: [] },
  374. tests: { total: 0, shown: 0, truncated: false, items: [] },
  375. hubs: { total: 0, shown: 0, truncated: false, items: [] },
  376. index: { lastIndexedAt: null, files: 3 },
  377. timing: { elapsedMs: 1, cached: false },
  378. }),
  379. deadCode: () =>
  380. seen('deadCode', {
  381. rows: { total: 0, shown: 0, truncated: false, items: [] },
  382. groups: [],
  383. candidates: 0,
  384. excluded: [],
  385. excludedTotal: 0,
  386. kinds: ['function'],
  387. includeExported: false,
  388. includeTests: false,
  389. includeGenerated: false,
  390. bounded: false,
  391. corroborated: true,
  392. timing: { elapsedMs: 1 },
  393. }),
  394. // Deliberately no `events`: a host without a live channel is the normal
  395. // case, and nothing may poll in its absence.
  396. };
  397. return { adapter, calls };
  398. }
  399. /* ----------------------------------------------------------------- harness */
  400. let host: HTMLDivElement;
  401. let mounted: Record<string, unknown> | null = null;
  402. /** jsdom has none of the observers a canvas library expects. */
  403. beforeAll(() => {
  404. class NoopObserver {
  405. observe(): void {}
  406. unobserve(): void {}
  407. disconnect(): void {}
  408. }
  409. const globals = globalThis as Record<string, unknown>;
  410. globals.ResizeObserver ??= NoopObserver;
  411. globals.IntersectionObserver ??= NoopObserver;
  412. globals.MutationObserver ??= NoopObserver;
  413. globals.requestAnimationFrame ??= (fn: FrameRequestCallback) =>
  414. setTimeout(() => fn(0), 0) as unknown as number;
  415. globals.cancelAnimationFrame ??= (handle: number) => clearTimeout(handle);
  416. // jsdom's own `matchMedia` is a stub that is not callable here, and Svelte's
  417. // `MediaQuery` (which `@xyflow/svelte`'s store constructs eagerly) calls it
  418. // the moment a canvas mounts. Replace it outright rather than guarding.
  419. const media = (query: string) => ({
  420. media: query,
  421. matches: false,
  422. onchange: null,
  423. addEventListener() {},
  424. removeEventListener() {},
  425. addListener() {},
  426. removeListener() {},
  427. dispatchEvent: () => false,
  428. });
  429. Object.defineProperty(window, 'matchMedia', { configurable: true, writable: true, value: media });
  430. globals.matchMedia = media;
  431. if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = () => {};
  432. });
  433. beforeEach(() => {
  434. host = document.createElement('div');
  435. document.body.appendChild(host);
  436. trail.clear();
  437. });
  438. afterEach(() => {
  439. if (mounted) {
  440. void unmount(mounted);
  441. mounted = null;
  442. }
  443. host.remove();
  444. setGraphAdapter(null);
  445. setNavigationDriver(null);
  446. });
  447. /**
  448. * Mount a component and let its data effects settle.
  449. *
  450. * Every screen fetches inside an `$effect`, so a render is not finished until
  451. * the promise the adapter returned has resolved and the follow-up render has
  452. * flushed. Two macrotask turns cover the deepest chain any of them has (the
  453. * Symbol view: node, then its source).
  454. */
  455. async function render(
  456. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  457. component: any,
  458. props: Record<string, unknown>
  459. ): Promise<void> {
  460. mounted = mount(component, { target: host, props }) as Record<string, unknown>;
  461. for (let turn = 0; turn < 4; turn += 1) {
  462. await new Promise((resolve) => setTimeout(resolve, 0));
  463. flushSync();
  464. }
  465. }
  466. describe('@colbymchenry/codegraph-ui — a host renders the package', () => {
  467. it('SymbolView draws callers, source and the callee rail from a mock adapter', async () => {
  468. const { adapter, calls } = mockAdapter();
  469. setGraphAdapter(adapter);
  470. await render(SymbolView, { id: SYMBOL.node.id, line: null });
  471. // It asked the adapter, by id, and it asked for the symbol's own slice.
  472. expect(calls).toContain(`node:${SYMBOL.node.id}`);
  473. expect(calls).toContain('source:src/auth/token.ts');
  474. const text = host.textContent ?? '';
  475. expect(text).toContain('parseToken');
  476. // The caller rail (left) and the callee rail (right) are both drawn.
  477. expect(text).toContain('handleCallback');
  478. expect(text).toContain('decodeJwt');
  479. // The verbatim source, not a summary of it.
  480. expect(text).toContain('expiresAt');
  481. // The honesty badge: nothing in the fixture's graph tests this symbol.
  482. expect(text.toLowerCase()).toContain('test');
  483. });
  484. it('TypeHierarchy draws the fan, its wiring and its fold from a payload alone', async () => {
  485. const implementers = Array.from({ length: 14 }, (_, i) => ({
  486. id: `impl-${i}`,
  487. kind: 'class' as const,
  488. name: `Target${i}`,
  489. qualifiedName: `Target${i}`,
  490. file: `src/targets/target-${i}.ts`,
  491. line: 1,
  492. endLine: 9,
  493. language: 'typescript' as const,
  494. test: false,
  495. depth: 1,
  496. parentId: SYMBOL.node.id,
  497. relation: 'implements' as const,
  498. // The first one arrived through a resolver rather than a parse, which is
  499. // the case the block has to draw differently.
  500. synthesized: i === 0,
  501. ...(i === 0 ? { via: 'go-implements', registeredAt: 'src/clock.go:11' } : {}),
  502. hiddenSubtypes: 0,
  503. }));
  504. const hierarchy: WireHierarchy = {
  505. ancestors: { total: 0, shown: 0, truncated: false, items: [] },
  506. descendants: {
  507. total: implementers.length,
  508. shown: implementers.length,
  509. truncated: false,
  510. items: implementers,
  511. },
  512. direct: implementers.length,
  513. implementers: implementers.length,
  514. bounded: false,
  515. polymorphic: true,
  516. };
  517. await render(TypeHierarchy, { hierarchy, focus: SYMBOL.node, onopen: () => {} });
  518. const text = host.textContent ?? '';
  519. // The claim a reader cannot get by counting rows.
  520. expect(text).toContain('14 implementations');
  521. // The wiring site of the synthesized edge.
  522. expect(text).toContain('go-implements');
  523. // Twelve rows, then the fold — never a silent truncation.
  524. expect(text).toContain('+2 more implementations');
  525. expect(text).toContain('Target0');
  526. expect(text).not.toContain('Target13');
  527. // It draws no network of its own: this component was handed a payload.
  528. expect(host.querySelectorAll('path').length).toBe(12);
  529. });
  530. it('FlowStrip draws one card per hop from a mock adapter', async () => {
  531. const { adapter, calls } = mockAdapter();
  532. setGraphAdapter(adapter);
  533. await render(FlowStrip, {
  534. from: 'handleCallback',
  535. to: 'decodeJwt',
  536. symbols: null,
  537. trailParam: null,
  538. });
  539. expect(calls).toContain('flow');
  540. const text = host.textContent ?? '';
  541. expect(text).toContain('handleCallback');
  542. expect(text).toContain('parseToken');
  543. });
  544. it('ArchitectureMap draws modules and their dependency from a mock adapter', async () => {
  545. const { adapter, calls } = mockAdapter();
  546. setGraphAdapter(adapter);
  547. await render(ArchitectureMap, { root: 'src', depth: 1, tests: false });
  548. expect(calls).toContain('map');
  549. const text = host.textContent ?? '';
  550. expect(text).toContain('auth');
  551. expect(text).toContain('http');
  552. });
  553. it('TrailBar and SearchPalette mount and read through the same adapter', async () => {
  554. const { adapter } = mockAdapter();
  555. setGraphAdapter(adapter);
  556. trail.push({ id: SYMBOL.node.id, name: 'parseToken', kind: 'function', dir: 'start' });
  557. await render(TrailBar, {});
  558. expect(host.textContent ?? '').toContain('parseToken');
  559. void unmount(mounted as Record<string, unknown>);
  560. mounted = null;
  561. host.innerHTML = '';
  562. await render(SearchPalette, {});
  563. expect(host.querySelector('input[role="combobox"]')).not.toBeNull();
  564. });
  565. it('CodegraphUi installs the adapter before its children ask for data', async () => {
  566. const { adapter, calls } = mockAdapter();
  567. // NOT installed by hand — the provider is the only thing that installs it.
  568. expect(getGraphAdapter()).not.toBe(adapter);
  569. mounted = mount(CodegraphUi, { target: host, props: { adapter } }) as Record<string, unknown>;
  570. flushSync();
  571. expect(getGraphAdapter()).toBe(adapter);
  572. expect(calls).toEqual([]);
  573. });
  574. });
  575. describe('@colbymchenry/codegraph-ui — the seams', () => {
  576. it('a host navigation driver replaces every href the components build', () => {
  577. const seen: string[] = [];
  578. const driver: NavigationDriver = {
  579. symbolHref: (id) => `/review/42/symbol/${encodeURIComponent(id)}`,
  580. fileHref: (path) => `/review/42/file/${path}`,
  581. mapHref: () => '/review/42/map',
  582. flowHref: () => '/review/42/flow',
  583. entryHref: () => '/review/42',
  584. navigate: (href) => seen.push(href),
  585. back: () => seen.push('back'),
  586. };
  587. setNavigationDriver(driver);
  588. expect(symbolHref('function:x')).toBe('/review/42/symbol/function%3Ax');
  589. expect(fileHref('src/a.ts')).toBe('/review/42/file/src/a.ts');
  590. expect(mapHref()).toBe('/review/42/map');
  591. expect(flowHref()).toBe('/review/42/flow');
  592. setNavigationDriver(null);
  593. // Back to the viewer's own address space, unchanged.
  594. expect(symbolHref('function:x')).toBe(hashNavigation.symbolHref('function:x'));
  595. expect(symbolHref('function:x')).toBe('#/s/function%3Ax');
  596. });
  597. it('the default adapter is the loopback JSON API and asks for `api/...`', async () => {
  598. const asked: string[] = [];
  599. const adapter = createHttpAdapter({
  600. fetch: async (input) => {
  601. asked.push(String(input));
  602. return new Response(JSON.stringify(STATS), {
  603. status: 200,
  604. headers: { 'content-type': 'application/json' },
  605. });
  606. },
  607. });
  608. await adapter.stats();
  609. await adapter.node('function:parse@a.ts:1');
  610. await adapter.source({ file: 'src/a.ts', from: 1, to: 4 });
  611. await adapter.nodes(['a', 'b']);
  612. expect(asked[0]).toBe('api/stats');
  613. // Ids are encoded per slash-separated segment, so ':' survives and '/' is
  614. // still a path separator.
  615. expect(asked[1]).toBe('api/node/function%3Aparse%40a.ts%3A1');
  616. expect(asked[2]).toBe('api/source?file=src%2Fa.ts&from=1&to=4');
  617. // Repeated `id` params, never a comma-joined list.
  618. expect(asked[3]).toBe('api/nodes?id=a&id=b');
  619. });
  620. it('an adapter with no live channel never connects and never polls', () => {
  621. const { adapter } = mockAdapter();
  622. setGraphAdapter(adapter);
  623. expect(adapter.events).toBeUndefined();
  624. // `live.start()` is a no-op in a jsdom test that never called it; what is
  625. // asserted here is the counters a host can still drive by hand.
  626. const before = live.indexTick;
  627. live.signal('index', { index: { lastIndexedAt: 1, files: 3 } });
  628. expect(live.indexTick).toBe(before + 1);
  629. });
  630. });
  631. describe('@colbymchenry/codegraph-ui — the published shape', () => {
  632. const manifest = JSON.parse(
  633. readFileSync(join(ROOT, 'ui', 'package.json'), 'utf8')
  634. ) as Record<string, any>;
  635. it('is versioned with the engine', () => {
  636. const engine = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) as {
  637. version: string;
  638. };
  639. expect(manifest.version).toBe(engine.version);
  640. });
  641. it('is named, scoped and not publishable by accident', () => {
  642. expect(manifest.name).toBe('@colbymchenry/codegraph-ui');
  643. // The package is PREPARED, not published (CG-61). `private` is the guard:
  644. // npm refuses to publish it until the maintainer deliberately removes this.
  645. expect(manifest.private).toBe(true);
  646. });
  647. it('exports the entry, the theme and nothing else', () => {
  648. expect(Object.keys(manifest.exports).sort()).toEqual(['.', './package.json', './theme.css']);
  649. expect(manifest.exports['.'].svelte).toBe('./dist/index.js');
  650. expect(manifest.exports['.'].types).toBe('./dist/index.d.ts');
  651. });
  652. it('takes svelte as a peer, so a host never gets a second copy', () => {
  653. expect(manifest.peerDependencies.svelte).toBeDefined();
  654. expect(manifest.dependencies?.svelte).toBeUndefined();
  655. // The canvas library is a real dependency: the Map and the Flow strip are
  656. // unusable without it and a host must not have to know its version.
  657. expect(manifest.dependencies['@xyflow/svelte']).toBeDefined();
  658. });
  659. });