Files
reverse-engineering-anything/tests/acceptance/applications/javascriptThisEmitters.test.ts
e9a6324a1c test(javascript): prove receiver ownership by source location (#15227)
* fix(javascript): scope candidate this event receivers

Preserve lexical receiver scopes and possible local inheritance links without asserting runtime this identity. Keep decorator evaluation outside method receiver and callable boundaries.

Fixes #3360

AI-assisted implementation and verification with OpenAI Codex; human PR ownership and readiness remain unfilled.

* fix(javascript): retain receivers through type wrappers

Reuse the canonical expression normalizer to preserve object function receiver identity through transparent wrappers. Keep arrows, computed keys and non-transparent expressions separate. AI-assisted implementation and verification with OpenAI Codex.

* fix(javascript): retain enclosing receivers for computed keys

Apply the existing computed-method-key evaluation boundary before non-arrow receiver selection. Cover object method keys and bodies through semantic IR and CLI/MCP regressions.

* test(javascript): verify class receiver links by source location

* test(javascript): prove computed receiver boundaries by source

---------

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: 星闌 <Xinglan233@163.com>
Co-authored-by: 星闌 <130824939+Xinglan233@users.noreply.github.com>
2026-11-30 20:42:41 +08:00

204 lines
7.4 KiB
TypeScript

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";
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
}
};
}
`;
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,
);