1
0

ui-package.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. // Deliberately no `events`: a host without a live channel is the normal
  380. // case, and nothing may poll in its absence.
  381. };
  382. return { adapter, calls };
  383. }
  384. /* ----------------------------------------------------------------- harness */
  385. let host: HTMLDivElement;
  386. let mounted: Record<string, unknown> | null = null;
  387. /** jsdom has none of the observers a canvas library expects. */
  388. beforeAll(() => {
  389. class NoopObserver {
  390. observe(): void {}
  391. unobserve(): void {}
  392. disconnect(): void {}
  393. }
  394. const globals = globalThis as Record<string, unknown>;
  395. globals.ResizeObserver ??= NoopObserver;
  396. globals.IntersectionObserver ??= NoopObserver;
  397. globals.MutationObserver ??= NoopObserver;
  398. globals.requestAnimationFrame ??= (fn: FrameRequestCallback) =>
  399. setTimeout(() => fn(0), 0) as unknown as number;
  400. globals.cancelAnimationFrame ??= (handle: number) => clearTimeout(handle);
  401. // jsdom's own `matchMedia` is a stub that is not callable here, and Svelte's
  402. // `MediaQuery` (which `@xyflow/svelte`'s store constructs eagerly) calls it
  403. // the moment a canvas mounts. Replace it outright rather than guarding.
  404. const media = (query: string) => ({
  405. media: query,
  406. matches: false,
  407. onchange: null,
  408. addEventListener() {},
  409. removeEventListener() {},
  410. addListener() {},
  411. removeListener() {},
  412. dispatchEvent: () => false,
  413. });
  414. Object.defineProperty(window, 'matchMedia', { configurable: true, writable: true, value: media });
  415. globals.matchMedia = media;
  416. if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = () => {};
  417. });
  418. beforeEach(() => {
  419. host = document.createElement('div');
  420. document.body.appendChild(host);
  421. trail.clear();
  422. });
  423. afterEach(() => {
  424. if (mounted) {
  425. void unmount(mounted);
  426. mounted = null;
  427. }
  428. host.remove();
  429. setGraphAdapter(null);
  430. setNavigationDriver(null);
  431. });
  432. /**
  433. * Mount a component and let its data effects settle.
  434. *
  435. * Every screen fetches inside an `$effect`, so a render is not finished until
  436. * the promise the adapter returned has resolved and the follow-up render has
  437. * flushed. Two macrotask turns cover the deepest chain any of them has (the
  438. * Symbol view: node, then its source).
  439. */
  440. async function render(
  441. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  442. component: any,
  443. props: Record<string, unknown>
  444. ): Promise<void> {
  445. mounted = mount(component, { target: host, props }) as Record<string, unknown>;
  446. for (let turn = 0; turn < 4; turn += 1) {
  447. await new Promise((resolve) => setTimeout(resolve, 0));
  448. flushSync();
  449. }
  450. }
  451. describe('@colbymchenry/codegraph-ui — a host renders the package', () => {
  452. it('SymbolView draws callers, source and the callee rail from a mock adapter', async () => {
  453. const { adapter, calls } = mockAdapter();
  454. setGraphAdapter(adapter);
  455. await render(SymbolView, { id: SYMBOL.node.id, line: null });
  456. // It asked the adapter, by id, and it asked for the symbol's own slice.
  457. expect(calls).toContain(`node:${SYMBOL.node.id}`);
  458. expect(calls).toContain('source:src/auth/token.ts');
  459. const text = host.textContent ?? '';
  460. expect(text).toContain('parseToken');
  461. // The caller rail (left) and the callee rail (right) are both drawn.
  462. expect(text).toContain('handleCallback');
  463. expect(text).toContain('decodeJwt');
  464. // The verbatim source, not a summary of it.
  465. expect(text).toContain('expiresAt');
  466. // The honesty badge: nothing in the fixture's graph tests this symbol.
  467. expect(text.toLowerCase()).toContain('test');
  468. });
  469. it('TypeHierarchy draws the fan, its wiring and its fold from a payload alone', async () => {
  470. const implementers = Array.from({ length: 14 }, (_, i) => ({
  471. id: `impl-${i}`,
  472. kind: 'class' as const,
  473. name: `Target${i}`,
  474. qualifiedName: `Target${i}`,
  475. file: `src/targets/target-${i}.ts`,
  476. line: 1,
  477. endLine: 9,
  478. language: 'typescript' as const,
  479. test: false,
  480. depth: 1,
  481. parentId: SYMBOL.node.id,
  482. relation: 'implements' as const,
  483. // The first one arrived through a resolver rather than a parse, which is
  484. // the case the block has to draw differently.
  485. synthesized: i === 0,
  486. ...(i === 0 ? { via: 'go-implements', registeredAt: 'src/clock.go:11' } : {}),
  487. hiddenSubtypes: 0,
  488. }));
  489. const hierarchy: WireHierarchy = {
  490. ancestors: { total: 0, shown: 0, truncated: false, items: [] },
  491. descendants: {
  492. total: implementers.length,
  493. shown: implementers.length,
  494. truncated: false,
  495. items: implementers,
  496. },
  497. direct: implementers.length,
  498. implementers: implementers.length,
  499. bounded: false,
  500. polymorphic: true,
  501. };
  502. await render(TypeHierarchy, { hierarchy, focus: SYMBOL.node, onopen: () => {} });
  503. const text = host.textContent ?? '';
  504. // The claim a reader cannot get by counting rows.
  505. expect(text).toContain('14 implementations');
  506. // The wiring site of the synthesized edge.
  507. expect(text).toContain('go-implements');
  508. // Twelve rows, then the fold — never a silent truncation.
  509. expect(text).toContain('+2 more implementations');
  510. expect(text).toContain('Target0');
  511. expect(text).not.toContain('Target13');
  512. // It draws no network of its own: this component was handed a payload.
  513. expect(host.querySelectorAll('path').length).toBe(12);
  514. });
  515. it('FlowStrip draws one card per hop from a mock adapter', async () => {
  516. const { adapter, calls } = mockAdapter();
  517. setGraphAdapter(adapter);
  518. await render(FlowStrip, {
  519. from: 'handleCallback',
  520. to: 'decodeJwt',
  521. symbols: null,
  522. trailParam: null,
  523. });
  524. expect(calls).toContain('flow');
  525. const text = host.textContent ?? '';
  526. expect(text).toContain('handleCallback');
  527. expect(text).toContain('parseToken');
  528. });
  529. it('ArchitectureMap draws modules and their dependency from a mock adapter', async () => {
  530. const { adapter, calls } = mockAdapter();
  531. setGraphAdapter(adapter);
  532. await render(ArchitectureMap, { root: 'src', depth: 1, tests: false });
  533. expect(calls).toContain('map');
  534. const text = host.textContent ?? '';
  535. expect(text).toContain('auth');
  536. expect(text).toContain('http');
  537. });
  538. it('TrailBar and SearchPalette mount and read through the same adapter', async () => {
  539. const { adapter } = mockAdapter();
  540. setGraphAdapter(adapter);
  541. trail.push({ id: SYMBOL.node.id, name: 'parseToken', kind: 'function', dir: 'start' });
  542. await render(TrailBar, {});
  543. expect(host.textContent ?? '').toContain('parseToken');
  544. void unmount(mounted as Record<string, unknown>);
  545. mounted = null;
  546. host.innerHTML = '';
  547. await render(SearchPalette, {});
  548. expect(host.querySelector('input[role="combobox"]')).not.toBeNull();
  549. });
  550. it('CodegraphUi installs the adapter before its children ask for data', async () => {
  551. const { adapter, calls } = mockAdapter();
  552. // NOT installed by hand — the provider is the only thing that installs it.
  553. expect(getGraphAdapter()).not.toBe(adapter);
  554. mounted = mount(CodegraphUi, { target: host, props: { adapter } }) as Record<string, unknown>;
  555. flushSync();
  556. expect(getGraphAdapter()).toBe(adapter);
  557. expect(calls).toEqual([]);
  558. });
  559. });
  560. describe('@colbymchenry/codegraph-ui — the seams', () => {
  561. it('a host navigation driver replaces every href the components build', () => {
  562. const seen: string[] = [];
  563. const driver: NavigationDriver = {
  564. symbolHref: (id) => `/review/42/symbol/${encodeURIComponent(id)}`,
  565. fileHref: (path) => `/review/42/file/${path}`,
  566. mapHref: () => '/review/42/map',
  567. flowHref: () => '/review/42/flow',
  568. entryHref: () => '/review/42',
  569. navigate: (href) => seen.push(href),
  570. back: () => seen.push('back'),
  571. };
  572. setNavigationDriver(driver);
  573. expect(symbolHref('function:x')).toBe('/review/42/symbol/function%3Ax');
  574. expect(fileHref('src/a.ts')).toBe('/review/42/file/src/a.ts');
  575. expect(mapHref()).toBe('/review/42/map');
  576. expect(flowHref()).toBe('/review/42/flow');
  577. setNavigationDriver(null);
  578. // Back to the viewer's own address space, unchanged.
  579. expect(symbolHref('function:x')).toBe(hashNavigation.symbolHref('function:x'));
  580. expect(symbolHref('function:x')).toBe('#/s/function%3Ax');
  581. });
  582. it('the default adapter is the loopback JSON API and asks for `api/...`', async () => {
  583. const asked: string[] = [];
  584. const adapter = createHttpAdapter({
  585. fetch: async (input) => {
  586. asked.push(String(input));
  587. return new Response(JSON.stringify(STATS), {
  588. status: 200,
  589. headers: { 'content-type': 'application/json' },
  590. });
  591. },
  592. });
  593. await adapter.stats();
  594. await adapter.node('function:parse@a.ts:1');
  595. await adapter.source({ file: 'src/a.ts', from: 1, to: 4 });
  596. await adapter.nodes(['a', 'b']);
  597. expect(asked[0]).toBe('api/stats');
  598. // Ids are encoded per slash-separated segment, so ':' survives and '/' is
  599. // still a path separator.
  600. expect(asked[1]).toBe('api/node/function%3Aparse%40a.ts%3A1');
  601. expect(asked[2]).toBe('api/source?file=src%2Fa.ts&from=1&to=4');
  602. // Repeated `id` params, never a comma-joined list.
  603. expect(asked[3]).toBe('api/nodes?id=a&id=b');
  604. });
  605. it('an adapter with no live channel never connects and never polls', () => {
  606. const { adapter } = mockAdapter();
  607. setGraphAdapter(adapter);
  608. expect(adapter.events).toBeUndefined();
  609. // `live.start()` is a no-op in a jsdom test that never called it; what is
  610. // asserted here is the counters a host can still drive by hand.
  611. const before = live.indexTick;
  612. live.signal('index', { index: { lastIndexedAt: 1, files: 3 } });
  613. expect(live.indexTick).toBe(before + 1);
  614. });
  615. });
  616. describe('@colbymchenry/codegraph-ui — the published shape', () => {
  617. const manifest = JSON.parse(
  618. readFileSync(join(ROOT, 'ui', 'package.json'), 'utf8')
  619. ) as Record<string, any>;
  620. it('is versioned with the engine', () => {
  621. const engine = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) as {
  622. version: string;
  623. };
  624. expect(manifest.version).toBe(engine.version);
  625. });
  626. it('is named, scoped and not publishable by accident', () => {
  627. expect(manifest.name).toBe('@colbymchenry/codegraph-ui');
  628. // The package is PREPARED, not published (CG-61). `private` is the guard:
  629. // npm refuses to publish it until the maintainer deliberately removes this.
  630. expect(manifest.private).toBe(true);
  631. });
  632. it('exports the entry, the theme and nothing else', () => {
  633. expect(Object.keys(manifest.exports).sort()).toEqual(['.', './package.json', './theme.css']);
  634. expect(manifest.exports['.'].svelte).toBe('./dist/index.js');
  635. expect(manifest.exports['.'].types).toBe('./dist/index.d.ts');
  636. });
  637. it('takes svelte as a peer, so a host never gets a second copy', () => {
  638. expect(manifest.peerDependencies.svelte).toBeDefined();
  639. expect(manifest.dependencies?.svelte).toBeUndefined();
  640. // The canvas library is a real dependency: the Map and the Flow strip are
  641. // unusable without it and a host must not have to know its version.
  642. expect(manifest.dependencies['@xyflow/svelte']).toBeDefined();
  643. });
  644. });