From 1881bbb55b9e23d53eaed5797a426b7fad6ed160 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:02:00 -0500 Subject: [PATCH] test(javascript): consolidate fingerprint and semantic analysis coverage --- .../javascriptAstFingerprint.test.ts | 161 ++--- .../javascript/javascriptAstFingerprint.ts | 42 +- ...avascriptSemanticAnalysis.dataflow.test.ts | 577 ++++++++---------- ...ascriptSemanticAnalysis.empty_keys.test.ts | 105 ++-- ...vascriptSemanticAnalysis.rejection.test.ts | 6 - ...ptStaticAnalysis.member_path_depth.test.ts | 67 +- .../applicationWorkflowCli.test.ts | 249 +++----- 7 files changed, 475 insertions(+), 732 deletions(-) diff --git a/src/domain/javascript/javascriptAstFingerprint.test.ts b/src/domain/javascript/javascriptAstFingerprint.test.ts index 6d2f9a963c..c67226adbb 100644 --- a/src/domain/javascript/javascriptAstFingerprint.test.ts +++ b/src/domain/javascript/javascriptAstFingerprint.test.ts @@ -2,24 +2,13 @@ import { parse } from "@babel/parser"; import { expect, it } from "vitest"; import { fingerprintJavaScriptAst } from "./javascriptAstFingerprint.js"; -import { analyzeJavaScriptStaticSource } from "../../../tests/fixtures/javascriptStaticAnalysis.js"; it.each([ - ["bigint values", "const value = 1n;", "const value = 2n;"], - [ - "bigint object keys", - "const value = { 1n: 0 };", - "const value = { 2n: 0 };", - ], [ "empty fixed object keys", 'const value = { "": 0 };', 'const value = { "x": 0 };', ], - ["directives", '"use strict";', '"use asm";'], - ["assignment operators", "value = 1;", "value += 1;"], - ["public class method names", "class A { foo() {} }", "class A { bar() {} }"], - ["public class field names", "class A { foo = 1; }", "class A { bar = 1; }"], ["update expression prefix", "value++", "++value"], ["declaration kind", "var value = 1;", "const value = 1;"], [ @@ -60,116 +49,63 @@ it.each([ ); }); -it("includes the fixed key of a Babel class auto-accessor", () => { - const before = parse("class A { accessor foo = 1; }", { - plugins: ["decoratorAutoAccessors"], - }); - const after = parse("class A { accessor bar = 1; }", { - plugins: ["decoratorAutoAccessors"], - }); - expect(fingerprintJavaScriptAst(before)).not.toBe( - fingerprintJavaScriptAst(after), - ); -}); - -it("retains public auto-accessor static and computed flags", () => { - const parseAutoAccessor = (source: string) => - parse(source, { plugins: ["decoratorAutoAccessors"] }); +it("distinguishes public auto-accessor keys and flags while ignoring binding names", () => { + // Auto-accessors are tested at the AST boundary because the source parser + // does not enable Babel's auto-accessor syntax. + const fingerprint = (source: string) => + fingerprintJavaScriptAst( + parse(source, { plugins: ["decoratorAutoAccessors"] }), + ); + const fixed = fingerprint("class A { accessor value = 1; }"); expect( - fingerprintJavaScriptAst( - parseAutoAccessor("class A { accessor value = 1; }"), - ), - ).not.toBe( - fingerprintJavaScriptAst( - parseAutoAccessor("class A { static accessor value = 1; }"), + new Set([ + fixed, + fingerprint("class A { accessor other = 1; }"), + fingerprint("class A { static accessor value = 1; }"), + fingerprint("class A { accessor [value] = 1; }"), + ]).size, + ).toBe(4); + expect( + fingerprint("const key = selectKey(); class A { accessor [key] = 1; }"), + ).toBe( + fingerprint( + "const selector = selectKey(); class B { accessor [selector] = 1; }", ), ); - expect( - fingerprintJavaScriptAst( - parseAutoAccessor("class A { accessor [key] = 1; }"), - ), - ).not.toBe( - fingerprintJavaScriptAst( - parseAutoAccessor("class A { accessor key = 1; }"), - ), + expect(fingerprint("class A { accessor #value = 1; }")).toBe( + fingerprint("class A { accessor #renamed = 1; }"), ); }); it.each(["() {}", "= 1;"])( - "preserves computed class key semantics for %s", + "distinguishes a computed class key from a fixed key in %s", (member) => { - const fingerprint = (source: string) => - fingerprintJavaScriptAst(parse(source)); expect( - fingerprint(`const key = selectKey(); class A { [key]${member} }`), - ).toBe( - fingerprint( - `const selector = selectKey(); class B { [selector]${member} }`, - ), - ); - expect(fingerprint(`class A { ["foo"]${member} }`)).not.toBe( - fingerprint(`class A { foo${member} }`), - ); + fingerprintJavaScriptAst(parse(`class A { ["foo"]${member} }`)), + ).not.toBe(fingerprintJavaScriptAst(parse(`class A { foo${member} }`))); }, ); -it("keeps computed auto-accessor binding renames compatible", () => { - const before = parse( - "const key = selectKey(); class A { accessor [key] = 1; }", - { plugins: ["decoratorAutoAccessors"] }, - ); - const after = parse( - "const selector = selectKey(); class B { accessor [selector] = 1; }", - { plugins: ["decoratorAutoAccessors"] }, - ); - expect(fingerprintJavaScriptAst(before)).toBe( - fingerprintJavaScriptAst(after), +it("ignores private class member renames", () => { + expect( + fingerprintJavaScriptAst(parse("class A { #read() {} #value = 1; }")), + ).toBe( + fingerprintJavaScriptAst(parse("class A { #renamed() {} #field = 1; }")), ); }); -it("keeps private class member renames compatible", () => { - const fingerprint = (source: string) => - fingerprintJavaScriptAst(parse(source)); - expect(fingerprint("class A { #read() {} }")).toBe( - fingerprint("class A { #renamed() {} }"), - ); - expect(fingerprint("class A { #value = 1; }")).toBe( - fingerprint("class A { #renamed = 1; }"), - ); - const fingerprintAutoAccessor = (source: string) => +it("ignores local binding renames inside optional computed reads", () => { + expect( fingerprintJavaScriptAst( - parse(source, { plugins: ["decoratorAutoAccessors"] }), - ); - expect(fingerprintAutoAccessor("class A { accessor #value = 1; }")).toBe( - fingerprintAutoAccessor("class A { accessor #renamed = 1; }"), + parse("function read(obj, key) { return obj?.[key]; }"), + ), + ).toBe( + fingerprintJavaScriptAst( + parse("function read(value, selector) { return value?.[selector]; }"), + ), ); }); -it("includes complete literal values in the fingerprint", () => { - const prefix = "x".repeat(1_024); - const left = parse(`const value = ${JSON.stringify(`${prefix}left`)};`); - const right = parse(`const value = ${JSON.stringify(`${prefix}right`)};`); - - expect(fingerprintJavaScriptAst(left)).not.toBe( - fingerprintJavaScriptAst(right), - ); -}); -it.each(["obj[key]", "obj?.[key]"])( - "ignores a local computed key binding in %s", - (expression) => { - const left = parse(`function read(obj, key) { return ${expression}; }`); - const renamed = expression - .replace("obj", "value") - .replace("key", "selector"); - const right = parse( - `function read(value, selector) { return ${renamed}; }`, - ); - expect(fingerprintJavaScriptAst(left)).toBe( - fingerprintJavaScriptAst(right), - ); - }, -); - it("distinguishes computed reads from fixed named members", () => { expect(fingerprintJavaScriptAst(parse("obj[key]"))).not.toBe( fingerprintJavaScriptAst(parse("obj.key")), @@ -189,32 +125,11 @@ it("distinguishes computed object keys from fixed object keys", () => { }); it.each([ - ["obj[`left`]", "obj[`right`]"], ["obj[``]", "obj[`right`]"], ["obj[true]", "obj[false]"], - ["obj[null]", "obj[false]"], - ['obj["" ]', 'obj["right"]'], ["obj[`prefix-${key}`]", "obj[`changed-${key}`]"], ])("retains computed literal contents in %s", (left, right) => { expect(fingerprintJavaScriptAst(parse(left))).not.toBe( fingerprintJavaScriptAst(parse(right)), ); }); - -it("keeps renamed computed-key bundle modules structurally matchable", () => { - const source = (name: string) => `globalThis.webpackChunkApp.push([[1], { - 17(module, exports) { const ${name} = selectKey(); exports.read = value[${name}]; } - }]);`; - const before = analyzeJavaScriptStaticSource(source("key")) - .bundler_registrations[0]?.modules[0]; - const after = analyzeJavaScriptStaticSource(source("selector")) - .bundler_registrations[0]?.modules[0]; - expect(before).toBeDefined(); - expect(after).toBeDefined(); - expect(before?.structural_fingerprint_algorithm).toBe("babel-ast-v3"); - expect(before?.source_sha256).not.toBe(after?.source_sha256); - expect(before?.structural_fingerprint_sha256).toMatch(/^[a-f0-9]{64}$/u); - expect(before?.structural_fingerprint_sha256).toBe( - after?.structural_fingerprint_sha256, - ); -}); diff --git a/src/domain/javascript/javascriptAstFingerprint.ts b/src/domain/javascript/javascriptAstFingerprint.ts index 96b2fd0739..48f6fdccf8 100644 --- a/src/domain/javascript/javascriptAstFingerprint.ts +++ b/src/domain/javascript/javascriptAstFingerprint.ts @@ -19,7 +19,7 @@ import { import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Static CommonJS export names. */ -export interface StaticExports { +interface StaticExports { readonly values: readonly string[]; /** Export-shaped writes whose receiver role could not be resolved. */ readonly unknown: number; @@ -40,7 +40,7 @@ export const fingerprintJavaScriptAst = (node: t.Node): string => { /** Collect statically declared CommonJS/bundler export names from one factory. */ export const collectJavaScriptExports = ( node: t.Node, - factory?: { + factory: { readonly roles: Pick< JavaScriptBundlerFactoryRoles, "module" | "exports" | "loader" | "unusedDefaults" @@ -51,20 +51,13 @@ export const collectJavaScriptExports = ( >; }, ): StaticExports => { - const roles = factory?.roles; - const index = factory?.index; - const bindings = index?.bindings; + const { roles, index } = factory; + const { bindings } = index; const exports = new Set(); let unknown = 0; const bindingId = (reference: t.Identifier): string | undefined => - bindings === undefined - ? undefined - : resolveSemanticBindingState(bindings, reference, reference.name) - ?.bindingId; - const identity = ( - parameters: readonly (t.Identifier | undefined)[], - fallback: string, - ) => { + resolveSemanticBindingState(bindings, reference, reference.name)?.bindingId; + const identity = (parameters: readonly (t.Identifier | undefined)[]) => { const ids = new Set( parameters.flatMap((parameter) => { const id = parameter === undefined ? undefined : bindingId(parameter); @@ -73,9 +66,6 @@ export const collectJavaScriptExports = ( ); return (reference: t.Node | null): ReceiverRole => { if (!t.isIdentifier(reference)) return undefined; - if (roles === undefined) - return reference.name === fallback ? "role" : undefined; - if (bindings === undefined) return undefined; const binding = resolveSemanticBindingState( bindings, reference, @@ -97,9 +87,9 @@ export const collectJavaScriptExports = ( : undefined; }; }; - const isExportsAlias = identity(roles?.exports ?? [], "exports"); - const isModuleAlias = identity([roles?.module], "module"); - const isLoaderAlias = identity([roles?.loader], "__webpack_require__"); + const isExportsAlias = identity(roles.exports); + const isModuleAlias = identity([roles.module]); + const isLoaderAlias = identity([roles.loader]); const receivers: ExportReceivers = { isExportsAlias, isModuleAlias, @@ -109,7 +99,7 @@ export const collectJavaScriptExports = ( }; traverseJavaScriptAst(node, { // A default the calling convention never runs declares no exports. - skip: (current) => roles?.unusedDefaults.has(current) === true, + skip: (current) => roles.unusedDefaults.has(current), enter: (current) => { if (t.isAssignmentExpression(current)) collectAssignmentExports( @@ -119,16 +109,14 @@ export const collectJavaScriptExports = ( receivers, ); if (t.isCallExpression(current)) { - const intrinsic = - bindings !== undefined && - isUnmodifiedGlobalReference(current.callee, bindings, [ - "Object", - "defineProperty", - ]); + const intrinsic = isUnmodifiedGlobalReference( + current.callee, + bindings, + ["Object", "defineProperty"], + ); collectCallExports(current, exports, receivers, intrinsic, (root) => { const loader = isLoaderAlias(root); if (loader !== "role" || root === null) return loader; - if (index === undefined) return "role"; const facts = index.effectsForReferenceWithinActivationAt( current, root, diff --git a/src/domain/javascript/javascriptSemanticAnalysis.dataflow.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.dataflow.test.ts index f2331fcd2e..ad6a32089b 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.dataflow.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.dataflow.test.ts @@ -11,102 +11,48 @@ import { } from "./javascriptSemanticAnalysis.fixture.js"; describe("JavaScript semantic analysis: dataflow 1", () => { - it("recovers static object reads, writes, spreads, and destructuring", () => { + it("attributes object operations to their bindings and leaves dynamic keys unresolved", () => { const ir = analyzeJavaScriptSemantics(` - const source = { token: "TOKEN", count: 1 }; - const { token } = source; + const source = { token: "TOKEN", kind: "config", 1: "one" }; + const key = getKey(); + const { [key]: dynamic } = source; + const { token, ["kind"]: literal, [1]: numeric } = source; const copy = { ...source }; source.count = 2; const read = source.token; `); - + const bindingNames = new Map( + ir.bindings.map(({ bindingId, name }) => [bindingId, name]), + ); + const name = (id: string | null) => + id === null ? null : bindingNames.get(id); expect( - ir.objectOperations.map(({ kind, propertyPath, resolution }) => ({ - kind, - propertyPath, - resolution, - })), - ).toEqual( - expect.arrayContaining([ - { - kind: "destructure", - propertyPath: ["token"], - resolution: "complete", - }, - { kind: "spread", propertyPath: [], resolution: "complete" }, - { kind: "write", propertyPath: ["count"], resolution: "complete" }, - { kind: "read", propertyPath: ["token"], resolution: "complete" }, - ]), - ); - }); - - it("does not invent property names for dynamic destructuring keys", () => { - const ir = analyzeJavaScriptSemantics(` - const source = { token: "TOKEN" }; - const key = getKey(); - const { [key]: dynamic } = source; - const { ["token"]: literal } = source; - const { token: renamed } = source; - const { token } = source; - const { [1]: numeric } = source; - `); - const destructures = ir.objectOperations.filter( - ({ kind }) => kind === "destructure", - ); - - expect(destructures.map(({ propertyPath }) => propertyPath)).toEqual([ - ["token"], - ["token"], - ["token"], - ["1"], + ir.objectOperations.map( + ({ + kind, + objectBindingId, + targetBindingId, + propertyPath, + resolution, + }) => [ + kind, + name(objectBindingId), + name(targetBindingId), + propertyPath, + resolution, + ], + ), + ).toEqual([ + ["destructure", "source", "token", ["token"], "complete"], + ["destructure", "source", "literal", ["kind"], "complete"], + ["destructure", "source", "numeric", ["1"], "complete"], + ["spread", "source", null, [], "complete"], + ["write", "source", null, ["count"], "complete"], + ["read", "source", null, ["token"], "complete"], ]); - expect( - destructures.every(({ resolution }) => resolution === "complete"), - ).toBe(true); expect(topLevelBinding(ir, "dynamic").value.status).toBe("unknown"); }); - it("does not project positional argument flow after a spread", () => { - const ir = analyzeJavaScriptSemantics(` - function target(first, second, third) { return third; } - target(one, ...rest, three); - `); - - expect(ir.argumentFlows.map(({ argumentIndex }) => argumentIndex)).toEqual([ - 0, - ]); - }); - - it("retains all statically recovered call, flow, capture, and frontier facts", () => { - const ir = analyzeJavaScriptSemantics( - ` - const captured = 1; - function target(value, other) { return value + other + captured; } - target(1, 2); - target(3, 4); - object[first]; - object[second]; - `, - ); - - expect(ir.callSites).toHaveLength(2); - expect(ir.callSites.map(({ arguments: args }) => args)).toEqual([ - [ - expect.objectContaining({ index: 0, spread: false }), - expect.objectContaining({ index: 1, spread: false }), - ], - [ - expect.objectContaining({ index: 0, spread: false }), - expect.objectContaining({ index: 1, spread: false }), - ], - ]); - expect(ir.argumentFlows).toHaveLength(4); - expect(ir.callReturnFlows).toHaveLength(2); - expect(ir.closureCaptures).toHaveLength(1); - expect(ir.frontiers).toHaveLength(2); - expect(ir.coverage.status).toBe("complete"); - }); - it("recovers only direct return sites with literal and unknown object fields", () => { const ir = analyzeJavaScriptSemantics(` export default function parseMarkdown(value) { @@ -125,34 +71,54 @@ describe("JavaScript semantic analysis: dataflow 1", () => { retainedCount: 2, omittedCount: 0, }); - expect(parse.returnSites).toHaveLength(2); - expect(parse.returnSites[0]?.value).toMatchObject({ - status: "object", - unknownProperties: false, - omittedProperties: 0, - properties: expect.arrayContaining([ - { - name: "depth", - presence: "present", - value: { status: "literal", value: 1 }, - }, - { - name: "type", - presence: "present", - value: { status: "literal", value: "heading" }, - }, - { - name: "text", - presence: "present", - value: { - status: "unknown", - reason: "Unsupported CallExpression value.", + expect(parse.returnSites.map(({ value }) => value)).toMatchObject([ + { + status: "object", + unknownProperties: false, + omittedProperties: 0, + properties: [ + { + name: "depth", + presence: "present", + value: { status: "literal", value: 1 }, }, + { name: "text", presence: "present", value: { status: "unknown" } }, + { + name: "type", + presence: "present", + value: { status: "literal", value: "heading" }, + }, + ], + }, + { + status: "object", + unknownProperties: false, + omittedProperties: 0, + properties: [ + { name: "text", presence: "present", value: { status: "unknown" } }, + { + name: "type", + presence: "present", + value: { status: "literal", value: "paragraph" }, + }, + ], + }, + ]); + for (const name of ["nested", "arrow"]) + expect( + onlyCallable(ir, name).returnSites.map(({ value }) => value), + ).toMatchObject([ + { + status: "object", + properties: [ + { + name: "type", + presence: "present", + value: { status: "literal", value: name }, + }, + ], }, - ]), - }); - expect(onlyCallable(ir, "nested").returnSites).toHaveLength(1); - expect(onlyCallable(ir, "arrow").returnSites).toHaveLength(1); + ]); expect(ir.moduleLinks).toContainEqual( expect.objectContaining({ exportedName: "default", @@ -162,6 +128,58 @@ describe("JavaScript semantic analysis: dataflow 1", () => { }); }); +it("attributes repeated calls and unresolved member reads to their own sites", () => { + const ir = analyzeJavaScriptSemantics( + [ + "function target(value) { return value; }", + "target(1);", + "target(2);", + "object[first];", + "object[second];", + ].join("\n"), + ); + const target = onlyCallable(ir, "target"); + expect(ir.callSites).toMatchObject([ + { + calleeCallableIds: [target.callableId], + location: { start: { line: 2, column: 0 } }, + }, + { + calleeCallableIds: [target.callableId], + location: { start: { line: 3, column: 0 } }, + }, + ]); + expect(ir.argumentFlows).toMatchObject( + ir.callSites.map(({ callSiteId }) => ({ + callSiteId, + argumentIndex: 0, + })), + ); + expect(ir.callReturnFlows).toMatchObject( + ir.callSites.map(({ callSiteId }) => ({ + callSiteId, + callableId: target.callableId, + returnSiteId: target.returnSites[0]?.returnSiteId, + })), + ); + expect(ir.frontiers).toMatchObject([ + { + kind: "dynamic-property", + location: { + start: { line: 4, column: 7 }, + end: { line: 4, column: 12 }, + }, + }, + { + kind: "dynamic-property", + location: { + start: { line: 5, column: 7 }, + end: { line: 5, column: 13 }, + }, + }, + ]); +}); + describe("JavaScript semantic call result flows", () => { it("links only directly assigned scalar call results", () => { const ir = analyzeJavaScriptSemantics(` @@ -176,41 +194,58 @@ describe("JavaScript semantic call result flows", () => { ir.bindings.map(({ bindingId, name }) => [bindingId, name]), ); + const calls = new Map( + ir.callSites.map(({ callSiteId, location }) => [ + callSiteId, + location.start, + ]), + ); expect( - ir.callResultFlows.map(({ bindingId }) => bindingNames.get(bindingId)), - ).toEqual(["direct", "nested"]); - expect(ir.callSites).toHaveLength(4); - expect(ir.callResultFlows.map(({ callSiteId }) => callSiteId)).toEqual([ - ir.callSites[0]?.callSiteId, - ir.callSites[2]?.callSiteId, + ir.callResultFlows.map(({ bindingId, callSiteId }) => ({ + binding: bindingNames.get(bindingId), + start: calls.get(callSiteId), + })), + ).toEqual([ + { binding: "direct", start: { line: 3, column: 23 } }, + { binding: "nested", start: { line: 5, column: 23 } }, ]); }); }); describe("JavaScript semantic analysis: read-modify-write", () => { - it.each(["+= 1", "++", "--", "||= 1", "&&= 1", "??= 1"])( - "retains the property read in a read-modify-write operation: %s", - (operator) => { - const ir = analyzeJavaScriptSemantics(` - const source = { count: 1 }; - source.count ${operator}; - `); - expect(ir.objectOperations.map(({ kind }) => kind)).toEqual([ - "read", - "write", - ]); - }, - ); - - it("keeps plain member assignment write-only and member access read-only", () => { + it("distinguishes member reads, writes, and read-modify-write operations", () => { const ir = analyzeJavaScriptSemantics(` - const source = { count: 1 }; - source.count = 2; - const value = source.count; + const source = {}; + const value = source.read; + source.plain = 2; + source.arithmetic += 1; + source.logical ??= 1; + source.increment++; + source.nonNull!++; + (source.cast as number) += 1; + (source.parenthesized)++; + (source.castPlain as number) = 2; + delete source.nonNullDelete!; `); - expect(ir.objectOperations.map(({ kind }) => kind)).toEqual([ - "write", - "read", + expect( + ir.objectOperations.map(({ kind, propertyPath }) => [kind, propertyPath]), + ).toEqual([ + ["read", ["read"]], + ["write", ["plain"]], + ["read", ["arithmetic"]], + ["write", ["arithmetic"]], + ["read", ["logical"]], + ["write", ["logical"]], + ["read", ["increment"]], + ["write", ["increment"]], + ["read", ["nonNull"]], + ["write", ["nonNull"]], + ["read", ["cast"]], + ["write", ["cast"]], + ["read", ["parenthesized"]], + ["write", ["parenthesized"]], + ["write", ["castPlain"]], + ["write", ["nonNullDelete"]], ]); }); @@ -233,36 +268,6 @@ describe("JavaScript semantic analysis: read-modify-write", () => { expect(ir.objectOperations.map(({ kind }) => kind)).toEqual(["write"]); }); - it.each([ - ["non-null update", "source.count!++;"], - ["non-null compound assignment", "source.count! += 1;"], - ["cast compound assignment", "(source.count as number) += 1;"], - ["parenthesized update", "(source.count)++;"], - ])( - "retains the property read in a wrapped read-modify-write: %s", - (_name, statement) => { - const ir = analyzeJavaScriptSemantics(` - const source = { count: 1 }; - ${statement} - `); - expect(ir.objectOperations.map(({ kind }) => kind)).toEqual([ - "read", - "write", - ]); - }, - ); - - it.each([ - ["cast plain assignment", "(source.count as number) = 2;"], - ["non-null delete", "delete source.count!;"], - ])("keeps a wrapped %s write-only", (_name, statement) => { - const ir = analyzeJavaScriptSemantics(` - const source = { count: 1 }; - ${statement} - `); - expect(ir.objectOperations.map(({ kind }) => kind)).toEqual(["write"]); - }); - it("keeps a member in a destructuring default value a read", () => { const ir = analyzeJavaScriptSemantics(` const source = { count: 1 }; @@ -365,117 +370,42 @@ describe("JavaScript semantic analysis: dataflow 2", () => { status: "cycle", }); }); - - it("does not invent exact module paths for dynamic property access", () => { - const ir = analyzeJavaScriptSemantics(` - const key = getKey(); - const dynamicMember = require("electron")[key]; - const { [key]: dynamicBinding } = require("electron"); - `); - - expect(topLevelBinding(ir, "dynamicMember").provenance).toMatchObject({ - status: "unknown", - origins: [], - }); - expect(topLevelBinding(ir, "dynamicBinding").provenance).toMatchObject({ - status: "unknown", - origins: [], - }); - expect( - ir.moduleLinks.filter(({ localName }) => - ["dynamicMember", "dynamicBinding"].includes(localName ?? ""), - ), - ).toEqual([]); - }); - - it("retains all scopes, bindings, and references without truncation", () => { - const ir = analyzeJavaScriptSemantics( - ` - const retained = "yes"; - const omitted = "no"; - retained; - function nested(value) { return retained + value; } - `, - ); - - expect(ir.bindings.map(({ name }) => name)).toEqual( - expect.arrayContaining(["retained", "omitted", "value"]), - ); - expect(ir.callables.map(({ name }) => name)).toContain("nested"); - expect(ir.coverage.status).toBe("complete"); - expect(ir.references.filter(({ name }) => name === "retained")).toEqual([ - expect.objectContaining({ - resolution: "resolved", - bindingId: topLevelBinding(ir, "retained").bindingId, - }), - expect.objectContaining({ - resolution: "resolved", - bindingId: topLevelBinding(ir, "retained").bindingId, - }), - ]); - }); }); describe("JavaScript semantic analysis: mapped arguments writes", () => { - const commonJs = (source: string) => { - const parsed = parseJavaScriptSource(source, "mapped-arguments.cjs"); + it("invalidates mapped parameters after direct, aliased and destructured arguments writes", () => { + const parsed = parseJavaScriptSource( + ` + function direct(value) { value = 1; arguments[0] = 2; return value; } + function alias(value) { value = 1; const args = arguments; args[0] = 2; return value; } + function array(value) { value = 1; [arguments[0]] = [2]; return value; } + function object(value) { value = 1; ({nested: arguments[0]} = {nested: 2}); return value; } + function strict(value) { "use strict"; value = 1; arguments[0] = 2; return value; } + function defaulted(value = 0) { value = 1; arguments[0] = 2; return value; } + function unrelated(value) { value = 1; const other = {}; other[0] = 2; return value; } + `, + "mapped-arguments.cjs", + ); if (parsed === null) throw new Error("Expected CommonJS fixture to parse"); - return analyzeParsedJavaScriptSemantics(parsed); - }; - const returnField = (source: string) => { - const value = onlyCallable(commonJs(source), "read").returnSites[0]?.value; - if (value?.status !== "object") - throw new Error("Expected an object return value"); - const field = value.properties.find(({ name }) => name === "value"); - if (field === undefined) throw new Error("Expected returned value field"); - return field.value; - }; - - it.each([ - ["direct arguments write", "arguments[0] = 2;"], - ["stable arguments alias write", "const args = arguments; args[0] = 2;"], - ["array assignment pattern write", "[arguments[0]] = [2];"], - [ - "nested object assignment pattern write", - "({ nested: arguments[0] } = { nested: 2 });", - ], - ])("does not retain a stale literal after a %s", (_name, write) => { - expect( - returnField( - `function read(value) { value = 1; ${write} return { value }; }`, - ).status, - ).not.toBe("literal"); - }); - - it.each([ - [ - "strict function", - 'function read(value) { "use strict"; value = 1; arguments[0] = 2; return { value }; }', - ], - [ - "default parameter", - "function read(value = 0) { value = 1; arguments[0] = 2; return { value }; }", - ], - [ - "no arguments write", - "function read(value) { value = 1; return { value }; }", - ], - ])("keeps the independent parameter value for a %s", (_name, fn) => { - expect(returnField(fn)).toEqual({ status: "literal", value: 1 }); + const ir = analyzeParsedJavaScriptSemantics(parsed); + for (const name of ["direct", "alias", "array", "object"]) + expect(onlyCallable(ir, name).returnSites[0]?.value, name).toMatchObject({ + status: "ambiguous", + }); + for (const name of ["strict", "defaulted", "unrelated"]) + expect(onlyCallable(ir, name).returnSites[0]?.value, name).toEqual({ + status: "literal", + value: 1, + }); }); it("retains uncertainty when source mode cannot establish sloppy semantics", () => { - const parsed = parseJavaScriptSource( - "function read(value) { value = 1; arguments[0] = 2; return { value }; }", + const ir = analyzeJavaScriptSemantics( + "function read(value) { value = 1; arguments[0] = 2; return value; }", ); - if (parsed === null) throw new Error("Expected fixture to parse"); - const value = onlyCallable(analyzeParsedJavaScriptSemantics(parsed), "read") - .returnSites[0]?.value; - if (value?.status !== "object") - throw new Error("Expected an object return value"); - const property = value.properties.find(({ name }) => name === "value"); - expect(property).toBeDefined(); - expect(property?.value.status).not.toBe("literal"); + expect(onlyCallable(ir, "read").returnSites[0]?.value).toMatchObject({ + status: "ambiguous", + }); }); }); @@ -618,65 +548,62 @@ describe("nonfinite static values", () => { }); describe("binding write invalidation", () => { - it.each(["in", "of"])( - "retains prototype uncertainty for an empty template in for-%s", - (operator) => { - const ir = analyzeJavaScriptSemantics(` - String.prototype.extra = "possible inherited key"; + it("preserves a binding across empty string loops and invalidates it across nonempty loops", () => { + const continuedEmpty = "`\\\n`"; + const ir = analyzeJavaScriptSemantics(` + let enumerated = "before"; + for (enumerated in "") {} + const observed = enumerated; + export function emptyForIn() { return observed; } + export function emptyForOf() { let selected = "before"; - for (selected ${operator} \`\`) {} - const observed = selected; - `); - expect( - topLevelBinding(ir, "selected").definitions.some( - ({ kind }) => kind === "assignment", - ), - ).toBe(true); - expect(topLevelBinding(ir, "observed").value.status).not.toBe("literal"); - }, - ); + for ([selected] of ${continuedEmpty}) {} + return selected; + } + export function nonemptyForIn() { + let selected = "before"; + for ([selected] in "abc") {} + return selected; + } + export function nonemptyForOf() { + let selected = "before"; + for (selected of \`\\u0061\`) {} + return selected; + } + `); + for (const name of ["emptyForIn", "emptyForOf"]) + expect(onlyCallable(ir, name).returnSites[0]?.value).toEqual({ + status: "literal", + value: "before", + }); + for (const name of ["nonemptyForIn", "nonemptyForOf"]) + expect(onlyCallable(ir, name).returnSites[0]?.value).toMatchObject({ + status: "ambiguous", + }); + }); - it.each( - [ - { input: '"abc"', empty: false }, - { input: "`abc`", empty: false }, - { input: "`\\u0061`", empty: false }, - { input: '""', empty: true }, - { input: "``", empty: true }, - { input: "`\\\n`", empty: true }, - ].flatMap((literal) => - ["in", "of"].flatMap((operator) => - ["selected", "[selected]"].map((head) => ({ - ...literal, - operator, - head, - })), - ), - ), - )( - "preserves writes for $head $operator $input (empty=$empty)", - ({ input, empty, operator, head }) => { - const ir = analyzeJavaScriptSemantics(` + it("keeps empty-template loops uncertain when a prototype was changed", () => { + const ir = analyzeJavaScriptSemantics(` + String.prototype.extra = "possible inherited key"; + export function enumerate() { let selected = "before"; - for (${head} ${operator} ${input}) {} - const observed = selected; - export function result() { return observed; } - `); - expect( - topLevelBinding(ir, "selected").definitions.some( - ({ kind }) => kind === "assignment", - ), - ).toBe(!empty); - const value = topLevelBinding(ir, "observed").value; - if (empty) expect(value).toEqual({ status: "literal", value: "before" }); - else expect(value).not.toEqual({ status: "literal", value: "before" }); - expect(onlyCallable(ir, "result").returnSites[0]?.value).toEqual(value); - }, - ); + for (selected in \`\`) {} + return selected; + } + export function iterate() { + let selected = "before"; + for (selected of \`\`) {} + return selected; + } + `); + for (const name of ["enumerate", "iterate"]) + expect(onlyCallable(ir, name).returnSites[0]?.value).toMatchObject({ + status: "ambiguous", + }); + }); it.each([ ["let value = 1; value++; const observed = value;", "unknown"], - ["let value = 1; --value; const observed = value;", "unknown"], [ 'let value = "old"; [value] = ["new"]; const observed = value;', "ambiguous", diff --git a/src/domain/javascript/javascriptSemanticAnalysis.empty_keys.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.empty_keys.test.ts index c0727479f3..5f08c800cf 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.empty_keys.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.empty_keys.test.ts @@ -1,5 +1,6 @@ import { expect, it } from "vitest"; import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js"; +import { topLevelBinding } from "./javascriptSemanticAnalysis.fixture.js"; it("resolves void keys while retaining their calls and binding writes", () => { const ir = analyzeJavaScriptSemantics(` @@ -17,35 +18,30 @@ it("resolves void keys while retaining their calls and binding writes", () => { expect(ir.childProcessSpawns[0]?.stdioMode).toBe("dynamic"); }); -it.each([ - "const routes = {'': 'HOME'}; const root = routes[''];", - "const routes = {['']: 'HOME'}; const root = routes[''];", - "const routes = {'': 'HOME'}; const {'': root} = routes;", - "const routes = {'': 'HOME'}; const {['']: root} = routes;", - "const routes = {home: 'HOME'}; const root = routes.home;", -])("preserves exact string keys in %s", (source) => { - const ir = analyzeJavaScriptSemantics(source); - expect(ir.bindings.find(({ name }) => name === "root")?.value).toEqual({ - status: "literal", - value: "HOME", - }); - expect( - ir.frontiers.filter(({ kind }) => kind === "dynamic-property"), - ).toEqual([]); -}); - -it("keeps a computed identifier key unresolved", () => { +it("resolves literal empty keys while leaving computed identifiers unresolved", () => { const ir = analyzeJavaScriptSemantics( - "const routes = {'': 'HOME'}; const root = routes[key];", - ); - expect(ir.bindings.find(({ name }) => name === "root")?.value.status).toBe( - "unknown", - ); - expect(ir.frontiers).toEqual( - expect.arrayContaining([ - expect.objectContaining({ kind: "dynamic-property" }), - ]), + [ + "const routes = {['']: 'HOME'};", + "const member = routes[''];", + "const {['']: pattern} = routes;", + "const unknown = routes[key];", + ].join("\n"), ); + for (const name of ["member", "pattern"]) + expect(topLevelBinding(ir, name).value).toEqual({ + status: "literal", + value: "HOME", + }); + expect(topLevelBinding(ir, "unknown").value.status).toBe("unknown"); + expect(ir.frontiers).toMatchObject([ + { + kind: "dynamic-property", + location: { + start: { line: 4, column: 23 }, + end: { line: 4, column: 26 }, + }, + }, + ]); }); it("retains exact empty method names and environment keys", () => { @@ -81,44 +77,27 @@ it("retains exact empty require paths and dependencies without dynamic-key bindi module.exports.root = require("./table.js")['']; `); expect( - ir.moduleLinks.map(({ kind, importedName, localName, exportedName }) => ({ - kind, - importedName, - localName, - exportedName, - })), + ir.moduleLinks.map( + ({ kind, specifier, importedName, localName, exportedName }) => [ + kind, + specifier, + importedName, + localName, + exportedName, + ], + ), ).toEqual([ - { - kind: "require", - importedName: "", - localName: "fromPattern", - exportedName: null, - }, - { - kind: "require", - importedName: "", - localName: "fromMember", - exportedName: null, - }, - { - kind: "require", - importedName: null, - localName: null, - exportedName: null, - }, - { - kind: "require", - importedName: null, - localName: null, - exportedName: null, - }, - { - kind: "commonjs-export", - importedName: "", - localName: null, - exportedName: "root", - }, + ["require", "./table.js", "", "fromPattern", null], + ["require", "./table.js", "", "fromMember", null], + ["require", "./table.js", null, null, null], + ["require", "./table.js", null, null, null], + ["commonjs-export", "./table.js", "", null, "root"], ]); + for (const name of ["dynamicPattern", "dynamicMember"]) + expect(topLevelBinding(ir, name).provenance).toMatchObject({ + status: "unknown", + origins: [], + }); }); it("retains exact empty request field names without dynamic fields", () => { diff --git a/src/domain/javascript/javascriptSemanticAnalysis.rejection.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.rejection.test.ts index 8e56a7b0b4..8e0b3be70f 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.rejection.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.rejection.test.ts @@ -8,10 +8,6 @@ import { } from "./javascriptSemanticAnalysis.js"; import { parseJavaScriptSource } from "./javascriptSourceParser.js"; import { analyzeParsedJavaScriptStaticSource } from "../../../tests/fixtures/javascriptStaticAnalysis.js"; -import { - collectJavaScriptExports, - fingerprintJavaScriptAst, -} from "./javascriptAstFingerprint.js"; import type { JavaScriptSemanticValue } from "./javascriptSemanticValueTypes.js"; import { onlyCallable, @@ -41,8 +37,6 @@ describe("JavaScript semantic analysis: rejection 1", () => { const staticAnalysis = analyzeParsedJavaScriptStaticSource("", parsed); expect(staticAnalysis.parse_status).toBe("complete"); expect(staticAnalysis.visited_ast_nodes).toBe(24006); - expect(collectJavaScriptExports(parsed).values).toEqual([]); - expect(fingerprintJavaScriptAst(parsed)).toMatch(/^[a-f0-9]{64}$/u); const ir = analyzeParsedJavaScriptSemantics(parsed); expect(ir.coverage).toMatchObject({ status: "partial", diff --git a/src/domain/javascript/javascriptStaticAnalysis.member_path_depth.test.ts b/src/domain/javascript/javascriptStaticAnalysis.member_path_depth.test.ts index c8c4010b8e..2dea7eb10b 100644 --- a/src/domain/javascript/javascriptStaticAnalysis.member_path_depth.test.ts +++ b/src/domain/javascript/javascriptStaticAnalysis.member_path_depth.test.ts @@ -1,48 +1,45 @@ +import * as t from "@babel/types"; import { expect, it } from "vitest"; -import { collectJavaScriptExports } from "./javascriptAstFingerprint.js"; import { analyzeJavaScriptStaticSource } from "../../../tests/fixtures/javascriptStaticAnalysis.js"; + +import { + collectJavaScriptExports, + fingerprintJavaScriptAst, +} from "./javascriptAstFingerprint.js"; +import { javascriptBundlerFactoryRoles } from "./javascriptBundlerFactoryRoles.js"; +import { indexJavaScriptBindingsWithReceiversSteps } from "./javascriptSemanticAnalysis.js"; +import { completeSemanticSteps } from "./javascriptSemanticTraversal.js"; import { parseJavaScriptSource } from "./javascriptSourceParser.js"; const memberChain = ".next".repeat(12_000); const ordinaryMemberChain = ".next".repeat(64); -it("collects a 12,000-member CommonJS export path without recursion", () => { - const file = parseJavaScriptSource(`exports${memberChain}.last = 1;`); - if (file === null) throw new Error("Expected valid JavaScript"); - expect(collectJavaScriptExports(file).values).toEqual(["next"]); -}); - -it("preserves exact empty keys without inventing dynamic, this, or private exports", () => { - const file = parseJavaScriptSource(` - exports[""].value = 1; - exports[""] = 0; - exports[key].value = 2; - exports.nested = {}; - exports.nested.child = 3; - exports["nested.child"] = 4; - this.exports.ignored = 3; - class Example { #private = 0; read() { this.#private = 1; } } - `); - if (file === null) throw new Error("Expected valid JavaScript"); - expect(collectJavaScriptExports(file).values).toEqual([ - "", - "nested", - "nested.child", - ]); -}); - -it("distinguishes the object literal prototype setter from own export keys", () => { - const prototypeSetter = parseJavaScriptSource( - "module.exports = { __proto__: {} };", +it("retains the root export and fingerprints the value of a 12,000-member assignment", () => { + const file = parseJavaScriptSource( + `function factory(module, exports) { exports${memberChain}.last = 1; }`, ); - const ownKeys = parseJavaScriptSource( - 'module.exports = { ["__proto__"]: 1, __proto__() {} };', + const factory = file?.program.body[0]; + if (file === null || !t.isFunctionDeclaration(factory)) + throw new Error("Expected a parsed factory"); + const index = completeSemanticSteps( + indexJavaScriptBindingsWithReceiversSteps(file.program), ); - if (prototypeSetter === null || ownKeys === null) - throw new Error("Expected valid JavaScript"); - expect(collectJavaScriptExports(prototypeSetter).values).toEqual([]); - expect(collectJavaScriptExports(ownKeys).values).toEqual(["__proto__"]); + expect( + collectJavaScriptExports(factory, { + roles: javascriptBundlerFactoryRoles(factory, "webpackChunkDeep"), + index, + }), + ).toEqual({ values: ["next"], unknown: 0 }); + const statement = factory.body.body[0]; + if ( + !t.isExpressionStatement(statement) || + !t.isAssignmentExpression(statement.expression) + ) + throw new Error("Expected a factory assignment"); + const before = fingerprintJavaScriptAst(factory); + statement.expression.right = t.numericLiteral(2); + expect(fingerprintJavaScriptAst(factory)).not.toBe(before); }); it("keeps left-first and outer-member-first bundler runtime matches", () => { diff --git a/tests/acceptance/applications/applicationWorkflowCli.test.ts b/tests/acceptance/applications/applicationWorkflowCli.test.ts index 49188d0150..4ef48371fc 100644 --- a/tests/acceptance/applications/applicationWorkflowCli.test.ts +++ b/tests/acceptance/applications/applicationWorkflowCli.test.ts @@ -3,11 +3,9 @@ import { execFile } from "node:child_process"; import { INLINE_EVIDENCE_MCP_ENVIRONMENT } from "../../../scripts/lib/mcp-verification-environment.mjs"; import { createHash } from "node:crypto"; import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; -import { createRequire } from "node:module"; import { join, relative, resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { promisify } from "node:util"; -import { runInNewContext } from "node:vm"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; @@ -44,7 +42,6 @@ import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js const execute = promisify(execFile); let cliSession: CliCommandSession | undefined; -const requireFixture = createRequire(import.meta.url); // Analysis requests are stateless; retain one compiled server and its SDK // validators while every scenario still owns a separate application directory. const mcpTransport = new StdioClientTransport({ @@ -93,7 +90,9 @@ const WEBPACK_FACTORY_BODY = ` exports["nested.child"] = 7; module.exports["module.dot"] = 5; module["exports.decoy"] = 99; - Object.defineProperty(exports, "", { + this.exports.ignoredReceiver = 3; + class Example { #private = 0; read() { this.#private = 1; } } + Object.defineProperty(exports, "defined.key", { value: 4, configurable: true, enumerable: true, @@ -1076,36 +1075,63 @@ describe("rest parameter semantic trace CLI", () => { }); }); -describe("empty property key application CLI", () => { - it.each(["const root = routes[''];", "const {'': root} = routes;"])( - "analyzes a root-route dictionary with %s", - async (read) => { - const root = await createTestTempDirectory("rea-empty-key-cli-"); - await writeFile( - join(root, "app.js"), - `const routes = {'': 'HOME'}; ${read}`, - ); - const evidence = await runCli([ - "analyze-javascript-application", - root, - "--json", - ]); - expect(evidence).toMatchObject({ - operation: "analyze_javascript_application", - normalized_result: { - semantic_graph: { - nodes: expect.arrayContaining([ - expect.objectContaining({ - kind: "property-slot", - label: '""', - properties: expect.objectContaining({ name: "" }), - }), - ]), - }, - }, - }); - }, +it("links empty-key reads and destructuring to the same property slot through CLI", async () => { + const root = await createTestTempDirectory("rea-empty-key-cli-"); + await writeFile( + join(root, "app.js"), + [ + "const routes = {'': 'HOME'};", + "const member = routes[''];", + "const {'': pattern} = routes;", + ].join("\n"), ); + const evidence = await runCli([ + "analyze-javascript-application", + root, + "--json", + ]); + const { semantic_graph: graph } = z + .object({ normalized_result: javascriptApplicationAnalysisResultSchema }) + .parse(evidence).normalized_result; + const slots = graph.nodes.filter( + ({ kind, properties }) => + kind === "property-slot" && properties.name === "", + ); + expect(slots).toMatchObject([ + { label: '""', properties: { property_path: [""], property_pointer: "/" } }, + ]); + const nodes = new Map(graph.nodes.map((node) => [node.node_id, node])); + expect( + graph.relations + .filter( + ({ source_node_id, relation }) => + source_node_id === slots[0]?.node_id && + (relation === "reads-property" || relation === "destructures"), + ) + .map(({ relation, resolution, target_node_id }) => { + const target = nodes.get(target_node_id); + return { + relation, + resolution, + kind: target?.kind, + label: target?.label, + }; + }) + .sort((left, right) => left.relation.localeCompare(right.relation)), + ).toEqual([ + { + relation: "destructures", + resolution: "resolved", + kind: "binding", + label: "pattern", + }, + { + relation: "reads-property", + resolution: "resolved", + kind: "expression", + label: "read:/", + }, + ]); }); describe("Webpack factory CommonJS export keys", () => { @@ -1126,77 +1152,6 @@ describe("Webpack factory CommonJS export keys", () => { }]);`; await writeFile(join(root, "bundle.js"), bundle); - // Execute the exact bundle and invoke its registered factory with a loader. - // This also rejects invalid factory syntax before trusting the export oracle. - const actual = runInNewContext(` - globalThis.webpackChunkStaticExports = []; - ${bundle} - const module = { exports: {} }; - const loader = { - d(target, definitions) { - for (const name of Object.keys(definitions)) - Object.defineProperty(target, name, { - enumerable: true, - get: definitions[name], - }); - }, - }; - const [, factories] = globalThis.webpackChunkStaticExports[0]; - factories[1](module, module.exports, loader); - module.exports; - `) as Record; - const oracleRoot = await createTestTempDirectory( - "rea-webpack-export-oracle-", - ); - expect(Reflect.ownKeys(actual).sort()).toEqual([ - "", - "dot.key", - "dynamic", - "from.helper", - "module.dot", - "nested", - "nested.child", - ]); - expect(actual).toMatchObject({ - "": 4, - "dot.key": 2, - dynamic: 1, - "from.helper": 7, - "module.dot": 5, - nested: { child: 6 }, - "nested.child": 7, - }); - const prototypeSetterPath = join(oracleRoot, "prototype-setter.cjs"); - const ownPrototypeKeyPath = join(oracleRoot, "own-prototype-key.cjs"); - await Promise.all([ - writeFile(prototypeSetterPath, "module.exports = { __proto__: {} }"), - writeFile( - ownPrototypeKeyPath, - 'module.exports = { ["__proto__"]: 1, __proto__() {} }', - ), - ]); - expect( - Reflect.ownKeys(requireFixture(prototypeSetterPath) as object), - ).toEqual([]); - expect( - Reflect.ownKeys(requireFixture(ownPrototypeKeyPath) as object), - ).toEqual(["__proto__"]); - - const aliasPath = join(oracleRoot, "alias.cjs"); - const replacementPath = join(oracleRoot, "replacement.cjs"); - await Promise.all([ - writeFile(aliasPath, "exports = function ignored() {};"), - writeFile( - replacementPath, - "module.exports = function actual() { return 42; };", - ), - ]); - expect(requireFixture(aliasPath)).toEqual({}); - const replacement: unknown = requireFixture(replacementPath); - if (typeof replacement !== "function") - throw new Error("Expected Node to load the replacement export"); - expect(replacement()).toBe(42); - const applicationEvidenceSchema = z.object({ evidence_id: z.string(), normalized_result: javascriptApplicationAnalysisResultSchema, @@ -1219,41 +1174,37 @@ describe("Webpack factory CommonJS export keys", () => { const mcpEvidence = applicationEvidenceSchema.parse( response.structuredContent, ); - expect(await client.ping()).toEqual({}); expect(mcpEvidence.evidence_id).toBe(cliEvidence.evidence_id); - const expectBundleExports = ( - evidence: typeof cliEvidence, - moduleKey: string, - expected: readonly string[], - ) => { - const module = evidence.normalized_result.graph.nodes.find( - ({ kind, observations }) => - kind === "javascript-module" && - observations.some( - ({ properties }) => - properties.runtime === "webpackChunkStaticExports" && - properties.module_key === moduleKey, - ), - ); - if (module === undefined) - throw new Error(`Missing webpack factory ${moduleKey}`); - expect(module.observations[0]?.properties.exports).toEqual(expected); - }; for (const evidence of [cliEvidence, mcpEvidence]) { - expectBundleExports(evidence, "1", [ - "", - "dot.key", - "from.helper", - "module.dot", - "nested", - "nested.child", + const modules = evidence.normalized_result.graph.nodes + .filter(({ kind }) => kind === "javascript-module") + .flatMap(({ observations }) => observations) + .filter( + ({ properties }) => + properties.runtime === "webpackChunkStaticExports", + ) + .map(({ properties }) => [properties.module_key, properties.exports]) + .sort(([left], [right]) => String(left).localeCompare(String(right))); + expect(modules).toEqual([ + [ + "1", + [ + "", + "defined.key", + "dot.key", + "from.helper", + "module.dot", + "nested", + "nested.child", + ], + ], + ["2", ["default"]], + ["3", []], + ["4", ["stable"]], + ["5", []], + ["6", ["__proto__"]], ]); - expectBundleExports(evidence, "2", ["default"]); - expectBundleExports(evidence, "3", []); - expectBundleExports(evidence, "4", ["stable"]); - expectBundleExports(evidence, "5", []); - expectBundleExports(evidence, "6", ["__proto__"]); } }); }); @@ -1312,21 +1263,17 @@ describe("application version source-scope MCP comparison", () => { ], }); const client = await connectedMcpClient(); - const compare = async (left: unknown, right: unknown) => { - const response = await client.callTool({ - name: "compare_application_versions", - arguments: { left, right }, - }); - expect(response.isError).not.toBe(true); - return applicationVersionComparisonResultSchema.parse( - parseEvidence(response.structuredContent).normalized_result, - ); - }; - const forward = await compare(full, selected); - const reverse = await compare(selected, full); + const response = await client.callTool({ + name: "compare_application_versions", + arguments: { left: full, right: selected }, + }); + expect(response.isError).not.toBe(true); + const result = applicationVersionComparisonResultSchema.parse( + parseEvidence(response.structuredContent).normalized_result, + ); expect( - forward.items.find( + result.items.find( ({ right_node_id }) => right_node_id === scope?.node_id, ), ).toMatchObject({ @@ -1338,11 +1285,7 @@ describe("application version source-scope MCP comparison", () => { selected.evidence_id, ]), }); - expect( - reverse.items.find(({ left_node_id }) => left_node_id === scope?.node_id), - ).toMatchObject({ status: "unknown", dimensions: ["availability"] }); - expect(forward.summary).toMatchObject({ added: 0, removed: 0 }); - expect(reverse.summary).toMatchObject({ added: 0, removed: 0 }); + expect(result.summary).toMatchObject({ added: 0, removed: 0 }); }); });