object-literal-methods.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /**
  2. * Object-literal method extraction (general AST rule).
  3. *
  4. * The extractor pulls function-valued properties out of an object literal that
  5. * is the value of an exported const — either DIRECTLY
  6. * (`export const actions = { foo: () => {} }`) or RETURNED by an initializer
  7. * call (`export const useStore = create((set, get) => ({ foo: () => {} }))`,
  8. * incl. middleware wrappers). This makes store actions (Zustand/Redux/Pinia/
  9. * MobX/handler maps) real nodes, so `codegraph_node`/`callers` on them resolve
  10. * instead of returning "not found" and forcing the agent to Read the store.
  11. *
  12. * Extraction is keyed on AST shape. The store-accessor resolver follows
  13. * destructured bindings, `useStore.getState().foo()`, and in-store `get().foo()`
  14. * to implementations within the store, excluding interface declarations.
  15. */
  16. import { describe, it, expect, beforeAll, afterEach } from 'vitest';
  17. import * as fs from 'fs';
  18. import * as path from 'path';
  19. import * as os from 'os';
  20. import { CodeGraph } from '../src';
  21. import { extractFromSource } from '../src/extraction';
  22. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  23. beforeAll(async () => {
  24. await initGrammars();
  25. await loadAllGrammars();
  26. });
  27. describe('object-literal method extraction', () => {
  28. it('extracts Zustand store actions (object returned by create()) as function nodes', () => {
  29. const code = `
  30. import { create } from 'zustand'
  31. interface Store {
  32. count: number
  33. fetchUser(): Promise<void>
  34. switchOrganization(id: string): Promise<void>
  35. reset(): void
  36. }
  37. export const useStore = create<Store>((set, get) => ({
  38. count: 0,
  39. fetchUser: async () => { await get().reset() },
  40. switchOrganization: async (id: string) => { set({ count: 1 }) },
  41. reset: () => set({ count: 0 }),
  42. }))
  43. `;
  44. const result = extractFromSource('store.ts', code);
  45. const fnNames = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  46. expect(fnNames).toContain('fetchUser');
  47. expect(fnNames).toContain('switchOrganization');
  48. expect(fnNames).toContain('reset');
  49. // Each action's body was walked: fetchUser references its sibling `reset`,
  50. // so an in-store calls edge will resolve once the pipeline runs.
  51. // By KIND as well as name: the fixture's `Store` interface declares a
  52. // `fetchUser` too, and since #1638 that signature is a node of its own —
  53. // one that appears FIRST in the file, so a name-only lookup finds the
  54. // declaration and reads its return type where the action's body was meant.
  55. const fetchUser = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchUser')!;
  56. const fetchUserRefs = result.unresolvedReferences.filter((r) => r.fromNodeId === fetchUser.id);
  57. // `get().reset()` keeps its call receiver (#1683): the ref is the chain
  58. // `get().reset`, which the resolver binds to the store's own `reset`.
  59. expect(fetchUserRefs.map((r) => r.referenceName)).toContain('get().reset');
  60. expect(fetchUserRefs.map((r) => r.referenceName)).not.toContain('reset');
  61. // The action's body wasn't mis-attributed to the file scope (the reason we
  62. // skip the generic body-visit for the store-factory call).
  63. const fileNode = result.nodes.find((n) => n.kind === 'file')!;
  64. const fileRefs = result.unresolvedReferences.filter((r) => r.fromNodeId === fileNode.id);
  65. expect(fileRefs.map((r) => r.referenceName)).not.toContain('reset');
  66. });
  67. it('extracts actions through a middleware wrapper (create(persist(...)))', () => {
  68. const code = `
  69. import { create } from 'zustand'
  70. import { persist } from 'zustand/middleware'
  71. export const useCounter = create(
  72. persist(
  73. (set, get) => ({
  74. value: 0,
  75. increment: () => set({ value: get().value + 1 }),
  76. }),
  77. { name: 'counter' }
  78. )
  79. )
  80. `;
  81. const result = extractFromSource('counter.ts', code);
  82. const fnNames = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  83. expect(fnNames).toContain('increment');
  84. });
  85. it('extracts actions when the initializer returns via a block (=> { return {...} })', () => {
  86. const code = `
  87. import { create } from 'zustand'
  88. export const useThing = create((set) => {
  89. const initial = 0
  90. return {
  91. value: initial,
  92. bump: () => set({ value: 1 }),
  93. }
  94. })
  95. `;
  96. const result = extractFromSource('thing.ts', code);
  97. const fnNames = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  98. expect(fnNames).toContain('bump');
  99. });
  100. it('does NOT extract methods from a non-exported call-wrapped object (noise gate)', () => {
  101. const code = `
  102. function wrap(f: any) { return f }
  103. const local = wrap(() => ({ shouldNotExtract: () => {} }))
  104. `;
  105. const result = extractFromSource('inline.ts', code);
  106. const names = result.nodes.map((n) => n.name);
  107. expect(names).not.toContain('shouldNotExtract');
  108. });
  109. it('still extracts the existing direct-object shape (export const actions = {...})', () => {
  110. const code = `
  111. export const actions = {
  112. load: async () => { helper() },
  113. }
  114. function helper() {}
  115. `;
  116. const result = extractFromSource('actions.ts', code);
  117. const fnNames = result.nodes.filter((n) => n.kind === 'function').map((n) => n.name);
  118. expect(fnNames).toContain('load');
  119. });
  120. });
  121. describe('object-literal method resolution (end-to-end)', () => {
  122. let tmpDir: string | undefined;
  123. afterEach(() => {
  124. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  125. tmpDir = undefined;
  126. });
  127. it('resolves callers of store actions across files (destructured + chained getState())', async () => {
  128. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-store-'));
  129. fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"t","dependencies":{"zustand":"^4"}}\n');
  130. fs.writeFileSync(
  131. path.join(tmpDir, 'store.ts'),
  132. `import { create } from 'zustand'\n` +
  133. `interface S { fetchUser(): Promise<void>; reset(): void }\n` +
  134. `export const useStore = create<S>((set, get) => ({\n` +
  135. ` fetchUser: async () => { get().reset() },\n` +
  136. ` reset: () => set({}),\n` +
  137. `}))\n`
  138. );
  139. fs.writeFileSync(
  140. path.join(tmpDir, 'caller.ts'),
  141. `import { useStore } from './store'\n` +
  142. `export async function loginFlow() {\n` +
  143. ` const { fetchUser } = useStore.getState()\n` +
  144. ` await fetchUser()\n` +
  145. `}\n` +
  146. `export function hardReset() {\n` +
  147. ` useStore.getState().reset()\n` +
  148. `}\n`
  149. );
  150. const cg = CodeGraph.initSync(tmpDir);
  151. await cg.indexAll();
  152. const fns = cg.getNodesByKind('function');
  153. const fetchUser = fns.find((n) => n.name === 'fetchUser' && n.filePath.endsWith('store.ts'));
  154. const reset = fns.find((n) => n.name === 'reset' && n.filePath.endsWith('store.ts'));
  155. expect(fetchUser).toBeDefined();
  156. expect(reset).toBeDefined();
  157. // Destructured-then-bare call: loginFlow -> fetchUser
  158. const fetchUserCallers = cg.getCallers(fetchUser!.id).map((c) => c.node.name);
  159. expect(fetchUserCallers).toContain('loginFlow');
  160. // Chained getState() call: hardReset -> reset, AND in-store sibling: fetchUser -> reset
  161. const resetCallers = cg.getCallers(reset!.id).map((c) => c.node.name);
  162. expect(resetCallers).toContain('hardReset');
  163. expect(resetCallers).toContain('fetchUser');
  164. cg.close();
  165. });
  166. });