ui-steps-api.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /**
  2. * `GET /api/steps` — what happens from a screen, as typed steps.
  3. *
  4. * Against a real index of a small Expo + React Native app, shaped to cross
  5. * every boundary the endpoint classifies: a screen whose handler (a
  6. * `useCallback`) calls a Swift method through an `RCT_EXTERN_MODULE` shim,
  7. * the Swift side sending an event the screen listens to, the listener calling
  8. * an API function that leaves the index (`client.post`), a store action in a
  9. * store file, and a navigation to a second screen behind a condition. The
  10. * pure layout is tested without an index in `ui-steps-model.test.ts`.
  11. */
  12. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  13. import * as fs from 'fs';
  14. import * as os from 'os';
  15. import * as path from 'path';
  16. import { CodeGraph } from '../src';
  17. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  18. import { buildSteps, crossing, effectCategory, isStoreFile } from '../src/ui-server/api/steps';
  19. let tmpDir: string;
  20. let cg: CodeGraph;
  21. function write(rel: string, content: string): void {
  22. const full = path.join(tmpDir, rel);
  23. fs.mkdirSync(path.dirname(full), { recursive: true });
  24. fs.writeFileSync(full, content);
  25. }
  26. beforeAll(async () => {
  27. await initGrammars();
  28. await loadAllGrammars();
  29. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-ui-steps-'));
  30. write('package.json', JSON.stringify({ name: 'app', dependencies: { expo: '52', 'expo-router': '4', 'react-native': '0.76' } }));
  31. write('src/app/_layout.tsx', 'export default function Layout() { return null }\n');
  32. write('src/app/index.tsx', "import { router } from 'expo-router'\nexport default function Home() {\n return null\n}\n");
  33. write(
  34. 'src/components/capture/capture-view.tsx',
  35. "import { NativeModules, NativeEventEmitter } from 'react-native'\n" +
  36. 'export const captureView = NativeModules.CaptureView\n' +
  37. 'export const nativeEmitter = new NativeEventEmitter(NativeModules.CaptureEvents)\n'
  38. );
  39. write('src/api/client.ts', "import axios from 'axios'\nexport const client = axios.create({ baseURL: 'x' })\n");
  40. write(
  41. 'src/api/frames.ts',
  42. "import { client } from './client'\n" +
  43. 'export async function uploadARCapture(uri: string) {\n' +
  44. " await client.post('/frames', { uri })\n" +
  45. " return client.get('/frames/status')\n" +
  46. '}\n'
  47. );
  48. write(
  49. 'src/storage/capture.storage.ts',
  50. "import { create } from 'zustand'\n" +
  51. 'const useCaptureStorage = create<State>((set) => ({\n' +
  52. ' zipUri: null,\n' +
  53. ' setZipUri: (zipUri: string) => set({ zipUri }),\n' +
  54. '}))\n' +
  55. 'export default useCaptureStorage\n'
  56. );
  57. write(
  58. 'src/app/capture/review.tsx',
  59. "import { useCallback, useEffect } from 'react'\n" +
  60. "import { router } from 'expo-router'\n" +
  61. "import { captureView, nativeEmitter } from '../../components/capture/capture-view'\n" +
  62. "import { uploadARCapture } from '../../api/frames'\n" +
  63. "import useCaptureStorage from '../../storage/capture.storage'\n" +
  64. 'export default function ReviewScreen({ unlimited }: { unlimited: boolean }) {\n' +
  65. ' const setZipUri = useCaptureStorage((s) => s.setZipUri)\n' +
  66. ' const handleApprove = useCallback(() => {\n' +
  67. ' captureView.finalizeCaptureSession()\n' +
  68. ' }, [])\n' +
  69. ' const handleZipComplete = useCallback(async (data: { uri: string }) => {\n' +
  70. ' setZipUri(data.uri)\n' +
  71. ' await uploadARCapture(data.uri)\n' +
  72. " Alert.alert('Uploaded', data.uri, [{ text: 'OK' }])\n" +
  73. " if (unlimited) router.replace('/')\n" +
  74. ' }, [unlimited])\n' +
  75. ' useEffect(() => {\n' +
  76. " const sub = nativeEmitter.addListener('onZipComplete', handleZipComplete)\n" +
  77. ' return () => sub.remove()\n' +
  78. ' }, [handleZipComplete])\n' +
  79. ' const form = useForm({ onSubmit: () => handleSubmit() })\n' +
  80. ' function handleSubmit() {\n' +
  81. ' captureView.finalizeCaptureSession()\n' +
  82. ' }\n' +
  83. ' return <Button onPress={handleApprove} />\n' +
  84. '}\n'
  85. );
  86. write(
  87. 'src/app/capture/index.tsx',
  88. "import { memo, useCallback } from 'react'\n" +
  89. "import { captureView } from '../../components/capture/capture-view'\n" +
  90. 'function CaptureComponent() {\n' +
  91. ' const handleOpen = useCallback(() => {\n' +
  92. ' captureView.finalizeCaptureSession()\n' +
  93. ' }, [])\n' +
  94. ' return <Button onPress={() => handleOpen()} />\n' +
  95. '}\n' +
  96. 'const MemoizedCaptureComponent = memo(CaptureComponent)\n' +
  97. 'export default function CapturePage() {\n' +
  98. ' return <MemoizedCaptureComponent />\n' +
  99. '}\n'
  100. );
  101. write(
  102. 'ios/CaptureView.m',
  103. '#import <React/RCTViewManager.h>\n@interface RCT_EXTERN_MODULE(CaptureView, RCTViewManager)\nRCT_EXTERN_METHOD(finalizeCaptureSession)\n@end\n'
  104. );
  105. write(
  106. 'ios/CaptureView.swift',
  107. 'import Foundation\n' +
  108. 'class CaptureView: RCTViewManager {\n' +
  109. ' @objc func finalizeCaptureSession() {\n' +
  110. ' let result = zip()\n' +
  111. ' if result {\n' +
  112. ' CaptureEvents.shared.emitZipComplete()\n' +
  113. ' }\n' +
  114. ' }\n' +
  115. ' func zip() -> Bool { return true }\n' +
  116. '}\n'
  117. );
  118. write(
  119. 'ios/CaptureEvents.swift',
  120. 'import Foundation\n' +
  121. 'class CaptureEvents: RCTEventEmitter {\n' +
  122. ' static let shared = CaptureEvents()\n' +
  123. ' func emitZipComplete() {\n' +
  124. ' sendEvent(withName: "onZipComplete", body: nil)\n' +
  125. ' }\n' +
  126. '}\n'
  127. );
  128. write(
  129. 'src/api/remove-thing.ts',
  130. "import { client } from './client'\n" +
  131. 'export async function removeThing(name: string) {\n' +
  132. " await client.post('/things/remove', { name })\n" +
  133. '}\n'
  134. );
  135. // The dialog-confirm-then-act pattern: the prompt is an effect box AND the
  136. // thing that fires the handler bound in its buttons.
  137. write(
  138. 'src/app/confirm.tsx',
  139. "import { Alert, Button } from 'react-native'\n" +
  140. "import { removeThing } from '../api/remove-thing'\n" +
  141. 'export default function ConfirmScreen() {\n' +
  142. ' return (\n' +
  143. ' <Button\n' +
  144. ' title="remove"\n' +
  145. ' onPress={() =>\n' +
  146. " Alert.prompt('Remove thing', 'Which one?', [\n" +
  147. " { text: 'Cancel' },\n" +
  148. " { text: 'OK', onPress: (name) => { if (name) removeThing(name) } },\n" +
  149. ' ])\n' +
  150. ' }\n' +
  151. ' />\n' +
  152. ' )\n' +
  153. '}\n'
  154. );
  155. cg = CodeGraph.initSync(tmpDir);
  156. await cg.indexAll();
  157. });
  158. afterAll(() => {
  159. cg?.close();
  160. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  161. });
  162. const q = (params: Record<string, string>) => new URLSearchParams(params);
  163. describe('classification helpers', () => {
  164. it('crossing: JS → native is a bridge, native → JS an event, anything else nothing', () => {
  165. expect(crossing('tsx', 'swift')).toBe('bridge');
  166. expect(crossing('swift', 'tsx')).toBe('event');
  167. expect(crossing('typescript', 'javascript')).toBeNull();
  168. expect(crossing('swift', 'objc')).toBeNull();
  169. });
  170. it('store files', () => {
  171. expect(isStoreFile('src/storage/capture.storage.ts')).toBe(true);
  172. expect(isStoreFile('src/stores/user.ts')).toBe(true);
  173. expect(isStoreFile('src/features/cart/cart.slice.ts')).toBe(true);
  174. expect(isStoreFile('src/components/button.tsx')).toBe(false);
  175. expect(isStoreFile('src/restore/thing.ts')).toBe(false);
  176. });
  177. it('effects: a curated table, by reference text', () => {
  178. expect(effectCategory('client.post')).toBe('network');
  179. expect(effectCategory('fetch')).toBe('network');
  180. expect(effectCategory('AsyncStorage.setItem')).toBe('storage');
  181. expect(effectCategory('Linking.openURL')).toBe('device');
  182. expect(effectCategory('DdRum.addAction')).toBe('telemetry');
  183. expect(effectCategory('Math.max')).toBeNull();
  184. expect(effectCategory('i18n.t')).toBeNull();
  185. });
  186. });
  187. describe('buildSteps', () => {
  188. it('walks a screen through its handler, the bridge, the event, the store and the request', async () => {
  189. const review = cg.getNodesByKind('route').find((r) => r.name === '/capture/review')!;
  190. expect(review).toBeDefined();
  191. const payload = await buildSteps(cg, tmpDir, q({ anchor: review.id }));
  192. const byLabel = new Map(payload.steps.map((s) => [s.label, s]));
  193. const kinds = Object.fromEntries(payload.steps.map((s) => [s.label, s.kind]));
  194. expect(kinds['/capture/review']).toBe('screen');
  195. expect(payload.steps.find((s) => s.anchor)?.label).toBe('/capture/review');
  196. // The handler is wired to the tap, so it is a trigger; the call it makes
  197. // crosses into Swift, so that is a bridge; the Swift side's event lands
  198. // on the named listener; the listener writes the store, leaves the index
  199. // through `client.post`, and navigates home behind `unlimited`.
  200. expect(kinds['handleApprove']).toBe('trigger');
  201. expect(kinds['finalizeCaptureSession']).toBe('bridge');
  202. expect(kinds['handleZipComplete']).toBe('event');
  203. expect(byLabel.get('handleZipComplete')?.event).toBe('onZipComplete');
  204. expect(byLabel.get('handleZipComplete')?.events).toEqual(['onZipComplete']);
  205. expect(kinds['setZipUri']).toBe('store');
  206. // One box per (function, category): both calls the upload makes into the
  207. // network, labelled by the first and counting the rest.
  208. const network = payload.steps.find((s) => s.kind === 'effect' && s.effect?.category === 'network')!;
  209. expect(network.label).toBe('client.post +1');
  210. expect(network.effect?.apis).toEqual(['client.post', 'client.get']);
  211. expect(network.effect?.by.name).toBe('uploadARCapture');
  212. expect(kinds['/']).toBe('screen');
  213. // Another screen is a boundary: drawn, marked, not entered.
  214. expect(byLabel.get('/')?.cut).toBe('screen');
  215. const link = (from: string, to: string) =>
  216. payload.links.find((l) => l.from === byLabel.get(from)!.id && l.to === byLabel.get(to)!.id);
  217. const req = link('handleZipComplete', 'client.post +1');
  218. const tap = link('/capture/review', 'handleApprove');
  219. expect(tap?.kind).toBe('handler');
  220. // What fires it — read at the site: the JSX prop and its element, and the
  221. // function that writes the binding.
  222. expect(tap?.trigger).toEqual({ kind: 'prop', name: 'onPress', of: 'Button', in: 'ReviewScreen' });
  223. expect(byLabel.get('handleApprove')?.trigger).toEqual({ kind: 'prop', name: 'onPress', of: 'Button', in: 'ReviewScreen' });
  224. // A function called from under an `on*` option is a handler too — the
  225. // Formik shape — and the option names what fires it.
  226. expect(kinds['handleSubmit']).toBe('trigger');
  227. expect(link('/capture/review', 'handleSubmit')?.trigger).toEqual({ kind: 'option', name: 'onSubmit', of: 'useForm', in: 'ReviewScreen' });
  228. // The listener registration is a callback binding on the handler link.
  229. expect(link('/capture/review', 'handleZipComplete')?.trigger).toEqual({ kind: 'callback', name: 'addListener', of: "'onZipComplete'", in: 'ReviewScreen' });
  230. expect(link('handleApprove', 'finalizeCaptureSession')?.kind).toBe('bridge');
  231. const evt = link('finalizeCaptureSession', 'handleZipComplete');
  232. expect(evt?.kind).toBe('event');
  233. expect(evt?.synthesized).toBe(true);
  234. expect(evt?.via.map((v) => v.name)).toEqual(['emitZipComplete']);
  235. expect(evt?.when).toBe('result');
  236. expect(evt?.label).toContain('event onZipComplete');
  237. const storeLink = link('handleZipComplete', 'setZipUri');
  238. expect(storeLink?.kind).toBe('store');
  239. // Every call-shaped site says what it passes.
  240. expect(storeLink?.sites[0]?.args).toBe('data.uri');
  241. expect(link('handleApprove', 'finalizeCaptureSession')?.sites[0]?.args).toBe('');
  242. // One call behind an effect box: the box says it. Several: the panel does.
  243. const alert = payload.steps.find((s) => s.kind === 'effect' && s.effect?.category === 'device')!;
  244. expect(alert.label).toBe("Alert.alert('Uploaded', data.uri, […])");
  245. expect(network.label).toBe('client.post +1');
  246. expect(req?.sites.map((s) => `${s.text}(${s.args})`)).toEqual(["client.post('/frames', { uri })", "client.get('/frames/status')"]);
  247. expect(req?.kind).toBe('effect');
  248. expect(req?.via.map((v) => v.name)).toEqual(['uploadARCapture']);
  249. const nav = link('handleZipComplete', '/');
  250. expect(nav?.kind).toBe('navigates');
  251. expect(nav?.when).toBe('unlimited');
  252. expect(nav?.sites[0]?.text).toBe('replace /');
  253. // Every site carries the whole condition it runs under — one scenario each.
  254. expect(nav?.sites[0]?.when).toBe('unlimited');
  255. expect(evt?.sites[0]?.when).toBe('result');
  256. expect(storeLink?.sites[0]?.when).toBe('');
  257. // Rows: the anchor on 0, then one more step away each. The listener is
  258. // registered BY the screen (`addListener('onZipComplete', handleZipComplete)`),
  259. // so it sits one step from the anchor as a handler and the native event
  260. // arrives at it from further down — a link back up the picture — and
  261. // names the event on the box.
  262. expect(byLabel.get('/capture/review')?.depth).toBe(0);
  263. expect(byLabel.get('handleApprove')?.depth).toBe(1);
  264. expect(byLabel.get('finalizeCaptureSession')?.depth).toBe(2);
  265. expect(byLabel.get('handleZipComplete')?.depth).toBe(1);
  266. expect(link('/capture/review', 'handleZipComplete')?.kind).toBe('handler');
  267. expect(network.depth).toBe(2);
  268. expect(payload.through).toBe(false);
  269. expect(payload.truncated).toEqual({ steps: 0, hubs: 0, chrome: 0 });
  270. // No cap fired; the only thing not entered is the other screen.
  271. expect(payload.steps.filter((s) => s.cut !== null).map((s) => [s.label, s.cut])).toEqual([['/', 'screen']]);
  272. });
  273. it('walks through a memo-wrapped component into the screen body', async () => {
  274. const capture = cg.getNodesByKind('route').find((r) => r.name === '/capture')!;
  275. const payload = await buildSteps(cg, tmpDir, q({ anchor: capture.id }));
  276. const kinds = Object.fromEntries(payload.steps.map((s) => [s.label, s.kind]));
  277. // The wrapper and the component are render hops, folded into the link;
  278. // the handler — called from an inline arrow under `onPress` — is the
  279. // first box, the native call the next.
  280. expect(kinds['handleOpen']).toBe('trigger');
  281. expect(kinds['finalizeCaptureSession']).toBe('bridge');
  282. const toHandler = payload.links.find((l) => l.to === payload.steps.find((s) => s.label === 'handleOpen')!.id)!;
  283. expect(toHandler.via.map((v) => v.name)).toEqual(['MemoizedCaptureComponent', 'CaptureComponent']);
  284. expect(toHandler.trigger).toEqual({ kind: 'prop', name: 'onPress', of: 'Button', in: 'CaptureComponent' });
  285. expect(payload.steps.map((s) => s.label)).not.toContain('CaptureComponent');
  286. });
  287. it('enters other screens when asked to continue through them', async () => {
  288. const review = cg.getNodesByKind('route').find((r) => r.name === '/capture/review')!;
  289. const payload = await buildSteps(cg, tmpDir, q({ anchor: review.id, through: '1' }));
  290. expect(payload.through).toBe(true);
  291. expect(payload.steps.find((s) => s.label === '/')?.cut).toBeNull();
  292. });
  293. it('anchors by name, prefers the screen, and lists the rest as ambiguous', async () => {
  294. const payload = await buildSteps(cg, tmpDir, q({ symbol: 'handleApprove' }));
  295. expect(payload.anchor.name).toBe('handleApprove');
  296. expect(payload.steps[0]?.kind).toBe('anchor');
  297. expect(payload.steps.map((s) => s.label)).toContain('finalizeCaptureSession');
  298. });
  299. it('a depth cap is announced on the step it stopped at', async () => {
  300. const review = cg.getNodesByKind('route').find((r) => r.name === '/capture/review')!;
  301. const payload = await buildSteps(cg, tmpDir, q({ anchor: review.id, depth: '2' }));
  302. // The bridge is two steps out: drawn, not explored — and says so.
  303. const bridge = payload.steps.find((s) => s.label === 'finalizeCaptureSession')!;
  304. expect(bridge.cut).toBe('depth');
  305. expect(payload.links.some((l) => l.kind === 'event')).toBe(false);
  306. // The listener still sits one step out, so the event step keeps its
  307. // handler kind: nothing arrived at it from native within the cap.
  308. expect(payload.steps.find((s) => s.label === 'handleZipComplete')?.kind).toBe('trigger');
  309. });
  310. it('refuses a missing anchor and an unknown id', async () => {
  311. await expect(buildSteps(cg, tmpDir, q({}))).rejects.toThrow(/anchor/);
  312. await expect(buildSteps(cg, tmpDir, q({ anchor: 'function:nope' }))).rejects.toThrow(/No symbol/);
  313. await expect(buildSteps(cg, tmpDir, q({ symbol: 'nothingNamedThis' }))).rejects.toThrow(/Nothing/);
  314. });
  315. });
  316. describe('screen regions', () => {
  317. it('a screen names every step’s region: the screen body for its own code, inherited down the walk', async () => {
  318. const review = cg.getNodesByKind('route').find((r) => r.name === '/capture/review')!;
  319. const payload = await buildSteps(cg, tmpDir, q({ anchor: review.id }));
  320. const byLabel = Object.fromEntries(payload.steps.map((s) => [s.label, s]));
  321. // Every step of a screen's picture belongs somewhere.
  322. for (const s of payload.steps) if (!s.anchor) expect(s.region, s.label).toBeDefined();
  323. // A handler declared in the screen body belongs to the screen's own component…
  324. expect(byLabel['handleApprove']!.region!.label).toBe('ReviewScreen');
  325. // …and what it reaches inherits the region that got there first.
  326. expect(byLabel['finalizeCaptureSession']!.region!.id).toBe(byLabel['handleApprove']!.region!.id);
  327. expect(byLabel['setZipUri']!.region!.label).toBe('ReviewScreen');
  328. });
  329. it('a step reached through a folded component belongs to that component — the fold’s first node', async () => {
  330. const capture = cg.getNodesByKind('route').find((r) => r.name === '/capture')!;
  331. const payload = await buildSteps(cg, tmpDir, q({ anchor: capture.id }));
  332. const handler = payload.steps.find((s) => s.label === 'handleOpen')!;
  333. const toHandler = payload.links.find((l) => l.to === handler.id)!;
  334. expect(handler.region!.label).toBe(toHandler.via[0]!.name);
  335. });
  336. it('an anchor with a body carries no regions — its rows read in the code’s order', async () => {
  337. const payload = await buildSteps(cg, tmpDir, q({ symbol: 'handleApprove' }));
  338. for (const s of payload.steps) expect(s.region).toBeUndefined();
  339. });
  340. });
  341. describe('fired from a dialog', () => {
  342. it('a handler bound inside a dialog’s buttons arrives from the dialog, not from the screen', async () => {
  343. const confirm = cg.getNodesByKind('route').find((r) => r.name === '/confirm')!;
  344. const payload = await buildSteps(cg, tmpDir, q({ anchor: confirm.id }));
  345. const prompt = payload.steps.find((s) => s.kind === 'effect' && s.label.startsWith('Alert.prompt'))!;
  346. const handler = payload.steps.find((s) => s.label === 'removeThing')!;
  347. const into = payload.links.filter((l) => l.to === handler.id);
  348. expect(into).toHaveLength(1);
  349. expect(into[0]!.from).toBe(prompt.id);
  350. expect(into[0]!.trigger?.of).toBe('Alert.prompt');
  351. // A handler CALLED from under a binding says what it passes, as every
  352. // call-shaped site does — the argument is what a wrapper wraps.
  353. expect(into[0]!.sites[0]!.args).toBe('name');
  354. // One step deeper than the prompt that fires it, in the prompt's region.
  355. expect(handler.depth).toBe(prompt.depth + 1);
  356. expect(handler.region!.id).toBe(prompt.region!.id);
  357. // …and what the handler does hangs on below.
  358. const post = payload.steps.find((s) => s.kind === 'effect' && s.effect?.category === 'network')!;
  359. expect(payload.links.some((l) => l.from === handler.id && l.to === post.id)).toBe(true);
  360. });
  361. });