import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect } from "vitest"; import { toolContract } from "../../../src/contracts/toolContracts.js"; import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js"; import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js"; const fixtureSource = ` class Base { run() { this.on('ready', () => {}); } // base-instance static run() { this.on('ready', () => {}); } // base-static } class Other { run() { this.on('ready', () => {}); } // other-instance static run() { this.on('ready', () => {}); } // other-static } class Child extends (flag ? Base : Other) { run() { this.emit('ready'); } // child-instance static run() { this.emit('ready'); } // child-static } class ExternalA extends external { field = this.on('ready', () => {}); } class ExternalB extends external { field = this.emit('ready'); } class Sides { field = this.on('sides', () => {}); static field = this.emit('sides'); } const stable = createEmitter(); stable.on('ready', () => {}); stable.emit('ready'); function install() { this.on('computed', () => {}); // computed-outer return { [this.emit('computed')]() { // computed-key this.emit('computed'); // computed-body } }; } `; for (const [label, target] of [ ["intact native emitter", null], [ "builtin module getter", 'process.getBuiltinModule("events").EventEmitter.prototype.on', ], [ "computed builtin module getter", 'process[`getBuiltinModule`]("events").EventEmitter.prototype.on', ], [ "awaited module import", '(await import("node:events")).EventEmitter.prototype.on', ], ] as const) { cliTest( `preserves missing-listener certainty for ${label} through CLI and stdio MCP`, async ({ cli }) => { const root = await createTestTempDirectory("rea-native-emitter-"); await writeFile( join(root, "main.mjs"), ` import {EventEmitter} from "node:events"; ${ target === null ? "" : ` const nativeOn = EventEmitter.prototype.on; function replacement(name, listener = () => {}) { return nativeOn.call(this, name, listener); } ${target} = replacement; ` } const emitter = new EventEmitter(); emitter.on("ready"); `, ); for (const surface of ["CLI", "stdio MCP"] as const) { const { semantic_graph: graph } = await analyzeJavaScriptDirectory( surface, cli, root, ); const events = graph.nodes.filter( (node) => node.kind === "event" && node.properties.event_name === "ready", ); expect(events).toHaveLength(target === null ? 0 : 1); if (target !== null) { expect( graph.relations.some( (relation) => relation.relation === "registers-listener" && (relation.source_node_id === events[0]?.node_id || relation.target_node_id === events[0]?.node_id), ), ).toBe(true); } } }, ); } type SemanticGraph = ReturnType< typeof javascriptApplicationAnalysisResultSchema.parse >["semantic_graph"]; const eventAtMarker = (graph: SemanticGraph, marker: string): string => { const line = fixtureSource .split("\n") .findIndex((text) => text.trimEnd().endsWith(`// ${marker}`)) + 1; if (line === 0) throw new Error(`Missing fixture marker ${marker}`); const relations = graph.relations.filter((relation) => { const location = relation.evidence.location; return ( ["registers-listener", "dispatches-candidate"].includes( relation.relation, ) && location.available && location.value.kind === "source-range" && location.value.start.line === line ); }); expect(relations).toHaveLength(1); const relation = relations[0]; if (relation === undefined) throw new Error(`Missing event relation at ${marker}`); const event = graph.nodes.find( (node) => node.kind === "event" && (node.node_id === relation.source_node_id || node.node_id === relation.target_node_id), ); if (event === undefined) throw new Error(`Missing event node at ${marker}`); return event.node_id; }; cliTest( "preserves receiver sides, local bases and computed-key evaluation through CLI and stdio MCP", async ({ cli }) => { const root = await createTestTempDirectory("rea-this-emitters-"); await writeFile(join(root, "main.mjs"), fixtureSource); const response = await cli.run({ arguments: [ "analyze-javascript-application", root, "--artifact-format", "directory", "--json", ], timeoutMs: 60_000, }); expect(response.exitCode).toBe(0); const contract = toolContract("analyze_javascript_application"); const cliEvidence = contract.outputSchema.parse(response.json); const cliGraph = javascriptApplicationAnalysisResultSchema.parse( cliEvidence.normalized_result, ).semantic_graph; const { client, call } = await connectLocalToolsMcp(); const result = await call("analyze_javascript_application", { input_path: root, format: "directory", }); expect(result.isError).not.toBe(true); const evidence = contract.outputSchema.parse(result.structuredContent); const text = result.content.find((item) => item.type === "text"); if (text?.type !== "text") throw new Error("Missing MCP text result"); expect(contract.outputSchema.parse(JSON.parse(text.text))).toEqual( evidence, ); const graph = javascriptApplicationAnalysisResultSchema.parse( evidence.normalized_result, ).semantic_graph; expect(graph).toEqual(cliGraph); const instance = eventAtMarker(graph, "base-instance"); const statics = eventAtMarker(graph, "base-static"); expect(instance).not.toBe(statics); expect(eventAtMarker(graph, "other-instance")).toBe(instance); expect(eventAtMarker(graph, "child-instance")).toBe(instance); expect(eventAtMarker(graph, "other-static")).toBe(statics); expect(eventAtMarker(graph, "child-static")).toBe(statics); const ready = graph.nodes.filter( (n) => n.kind === "event" && n.properties.event_name === "ready", ); expect(ready).toHaveLength(5); const eventRelations = (id: string) => graph.relations.filter( (r) => ["registers-listener", "dispatches-candidate"].includes(r.relation) && (r.source_node_id === id || r.target_node_id === id), ); const stable = ready.find((n) => String(n.properties.emitter_key).startsWith("binding:"), ); if (stable === undefined) throw new Error("Stable emitter was lost"); expect(eventRelations(stable.node_id).map((r) => r.resolution)).toEqual([ "resolved", "resolved", ]); const receivers = ready.filter((n) => n !== stable); expect( receivers.map((n) => eventRelations(n.node_id).length).sort(), ).toEqual([1, 1, 3, 3]); for (const event of receivers) { expect( eventRelations(event.node_id).every( (r) => r.resolution === "candidate", ), ).toBe(true); expect( graph.unknowns.some( (u) => u.family === "event" && u.node_id === event.node_id, ), ).toBe(true); } const sides = graph.nodes.filter( (n) => n.kind === "event" && n.properties.event_name === "sides", ); expect(sides).toHaveLength(2); for (const event of sides) { expect(eventRelations(event.node_id)).toHaveLength(1); expect(eventRelations(event.node_id)[0]?.resolution).toBe("candidate"); } const computed = graph.nodes.filter( (n) => n.kind === "event" && n.properties.event_name === "computed", ); expect(computed).toHaveLength(2); const outer = eventAtMarker(graph, "computed-outer"); expect(eventAtMarker(graph, "computed-key")).toBe(outer); expect(eventAtMarker(graph, "computed-body")).not.toBe(outer); const registration = computed.find((n) => eventRelations(n.node_id).some( (r) => r.relation === "registers-listener", ), ); if (registration === undefined) throw new Error("Outer receiver registration was lost"); expect( eventRelations(registration.node_id) .map((r) => r.relation) .sort(), ).toEqual(["dispatches-candidate", "registers-listener"]); expect( computed .filter((n) => n !== registration) .flatMap((n) => eventRelations(n.node_id)) .map((r) => r.relation), ).toEqual(["dispatches-candidate"]); for (const event of computed) { expect( eventRelations(event.node_id).every( (r) => r.resolution === "candidate", ), ).toBe(true); expect( graph.unknowns.some( (u) => u.family === "event" && u.node_id === event.node_id, ), ).toBe(true); } await client.ping(); }, 120_000, );