From 283a6e89043f5febf481e58defc3cf1ddc58e8c8 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Fri, 30 Oct 2026 10:59:00 +0800 Subject: [PATCH 01/21] fix(javascript): resolve module-level Electron options in functions --- .../electronStaticAnalysisOptions.test.ts | 38 +++++++++++++++++++ .../javascriptSemanticMutationInitializers.ts | 32 ++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index e164a237c2b..23813c260c9 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -200,6 +200,44 @@ describe("Electron option captures and initialization", () => { }); }); +it("resolves module-level webPreferences used inside a function", () => { + const analysis = analyzeJavaScriptStaticSource(` + const { BrowserWindow } = require("electron"); + const webPreferences = { nodeIntegration: true, contextIsolation: false }; + function createWindow() { + return new BrowserWindow({ width: 800, webPreferences }); + } + createWindow(); + `); + const window = analysis.electron.browser_windows[0]; + expect(window?.web_preferences_status).toBe("object-literal"); + expect(window?.web_preferences).toEqual( + expect.arrayContaining([ + { + name: "nodeIntegration", + value: expect.objectContaining({ status: "literal", value: true }), + }, + { + name: "contextIsolation", + value: expect.objectContaining({ status: "literal", value: false }), + }, + ]), + ); +}); +it("keeps a module-level option unresolved when called before initialization", () => { + const analysis = analyzeJavaScriptStaticSource(` + const { BrowserWindow } = require("electron"); + function createWindow() { + return new BrowserWindow({ webPreferences }); + } + createWindow(); + const webPreferences = { nodeIntegration: true }; + `); + expect(analysis.electron.browser_windows[0]).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); +}); describe("Electron option evidence", () => { it.each([ '({ webPreferences: { preload: "./preload.js", sandbox: true } } as const)', diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 2276d8a1ba2..5ffc12cee7d 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -897,11 +897,43 @@ export const semanticBindingAtRead = ( binding, hasDefiniteInitializer, }; + const functionStatementPosition = (): StatementPosition | null => { + let child: t.Node = read; + for ( + let parent = parents.get(child); + parent !== undefined; + child = parent, parent = parents.get(parent) + ) { + if ( + t.isFunction(parent) && + (child === parent.body || semanticComputedMethodKey(parent, child)) + ) { + if (t.isStatement(parent)) return statementPosition(parent, parents); + for ( + let owner = parents.get(parent); + owner !== undefined; + owner = parents.get(owner) + ) + if (t.isStatement(owner)) return statementPosition(owner, parents); + return null; + } + } + return null; + }; + const functionPosition = functionStatementPosition(); + const moduleConstInitializerIsBeforeFunction = + sourcePosition !== null && + functionPosition !== null && + sourcePosition.body === functionPosition.body && + positionPrecedes(sourcePosition, functionPosition) && + binding.scopeId.startsWith("scope:program:"); const uncertainOrder = repeatingLoop || sourcePosition === null || position === null || sourcePosition.body !== position.body; + if (uncertainOrder && moduleConstInitializerIsBeforeFunction) + return { status: "ordered", binding, hasDefiniteInitializer: true }; if (uncertainOrder) return { status: "unresolved", binding, hasDefiniteInitializer }; const selected = selectInitializers(binding, position, read, parents); From 4edd03e3b337cdf313b7eb86f0c6b0df31140885 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Fri, 30 Oct 2026 11:20:41 +0800 Subject: [PATCH 02/21] fix(javascript): limit module option ancestry walk --- .../javascriptSemanticMutationInitializers.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 5ffc12cee7d..396711aaf8e 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -920,13 +920,20 @@ export const semanticBindingAtRead = ( } return null; }; - const functionPosition = functionStatementPosition(); + const moduleConstBinding = + binding.scopeId.startsWith("scope:program:") && + binding.declarationKinds.size === 1 && + binding.declarationKinds.has("const") && + !binding.mutable; + const functionPosition = moduleConstBinding + ? functionStatementPosition() + : null; const moduleConstInitializerIsBeforeFunction = + moduleConstBinding && sourcePosition !== null && functionPosition !== null && sourcePosition.body === functionPosition.body && - positionPrecedes(sourcePosition, functionPosition) && - binding.scopeId.startsWith("scope:program:"); + positionPrecedes(sourcePosition, functionPosition); const uncertainOrder = repeatingLoop || sourcePosition === null || From fb2532ad61ceb4cce7d233131fc1edd4305925ff Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Fri, 30 Oct 2026 11:51:26 +0800 Subject: [PATCH 03/21] fix(javascript): preserve uncertain captured argument ordering --- .../javascript/javascriptSemanticMutationInitializers.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 396711aaf8e..c7d594c394f 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -940,7 +940,8 @@ export const semanticBindingAtRead = ( position === null || sourcePosition.body !== position.body; if (uncertainOrder && moduleConstInitializerIsBeforeFunction) - return { status: "ordered", binding, hasDefiniteInitializer: true }; + // Initialization coverage does not order a capture in another activation. + return { status: "unresolved", binding, hasDefiniteInitializer: true }; if (uncertainOrder) return { status: "unresolved", binding, hasDefiniteInitializer }; const selected = selectInitializers(binding, position, read, parents); From 9bafc838629358fb8ebc0ce86abefa5c82c8a0ab Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Fri, 30 Oct 2026 13:38:37 +0800 Subject: [PATCH 04/21] fix(javascript): retain hoisted activation uncertainty --- .../electronStaticAnalysisOptions.test.ts | 57 ++++++++ .../javascriptSemanticMutationInitializers.ts | 132 ++++++++++++++---- .../electronModuleInitializationCli.test.ts | 61 ++++++++ 3 files changed, 225 insertions(+), 25 deletions(-) create mode 100644 tests/acceptance/applications/electronModuleInitializationCli.test.ts diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 23813c260c9..69623c0bb99 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -238,6 +238,63 @@ it("keeps a module-level option unresolved when called before initialization", ( web_preferences: [], }); }); +it.each([ + { label: "a direct call", before: "createWindow();", after: "" }, + { + label: "an aliased call", + before: "const early = createWindow; early();", + after: "", + }, + { + label: "a forwarding function", + before: "start();", + after: "function start() { createWindow(); }", + }, +])( + "does not initialize a hoisted window function reached by $label", + ({ before, after }) => { + const source = ` + const { BrowserWindow } = require("electron"); + ${before} + const webPreferences = { nodeIntegration: true }; + function createWindow() { + return new BrowserWindow({ webPreferences }); + } + ${after} + `; + expect(() => + runInNewContext(source, { + require: () => ({ BrowserWindow: class {} }), + }), + ).toThrow(/before initialization/); + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); + }, +); + +it("resolves a hoisted window function called after module initialization", () => { + const source = ` + const { BrowserWindow } = require("electron"); + function createWindow() { + return new BrowserWindow({ webPreferences }); + } + const webPreferences = { nodeIntegration: true }; + createWindow(); + `; + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); +}); + describe("Electron option evidence", () => { it.each([ '({ webPreferences: { preload: "./preload.js", sandbox: true } } as const)', diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index c7d594c394f..ae486d31f09 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -1,4 +1,5 @@ import * as t from "@babel/types"; +import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; import { delayedInstanceFieldValue, @@ -29,6 +30,7 @@ interface StatementPosition { interface BindingReadPosition { readonly position: StatementPosition | null; readonly repeatingLoop: t.Loop | undefined; + readonly enclosingFunction: t.Function | undefined; } interface ExpressionSiblings { @@ -54,6 +56,10 @@ interface InitializerPositionCache { readonly mutation: WeakMap; readonly reference: WeakMap; readonly read: WeakMap; + readonly moduleFunctionReads: WeakMap< + readonly t.Statement[], + WeakMap + >; readonly evaluationChildren: WeakMap< t.Node, ReadonlyMap | null @@ -78,6 +84,7 @@ const initializerPositionCache = ( mutation: new WeakMap(), reference: new WeakMap(), read: new WeakMap(), + moduleFunctionReads: new WeakMap(), evaluationChildren: new WeakMap(), expressionAncestry: undefined, }; @@ -727,7 +734,11 @@ const bindingReadPosition = ( path.push(current); const parent = parents.get(current); if (t.isLoop(parent)) { - result = { position: null, repeatingLoop: parent }; + result = { + position: null, + repeatingLoop: parent, + enclosingFunction: undefined, + }; break; } if ( @@ -735,7 +746,12 @@ const bindingReadPosition = ( (t.isFunction(parent) && !semanticComputedMethodKey(parent, current)) || delayedInstanceFieldValue(parent, current) ) { - result = { position: null, repeatingLoop: undefined }; + result = { + position: null, + repeatingLoop: undefined, + enclosingFunction: + t.isFunction(parent) && current === parent.body ? parent : undefined, + }; break; } current = parent; @@ -798,6 +814,70 @@ type SemanticBindingRead = { readonly binding: JavaScriptSemanticBindingState; }; +/** A hoisted function needs a module-level use after initialization, not a later declaration. */ +const moduleFunctionFirstRead = ( + declaration: t.FunctionDeclaration, + body: readonly t.Statement[], + parents: WeakMap, +): number | null => { + const cache = initializerPositionCache(parents).moduleFunctionReads; + let reads = cache.get(body); + if (reads === undefined) { + reads = new WeakMap(); + cache.set(body, reads); + const functions = new Map(); + for (const statement of body) { + const exported = + t.isExportNamedDeclaration(statement) || + t.isExportDefaultDeclaration(statement); + const node = exported ? statement.declaration : statement; + if (!t.isFunctionDeclaration(node)) continue; + reads.set(node, exported ? null : Infinity); + if (node.id == null) continue; + const name = node.id.name; + if (functions.has(name)) { + const previous = functions.get(name); + if (previous != null) reads.set(previous, null); + reads.set(node, null); + functions.set(name, null); + } else functions.set(name, node); + } + const indexedReads = reads; + const active = new Set(); + for (let index = 0; index < body.length; index++) { + const statement = body[index]; + if (statement === undefined) continue; + traverseJavaScriptAst(statement, { + enter(node, parent) { + if (t.isFunction(node)) active.add(node); + if ( + !t.isIdentifier(node) || + parent === null || + !t.isReferenced(node, parent) + ) + return; + const fn = functions.get(node.name); + if (fn == null || active.has(fn)) return; + const current = indexedReads.get(fn); + if (current === null || current === undefined) return; + // Indirect activations and live exports have no proven module timing. + indexedReads.set( + fn, + active.size > 0 || t.isExportSpecifier(parent) + ? null + : Math.min(current, index), + ); + }, + exit(node) { + if (t.isFunction(node)) active.delete(node); + }, + }); + } + } + const first = reads.get(declaration); + return first !== undefined && Number.isFinite(first) ? first : null; +}; + export const semanticBindingAtRead = ( binding: JavaScriptSemanticBindingState, read: t.Node, @@ -864,7 +944,10 @@ export const semanticBindingAtRead = ( ? null : initializerPosition(reference, parents, true) : initializerPosition(initializer, parents); - const { position, repeatingLoop } = bindingReadPosition(read, parents); + const { position, repeatingLoop, enclosingFunction } = bindingReadPosition( + read, + parents, + ); // Coverage and latest-value selection are independent. A preceding write // can cover entry even when another write's order remains unknown. const hasDefiniteInitializer = @@ -898,26 +981,15 @@ export const semanticBindingAtRead = ( hasDefiniteInitializer, }; const functionStatementPosition = (): StatementPosition | null => { - let child: t.Node = read; + if (enclosingFunction === undefined) return null; + if (t.isStatement(enclosingFunction)) + return statementPosition(enclosingFunction, parents); for ( - let parent = parents.get(child); - parent !== undefined; - child = parent, parent = parents.get(parent) - ) { - if ( - t.isFunction(parent) && - (child === parent.body || semanticComputedMethodKey(parent, child)) - ) { - if (t.isStatement(parent)) return statementPosition(parent, parents); - for ( - let owner = parents.get(parent); - owner !== undefined; - owner = parents.get(owner) - ) - if (t.isStatement(owner)) return statementPosition(owner, parents); - return null; - } - } + let owner = parents.get(enclosingFunction); + owner !== undefined; + owner = parents.get(owner) + ) + if (t.isStatement(owner)) return statementPosition(owner, parents); return null; }; const moduleConstBinding = @@ -928,18 +1000,28 @@ export const semanticBindingAtRead = ( const functionPosition = moduleConstBinding ? functionStatementPosition() : null; - const moduleConstInitializerIsBeforeFunction = + const firstFunctionRead = + moduleConstBinding && + sourcePosition !== null && + functionPosition !== null && + sourcePosition.body === functionPosition.body && + t.isFunctionDeclaration(enclosingFunction) + ? moduleFunctionFirstRead(enclosingFunction, sourcePosition.body, parents) + : null; + const moduleConstInitializedBeforeActivation = moduleConstBinding && sourcePosition !== null && functionPosition !== null && sourcePosition.body === functionPosition.body && - positionPrecedes(sourcePosition, functionPosition); + (t.isFunctionDeclaration(enclosingFunction) + ? firstFunctionRead !== null && sourcePosition.index < firstFunctionRead + : positionPrecedes(sourcePosition, functionPosition)); const uncertainOrder = repeatingLoop || sourcePosition === null || position === null || sourcePosition.body !== position.body; - if (uncertainOrder && moduleConstInitializerIsBeforeFunction) + if (uncertainOrder && moduleConstInitializedBeforeActivation) // Initialization coverage does not order a capture in another activation. return { status: "unresolved", binding, hasDefiniteInitializer: true }; if (uncertainOrder) diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts new file mode 100644 index 00000000000..a2b1345b39e --- /dev/null +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -0,0 +1,61 @@ +import { expect } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; +import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js"; +import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js"; + +cliTest.for(["CLI", "stdio MCP"] as const)( + "preserves hoisted Electron initialization uncertainty through %s", + async (surface, { cli }) => { + const root = await createTestTempDirectory("rea-electron-initialization-"); + await writeFixtureFiles(root, { + "package.json": JSON.stringify({ main: "early.cjs" }), + "early.cjs": ` + const { BrowserWindow } = require("electron"); + createWindow(); + const webPreferences = { nodeIntegration: true }; + function createWindow() { + return new BrowserWindow({ webPreferences }); + } + require("./late.cjs"); + throw new Error("must not execute source"); + `, + "late.cjs": ` + const { BrowserWindow } = require("electron"); + function createWindow() { + return new BrowserWindow({ webPreferences }); + } + const webPreferences = { nodeIntegration: true }; + createWindow(); + throw new Error("must not execute source"); + `, + }); + const result = await analyzeJavaScriptDirectory(surface, cli, root); + expect(result.statistics.parse_failures).toBe(0); + const windows = result.graph.nodes.filter( + ({ kind }) => kind === "browser-window", + ); + expect(windows).toHaveLength(2); + const observations = windows.flatMap(({ observations }) => observations); + const inSource = (source: string) => + observations.filter( + ({ evidence }) => + evidence.location.available && + evidence.location.value.kind === "source-range" && + evidence.location.value.source === source, + ); + expect(inSource("early.cjs")).toHaveLength(1); + expect(inSource("early.cjs")[0]?.properties).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); + expect(inSource("late.cjs")).toHaveLength(1); + expect(inSource("late.cjs")[0]?.properties).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + }, +); From cc2bb1242a5611527bfb99935bc7dbcf85e902f7 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Fri, 30 Oct 2026 23:53:56 +0800 Subject: [PATCH 05/21] fix(javascript): retain function ownership through loops --- .../electronStaticAnalysisOptions.test.ts | 40 ++++++++++++ .../javascriptSemanticMutationInitializers.ts | 63 ++++++++++++------- .../electronModuleInitializationCli.test.ts | 53 ++++++++++++---- 3 files changed, 122 insertions(+), 34 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 69623c0bb99..9cd76e22f7c 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -295,6 +295,46 @@ it("resolves a hoisted window function called after module initialization", () = }); }); +it.each([ + "for (const item of [0])", + "for (let index = 0; index < 1; index++)", + "while (true)", +])( + "keeps function initialization coverage separate from %s ordering", + (loop) => { + const source = (early: boolean) => ` + const { BrowserWindow } = require("electron"); + ${early ? "createWindow();" : ""} + const webPreferences = { nodeIntegration: true }; + function createWindow() { + ${loop} { + return new BrowserWindow({ webPreferences }); + } + } + ${early ? "" : "createWindow();"} + `; + const runtime = () => ({ require: () => ({ BrowserWindow: class {} }) }); + expect(() => runInNewContext(source(false), runtime())).not.toThrow(); + expect( + analyzeJavaScriptStaticSource(source(false)).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + expect(() => runInNewContext(source(true), runtime())).toThrow( + /before initialization/, + ); + expect( + analyzeJavaScriptStaticSource(source(true)).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); + }, +); + describe("Electron option evidence", () => { it.each([ '({ webPreferences: { preload: "./preload.js", sandbox: true } } as const)', diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index ae486d31f09..9210fe87a3f 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -30,7 +30,6 @@ interface StatementPosition { interface BindingReadPosition { readonly position: StatementPosition | null; readonly repeatingLoop: t.Loop | undefined; - readonly enclosingFunction: t.Function | undefined; } interface ExpressionSiblings { @@ -56,6 +55,7 @@ interface InitializerPositionCache { readonly mutation: WeakMap; readonly reference: WeakMap; readonly read: WeakMap; + readonly enclosingFunction: WeakMap; readonly moduleFunctionReads: WeakMap< readonly t.Statement[], WeakMap @@ -84,6 +84,7 @@ const initializerPositionCache = ( mutation: new WeakMap(), reference: new WeakMap(), read: new WeakMap(), + enclosingFunction: new WeakMap(), moduleFunctionReads: new WeakMap(), evaluationChildren: new WeakMap(), expressionAncestry: undefined, @@ -716,6 +717,35 @@ export const semanticMutationInitializers = ( }; }; +/** Function ownership is independent of uncertain ordering within a loop. */ +const bindingEnclosingFunction = ( + read: t.Node, + parents: WeakMap, +): t.Function | undefined => { + const cache = initializerPositionCache(parents).enclosingFunction; + const path: t.Node[] = []; + let current = read; + let result: t.Function | null = null; + while (true) { + const cached = cache.get(current); + if (cached !== undefined) { + result = cached; + break; + } + path.push(current); + const parent = parents.get(current); + if (parent === undefined || delayedInstanceFieldValue(parent, current)) + break; + if (t.isFunction(parent) && !semanticComputedMethodKey(parent, current)) { + if (current === parent.body) result = parent; + break; + } + current = parent; + } + for (const node of path) cache.set(node, result); + return result ?? undefined; +}; + /** Reuse immutable ancestry facts across reads nested in the same expression. */ const bindingReadPosition = ( read: t.Node, @@ -734,11 +764,7 @@ const bindingReadPosition = ( path.push(current); const parent = parents.get(current); if (t.isLoop(parent)) { - result = { - position: null, - repeatingLoop: parent, - enclosingFunction: undefined, - }; + result = { position: null, repeatingLoop: parent }; break; } if ( @@ -746,12 +772,7 @@ const bindingReadPosition = ( (t.isFunction(parent) && !semanticComputedMethodKey(parent, current)) || delayedInstanceFieldValue(parent, current) ) { - result = { - position: null, - repeatingLoop: undefined, - enclosingFunction: - t.isFunction(parent) && current === parent.body ? parent : undefined, - }; + result = { position: null, repeatingLoop: undefined }; break; } current = parent; @@ -944,10 +965,7 @@ export const semanticBindingAtRead = ( ? null : initializerPosition(reference, parents, true) : initializerPosition(initializer, parents); - const { position, repeatingLoop, enclosingFunction } = bindingReadPosition( - read, - parents, - ); + const { position, repeatingLoop } = bindingReadPosition(read, parents); // Coverage and latest-value selection are independent. A preceding write // can cover entry even when another write's order remains unknown. const hasDefiniteInitializer = @@ -980,6 +998,14 @@ export const semanticBindingAtRead = ( binding, hasDefiniteInitializer, }; + const moduleConstBinding = + binding.scopeId.startsWith("scope:program:") && + binding.declarationKinds.size === 1 && + binding.declarationKinds.has("const") && + !binding.mutable; + const enclosingFunction = moduleConstBinding + ? bindingEnclosingFunction(read, parents) + : undefined; const functionStatementPosition = (): StatementPosition | null => { if (enclosingFunction === undefined) return null; if (t.isStatement(enclosingFunction)) @@ -992,11 +1018,6 @@ export const semanticBindingAtRead = ( if (t.isStatement(owner)) return statementPosition(owner, parents); return null; }; - const moduleConstBinding = - binding.scopeId.startsWith("scope:program:") && - binding.declarationKinds.size === 1 && - binding.declarationKinds.has("const") && - !binding.mutable; const functionPosition = moduleConstBinding ? functionStatementPosition() : null; diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index a2b1345b39e..8bf380c159a 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -19,6 +19,8 @@ cliTest.for(["CLI", "stdio MCP"] as const)( return new BrowserWindow({ webPreferences }); } require("./late.cjs"); + require("./early-loop.cjs"); + require("./late-loop.cjs"); throw new Error("must not execute source"); `, "late.cjs": ` @@ -30,13 +32,31 @@ cliTest.for(["CLI", "stdio MCP"] as const)( createWindow(); throw new Error("must not execute source"); `, + "early-loop.cjs": ` + const { BrowserWindow } = require("electron"); + createWindow(); + const webPreferences = { nodeIntegration: true }; + function createWindow() { + for (const item of [0]) return new BrowserWindow({ webPreferences }); + } + throw new Error("must not execute source"); + `, + "late-loop.cjs": ` + const { BrowserWindow } = require("electron"); + const webPreferences = { nodeIntegration: true }; + function createWindow() { + for (const item of [0]) return new BrowserWindow({ webPreferences }); + } + createWindow(); + throw new Error("must not execute source"); + `, }); const result = await analyzeJavaScriptDirectory(surface, cli, root); expect(result.statistics.parse_failures).toBe(0); const windows = result.graph.nodes.filter( ({ kind }) => kind === "browser-window", ); - expect(windows).toHaveLength(2); + expect(windows).toHaveLength(4); const observations = windows.flatMap(({ observations }) => observations); const inSource = (source: string) => observations.filter( @@ -45,17 +65,24 @@ cliTest.for(["CLI", "stdio MCP"] as const)( evidence.location.value.kind === "source-range" && evidence.location.value.source === source, ); - expect(inSource("early.cjs")).toHaveLength(1); - expect(inSource("early.cjs")[0]?.properties).toMatchObject({ - web_preferences_status: "dynamic", - web_preferences: [], - }); - expect(inSource("late.cjs")).toHaveLength(1); - expect(inSource("late.cjs")[0]?.properties).toMatchObject({ - web_preferences_status: "object-literal", - web_preferences: [ - { name: "nodeIntegration", value: { status: "literal", value: true } }, - ], - }); + for (const source of ["early.cjs", "early-loop.cjs"]) { + expect(inSource(source)).toHaveLength(1); + expect(inSource(source)[0]?.properties).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); + } + for (const source of ["late.cjs", "late-loop.cjs"]) { + expect(inSource(source)).toHaveLength(1); + expect(inSource(source)[0]?.properties).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { + name: "nodeIntegration", + value: { status: "literal", value: true }, + }, + ], + }); + } }, ); From 9611e5cbe8d0d3639f87df529d2989e69a63d1f2 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Sun, 1 Nov 2026 18:49:33 +0800 Subject: [PATCH 06/21] fix(javascript): account for classic global activations --- docs/javascript-artifact-reconstruction.md | 8 ++ .../electronStaticAnalysisOptions.test.ts | 95 ++++++++++++++++++- .../javascriptSemanticMutationInitializers.ts | 33 ++++++- .../electronModuleInitializationCli.test.ts | 51 ++++++++++ 4 files changed, 181 insertions(+), 6 deletions(-) diff --git a/docs/javascript-artifact-reconstruction.md b/docs/javascript-artifact-reconstruction.md index 396352c5b20..cd32a1c3d3d 100644 --- a/docs/javascript-artifact-reconstruction.md +++ b/docs/javascript-artifact-reconstruction.md @@ -541,6 +541,14 @@ the same artifact. Inline option syntax keeps its observed Evidence. This does not execute code or establish runtime configuration; popup overrides from `setWindowOpenHandler` are not covered by this constant-options resolution. +A hoisted function does not establish initialization timing by declaration order. +For classic scripts, the shared index also accounts for matching literal global +property accesses through `globalThis`, `window`, `self`, and `this`, including +optional and computed literal access. An early read or an indirect activation +keeps captured options unknown even when a later bare call exists. ES module +function declarations are not inferred to be global properties. This remains a +bounded source-order check, not a proof that runtime activation succeeds. + Recognized literal module-table bootstraps also support bounded lexical substitution through module exports, import helper bodies, local wrapper calls, returned closures, object spreads, and callback parameters. Recovered Electron diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 9cd76e22f7c..f33c30f5d49 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -313,7 +313,10 @@ it.each([ } ${early ? "" : "createWindow();"} `; - const runtime = () => ({ require: () => ({ BrowserWindow: class {} }) }); + const runtime = () => { + const context = { require: () => ({ BrowserWindow: class {} }) }; + return { ...context, window: undefined, self: undefined }; + }; expect(() => runInNewContext(source(false), runtime())).not.toThrow(); expect( analyzeJavaScriptStaticSource(source(false)).electron.browser_windows[0], @@ -335,6 +338,96 @@ it.each([ }, ); +describe("Classic-script global function activation", () => { + it.each([ + "globalThis.createWindow();", + 'globalThis["createWindow"]();', + "const early = globalThis.createWindow; early();", + "globalThis?.createWindow?.();", + "window.createWindow();", + 'self["createWindow"]();', + "this.createWindow();", + ])("keeps early global access unresolved: %s", (activation) => { + const body = (early: boolean) => ` + const { BrowserWindow } = require("electron"); + ${early ? activation : ""} + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + ${early ? "" : activation} + createWindow(); + `; + const runtime = () => ({ require: () => ({ BrowserWindow: class {} }) }); + expect(() => + runInNewContext( + "globalThis.window = globalThis; globalThis.self = globalThis;" + + body(true), + runtime(), + ), + ).toThrow(/before initialization/); + expect(() => + runInNewContext( + "globalThis.window = globalThis; globalThis.self = globalThis;" + + body(false), + runtime(), + ), + ).not.toThrow(); + expect( + analyzeJavaScriptStaticSource(body(true)).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); + expect( + analyzeJavaScriptStaticSource(body(false)).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + }); + + it("does not treat an ES module function as a global property", () => { + const source = ` + import { BrowserWindow } from "electron"; + globalThis.createWindow(); + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + createWindow(); + `; + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + }); + + it("keeps unrelated same-named member calls independent", () => { + const source = ` + const { BrowserWindow } = require("electron"); + const other = { createWindow() {} }; + other.createWindow(); + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + createWindow(); + `; + expect(() => + runInNewContext(source, { require: () => ({ BrowserWindow: class {} }) }), + ).not.toThrow(); + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + }); +}); + describe("Electron option evidence", () => { it.each([ '({ webPreferences: { preload: "./preload.js", sandbox: true } } as const)', diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 9210fe87a3f..cc5c5326c14 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -864,6 +864,11 @@ const moduleFunctionFirstRead = ( } else functions.set(name, node); } const indexedReads = reads; + const firstStatement = body[0]; + const program = + firstStatement === undefined ? undefined : parents.get(firstStatement); + const classicScript = + t.isProgram(program) && program.sourceType === "script"; const active = new Set(); for (let index = 0; index < body.length; index++) { const statement = body[index]; @@ -871,13 +876,31 @@ const moduleFunctionFirstRead = ( traverseJavaScriptAst(statement, { enter(node, parent) { if (t.isFunction(node)) active.add(node); + let name: string | null = null; if ( - !t.isIdentifier(node) || - parent === null || - !t.isReferenced(node, parent) + t.isIdentifier(node) && + parent !== null && + t.isReferenced(node, parent) ) - return; - const fn = functions.get(node.name); + name = node.name; + else if ( + classicScript && + (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) + ) { + const receiver = unwrapJavaScriptExpression(node.object).node; + // Classic scripts expose hoisted functions through the global object. + // Property names are not referenced identifiers; keep their read timing too. + if ( + t.isThisExpression(receiver) || + (t.isIdentifier(receiver) && + (receiver.name === "globalThis" || + receiver.name === "window" || + receiver.name === "self")) + ) + name = semanticStaticPropertyKey(node.property, node.computed); + } + if (name === null) return; + const fn = functions.get(name); if (fn == null || active.has(fn)) return; const current = indexedReads.get(fn); if (current === null || current === undefined) return; diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index 8bf380c159a..01513cc9b49 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -86,3 +86,54 @@ cliTest.for(["CLI", "stdio MCP"] as const)( } }, ); + +cliTest.for(["CLI", "stdio MCP"] as const)( + "preserves classic global initialization uncertainty through %s", + async (surface, { cli }) => { + const root = await createTestTempDirectory( + "rea-electron-global-initialization-", + ); + const source = (early: boolean) => ` + const { BrowserWindow } = require("electron"); + ${early ? "globalThis.createWindow();" : ""} + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + ${early ? "" : "globalThis.createWindow();"} + createWindow(); + throw new Error("must not execute source"); + `; + await writeFixtureFiles(root, { + "early.js": source(true), + "late.js": source(false), + "index.html": + '', + }); + const result = await analyzeJavaScriptDirectory(surface, cli, root); + expect(result.statistics.parse_failures).toBe(0); + const windows = result.graph.nodes.filter( + ({ kind }) => kind === "browser-window", + ); + expect(windows).toHaveLength(2); + const inSource = (name: string) => + windows + .flatMap(({ observations }) => observations) + .filter( + ({ evidence }) => + evidence.location.available && + evidence.location.value.kind === "source-range" && + evidence.location.value.source === name, + ); + expect(inSource("early.js")).toHaveLength(1); + expect(inSource("early.js")[0]?.properties).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); + expect(inSource("late.js")).toHaveLength(1); + expect(inSource("late.js")[0]?.properties).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + }, +); From 4cd804cbcc17dc76f02c27f327f577d2fc7b3665 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Mon, 2 Nov 2026 19:10:23 +0800 Subject: [PATCH 07/21] fix(javascript): bind first activations to lexical identities --- .../electronStaticAnalysisOptions.test.ts | 20 ++++++ .../javascript/electronStaticOptionObjects.ts | 2 +- .../javascript/electronStaticRenderer.ts | 2 +- .../javascript/javascriptAstFingerprint.ts | 2 +- .../javascriptBundledRequireOrigin.ts | 6 +- .../javascript/javascriptNetworkRequests.ts | 3 +- src/domain/javascript/javascriptRouteScan.ts | 8 +-- .../javascriptSemanticAmbientWrites.ts | 2 +- .../javascriptSemanticAsyncEffects.ts | 4 +- .../javascriptSemanticCallResolution.test.ts | 4 +- .../javascriptSemanticCallResolution.ts | 6 +- .../javascriptSemanticChildProcesses.ts | 6 +- .../javascriptSemanticDataEffects.ts | 6 +- .../javascriptSemanticExpressionShapes.ts | 2 +- .../javascriptSemanticGetterResultWalker.ts | 2 +- .../javascriptSemanticMapOperations.ts | 3 +- .../javascriptSemanticMemberMutations.ts | 6 +- .../javascriptSemanticMutationInitializers.ts | 62 +++++++++++++++---- .../javascriptSemanticProjectedSources.ts | 2 +- .../javascript/javascriptSemanticPromises.ts | 2 +- .../javascriptSemanticRequireOrigin.ts | 8 +-- .../javascriptSemanticReturnedReferences.ts | 6 +- .../javascript/javascriptSemanticReturns.ts | 2 +- .../javascript/javascriptSemanticValues.ts | 8 +-- .../electronModuleInitializationCli.test.ts | 17 +++-- 25 files changed, 109 insertions(+), 82 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index f33c30f5d49..2badb176c71 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -347,6 +347,8 @@ describe("Classic-script global function activation", () => { "window.createWindow();", 'self["createWindow"]();', "this.createWindow();", + "const root = globalThis; root.createWindow();", + "const root = window; const alias = root; alias.createWindow();", ])("keeps early global access unresolved: %s", (activation) => { const body = (early: boolean) => ` const { BrowserWindow } = require("electron"); @@ -387,6 +389,24 @@ describe("Classic-script global function activation", () => { }); }); + it("does not confuse an unrelated parameter with the module function", () => { + const source = ` + const { BrowserWindow } = require("electron"); + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + function helper(createWindow) { createWindow(); } + createWindow(); + `; + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + }); + it("does not treat an ES module function as a global property", () => { const source = ` import { BrowserWindow } from "electron"; diff --git a/src/domain/javascript/electronStaticOptionObjects.ts b/src/domain/javascript/electronStaticOptionObjects.ts index 1f2a2baf1e2..9c0e7dc2197 100644 --- a/src/domain/javascript/electronStaticOptionObjects.ts +++ b/src/domain/javascript/electronStaticOptionObjects.ts @@ -32,7 +32,7 @@ const optionObjectCandidate = ( !binding.declarationKinds.has("const") || initializer === undefined || initializer.projection.length !== 0 || - !semanticBindingAtRead(binding, node, index.bindings.parentsByNode) + !semanticBindingAtRead(binding, node, index.bindings) .hasDefiniteInitializer ) return undefined; diff --git a/src/domain/javascript/electronStaticRenderer.ts b/src/domain/javascript/electronStaticRenderer.ts index 578dff96b6b..d68630c0450 100644 --- a/src/domain/javascript/electronStaticRenderer.ts +++ b/src/domain/javascript/electronStaticRenderer.ts @@ -75,7 +75,7 @@ export const resolveElectronBrowserWindowReceiver = ( if ( initializer === undefined || initializer.projection.length !== 0 || - !semanticBindingAtRead(binding, receiver, index.bindings.parentsByNode) + !semanticBindingAtRead(binding, receiver, index.bindings) .hasDefiniteInitializer ) return undefined; diff --git a/src/domain/javascript/javascriptAstFingerprint.ts b/src/domain/javascript/javascriptAstFingerprint.ts index 861f7651ab3..f7d4e5be446 100644 --- a/src/domain/javascript/javascriptAstFingerprint.ts +++ b/src/domain/javascript/javascriptAstFingerprint.ts @@ -89,7 +89,7 @@ export const collectJavaScriptExports = ( const read = semanticBindingAtRead( withoutUnusedFactoryDefaults(binding, roles), reference, - bindings.parentsByNode, + bindings, ); if (read.status !== "ordered") return "unresolved"; return read.binding.initializers.length === 0 && diff --git a/src/domain/javascript/javascriptBundledRequireOrigin.ts b/src/domain/javascript/javascriptBundledRequireOrigin.ts index bed7e9da70c..0e7db5e8565 100644 --- a/src/domain/javascript/javascriptBundledRequireOrigin.ts +++ b/src/domain/javascript/javascriptBundledRequireOrigin.ts @@ -175,11 +175,7 @@ const canonicalWebpackInteropBindings = ( const binding = resolveSemanticBindingState(state, node, node.name); if (binding === undefined) continue; if (loaderBindingIds.has(binding.bindingId)) return true; - const selected = semanticBindingAtRead( - binding, - node, - state.parentsByNode, - ).binding; + const selected = semanticBindingAtRead(binding, node, state).binding; for (const source of [ ...selected.initializers, ...selected.referenceInitializers, diff --git a/src/domain/javascript/javascriptNetworkRequests.ts b/src/domain/javascript/javascriptNetworkRequests.ts index efc897f7143..a2b4cfc8ec8 100644 --- a/src/domain/javascript/javascriptNetworkRequests.ts +++ b/src/domain/javascript/javascriptNetworkRequests.ts @@ -89,8 +89,7 @@ const isXhrOpenRequest = ( if ( initializer === undefined || initializer.projection.length !== 0 || - !semanticBindingAtRead(binding, receiver, bindings.parentsByNode) - .hasDefiniteInitializer + !semanticBindingAtRead(binding, receiver, bindings).hasDefiniteInitializer ) return false; receiver = unwrapJavaScriptExpression(initializer.node).node; diff --git a/src/domain/javascript/javascriptRouteScan.ts b/src/domain/javascript/javascriptRouteScan.ts index e3e1f38992b..06c55f45579 100644 --- a/src/domain/javascript/javascriptRouteScan.ts +++ b/src/domain/javascript/javascriptRouteScan.ts @@ -452,7 +452,7 @@ export class JavaScriptRouteScan { const binding = semanticBindingAtRead( declared, node, - this.index.bindings.parentsByNode, + this.index.bindings, ).binding; for (const initializers of [ binding.initializers, @@ -1020,11 +1020,7 @@ export class JavaScriptRouteScan { seen.add(node); const binding = index.bindingForReferenceAt(node); if (binding === undefined) return; - const read = semanticBindingAtRead( - binding, - node, - index.bindings.parentsByNode, - ); + const read = semanticBindingAtRead(binding, node, index.bindings); if (!read.hasDefiniteInitializer) return; const initializer = semanticStableInitializer( read.binding, diff --git a/src/domain/javascript/javascriptSemanticAmbientWrites.ts b/src/domain/javascript/javascriptSemanticAmbientWrites.ts index 688ff5c4a8b..99b63daed29 100644 --- a/src/domain/javascript/javascriptSemanticAmbientWrites.ts +++ b/src/domain/javascript/javascriptSemanticAmbientWrites.ts @@ -345,7 +345,7 @@ export const createAmbientPathResolver = ( const readAt = current.readsAtSelf ? root : capture; const atRead = possibleWrites && readAt !== undefined - ? semanticBindingAtRead(binding, readAt, state.parentsByNode) + ? semanticBindingAtRead(binding, readAt, state) : undefined; const selected = atRead?.binding ?? binding; if (possibleWrites && atRead?.hasDefiniteInitializer === false) diff --git a/src/domain/javascript/javascriptSemanticAsyncEffects.ts b/src/domain/javascript/javascriptSemanticAsyncEffects.ts index 591a0f4e367..c64b479b10c 100644 --- a/src/domain/javascript/javascriptSemanticAsyncEffects.ts +++ b/src/domain/javascript/javascriptSemanticAsyncEffects.ts @@ -191,7 +191,7 @@ const emitterIdentity = ( if (t.isIdentifier(node)) { const binding = resolveSemanticBindingState(state, node, node.name); if (binding !== undefined) { - const read = semanticBindingAtRead(binding, node, state.parentsByNode); + const read = semanticBindingAtRead(binding, node, state); const origins = [ ...read.binding.initializers, ...read.binding.referenceInitializers, @@ -270,7 +270,7 @@ const collectTimer = (input: TimerCollectionInput): void => { const snapshot = semanticBindingAtRead( handle, node.arguments[0], - state.parentsByNode, + state, ); // A const handle has the same value inside a later closure even // when the source positions belong to different function bodies. diff --git a/src/domain/javascript/javascriptSemanticCallResolution.test.ts b/src/domain/javascript/javascriptSemanticCallResolution.test.ts index af65fb35ac3..ad28155ff6c 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.test.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.test.ts @@ -206,7 +206,7 @@ it.each([ ) { reads++; expect( - semanticBindingAtRead(binding, node.callee, state.parentsByNode) + semanticBindingAtRead(binding, node.callee, state) .hasDefiniteInitializer, ).toBe(expected); } @@ -411,7 +411,7 @@ it.each(["||=", "??="])( ) { reads++; expect( - semanticBindingAtRead(binding, node.callee, state.parentsByNode) + semanticBindingAtRead(binding, node.callee, state) .hasDefiniteInitializer, ).toBe(true); } diff --git a/src/domain/javascript/javascriptSemanticCallResolution.ts b/src/domain/javascript/javascriptSemanticCallResolution.ts index 0dde3540784..57d94066eb6 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.ts @@ -104,11 +104,7 @@ const resolveIdentifier = ( complete: false, reason: `Unresolved call target ${node.name}.`, }; - const read = semanticBindingAtRead( - binding, - node, - context.state.parentsByNode, - ); + const read = semanticBindingAtRead(binding, node, context.state); // A full read re-enters the same candidate set wherever the chain returns // to this binding. Close that cycle at the binding; position-narrowed reads // keep their per-initializer cycle handling. diff --git a/src/domain/javascript/javascriptSemanticChildProcesses.ts b/src/domain/javascript/javascriptSemanticChildProcesses.ts index ea8c872e19c..241062d1c90 100644 --- a/src/domain/javascript/javascriptSemanticChildProcesses.ts +++ b/src/domain/javascript/javascriptSemanticChildProcesses.ts @@ -338,11 +338,7 @@ const resolveChildCandidates = ( // An alias captures its source at its initializer read, not at the later // interaction. The shared selector retains all sources across uncertain // control flow, loops and writes in other activations. - const snapshot = semanticBindingAtRead( - binding, - current, - state.parentsByNode, - ); + const snapshot = semanticBindingAtRead(binding, current, state); const selected = snapshot.binding; const initializers = [ ...selected.initializers, diff --git a/src/domain/javascript/javascriptSemanticDataEffects.ts b/src/domain/javascript/javascriptSemanticDataEffects.ts index 732b309fce4..d6e37583ff0 100644 --- a/src/domain/javascript/javascriptSemanticDataEffects.ts +++ b/src/domain/javascript/javascriptSemanticDataEffects.ts @@ -261,11 +261,7 @@ const soleWriteReachesRead = ( request: t.Node | undefined, ): boolean => { if (binding === undefined || request === undefined) return false; - const snapshot = semanticBindingAtRead( - binding, - read, - context.state.parentsByNode, - ); + const snapshot = semanticBindingAtRead(binding, read, context.state); const initializers = snapshot.binding.initializers.filter( ({ node }) => semanticEffectTiming(read, node, context.state) !== "after", ); diff --git a/src/domain/javascript/javascriptSemanticExpressionShapes.ts b/src/domain/javascript/javascriptSemanticExpressionShapes.ts index 423bf91dd3c..395a5af1d62 100644 --- a/src/domain/javascript/javascriptSemanticExpressionShapes.ts +++ b/src/domain/javascript/javascriptSemanticExpressionShapes.ts @@ -96,7 +96,7 @@ export const createSemanticExpressionShapeResolver = ( const initializer = semanticStableInitializer(binding, state); if (initializer === undefined || initializer.projection.length > 0) return "unknown"; - const read = semanticBindingAtRead(binding, node, state.parentsByNode); + const read = semanticBindingAtRead(binding, node, state); if (read.status !== "ordered" || !read.hasDefiniteInitializer) return "unknown"; node = initializer.node; diff --git a/src/domain/javascript/javascriptSemanticGetterResultWalker.ts b/src/domain/javascript/javascriptSemanticGetterResultWalker.ts index 7c2fe5f831c..3144b0d1ab5 100644 --- a/src/domain/javascript/javascriptSemanticGetterResultWalker.ts +++ b/src/domain/javascript/javascriptSemanticGetterResultWalker.ts @@ -208,7 +208,7 @@ export class GetterResultWalker { const { binding: origins } = semanticBindingAtRead( binding, expression, - state.parentsByNode, + state, ); const aliases: AliasVisit = { identity, diff --git a/src/domain/javascript/javascriptSemanticMapOperations.ts b/src/domain/javascript/javascriptSemanticMapOperations.ts index 9cf0a2a4c1b..ce559fe3ba9 100644 --- a/src/domain/javascript/javascriptSemanticMapOperations.ts +++ b/src/domain/javascript/javascriptSemanticMapOperations.ts @@ -54,8 +54,7 @@ export const isIntrinsicMapLookup = ( if ( initializer === undefined || initializer.projection.length !== 0 || - !semanticBindingAtRead(binding, receiver, bindings.parentsByNode) - .hasDefiniteInitializer + !semanticBindingAtRead(binding, receiver, bindings).hasDefiniteInitializer ) return false; receiver = unwrapJavaScriptExpression(initializer.node).node; diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index aff9ca30d63..002405d48fa 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -161,11 +161,7 @@ const localAccessorMethods = ( if (t.isIdentifier(node)) { const binding = resolveSemanticBindingState(state, node, node.name); if (binding === undefined) continue; - const selected = semanticBindingAtRead( - binding, - node, - state.parentsByNode, - ).binding; + const selected = semanticBindingAtRead(binding, node, state).binding; for (const source of [ ...selected.initializers, ...selected.referenceInitializers, diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index cc5c5326c14..d4222308eb5 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -840,6 +840,7 @@ const moduleFunctionFirstRead = ( declaration: t.FunctionDeclaration, body: readonly t.Statement[], parents: WeakMap, + state?: JavaScriptSemanticAnalysisState, ): number | null => { const cache = initializerPositionCache(parents).moduleFunctionReads; let reads = cache.get(body); @@ -869,6 +870,25 @@ const moduleFunctionFirstRead = ( firstStatement === undefined ? undefined : parents.get(firstStatement); const classicScript = t.isProgram(program) && program.sourceType === "script"; + const globalReceiver = ( + input: t.Node, + seen = new Set(), + ): boolean => { + const node = unwrapJavaScriptExpression(input).node; + if (t.isThisExpression(node)) return true; + if (!t.isIdentifier(node)) return false; + const binding = + state === undefined + ? undefined + : resolveSemanticBindingState(state, node, node.name); + if (binding === undefined) + return ["globalThis", "window", "self"].includes(node.name); + if (seen.has(binding.bindingId)) return false; + seen.add(binding.bindingId); + return binding.initializers.some(({ node: value }) => + globalReceiver(value, seen), + ); + }; const active = new Set(); for (let index = 0; index < body.length; index++) { const statement = body[index]; @@ -881,22 +901,28 @@ const moduleFunctionFirstRead = ( t.isIdentifier(node) && parent !== null && t.isReferenced(node, parent) - ) - name = node.name; - else if ( + ) { + const candidate = functions.get(node.name); + const binding = + state === undefined + ? undefined + : resolveSemanticBindingState(state, node, node.name); + if ( + state === undefined || + (candidate != null && + binding?.initializers.some( + ({ node: value }) => value === candidate, + )) + ) + name = node.name; + } else if ( classicScript && (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) ) { const receiver = unwrapJavaScriptExpression(node.object).node; // Classic scripts expose hoisted functions through the global object. // Property names are not referenced identifiers; keep their read timing too. - if ( - t.isThisExpression(receiver) || - (t.isIdentifier(receiver) && - (receiver.name === "globalThis" || - receiver.name === "window" || - receiver.name === "self")) - ) + if (globalReceiver(receiver)) name = semanticStaticPropertyKey(node.property, node.computed); } if (name === null) return; @@ -925,8 +951,13 @@ const moduleFunctionFirstRead = ( export const semanticBindingAtRead = ( binding: JavaScriptSemanticBindingState, read: t.Node, - parents: WeakMap, + context: WeakMap | JavaScriptSemanticAnalysisState, ): SemanticBindingRead => { + const state = "parentsByNode" in context ? context : undefined; + const parents = + state === undefined + ? (context as WeakMap) + : state.parentsByNode; if ( binding.initializers.length === 0 && binding.referenceInitializers.length === 0 @@ -1050,7 +1081,12 @@ export const semanticBindingAtRead = ( functionPosition !== null && sourcePosition.body === functionPosition.body && t.isFunctionDeclaration(enclosingFunction) - ? moduleFunctionFirstRead(enclosingFunction, sourcePosition.body, parents) + ? moduleFunctionFirstRead( + enclosingFunction, + sourcePosition.body, + parents, + state, + ) : null; const moduleConstInitializedBeforeActivation = moduleConstBinding && @@ -1415,7 +1451,7 @@ export const semanticBindingHasPriorValueWrite = ( ): boolean => { if (binding.definitions.some(({ kind }) => kind === "function")) return true; const writes = state.bindingWrites.get(binding.bindingId) ?? []; - const read = semanticBindingAtRead(binding, site, state.parentsByNode); + const read = semanticBindingAtRead(binding, site, state); const retained = read.status === "ordered" ? new Set([ diff --git a/src/domain/javascript/javascriptSemanticProjectedSources.ts b/src/domain/javascript/javascriptSemanticProjectedSources.ts index f1cb5f9c73f..aaa9ae14222 100644 --- a/src/domain/javascript/javascriptSemanticProjectedSources.ts +++ b/src/domain/javascript/javascriptSemanticProjectedSources.ts @@ -225,7 +225,7 @@ const projectedSourceFactsAtRead = ( readonly retainsOrigin: boolean; } | undefined => { - const read = semanticBindingAtRead(binding, reference, state.parentsByNode); + const read = semanticBindingAtRead(binding, reference, state); const captured = [ ...read.binding.initializers, ...read.binding.referenceInitializers, diff --git a/src/domain/javascript/javascriptSemanticPromises.ts b/src/domain/javascript/javascriptSemanticPromises.ts index 250285e458b..2d83ad662e9 100644 --- a/src/domain/javascript/javascriptSemanticPromises.ts +++ b/src/domain/javascript/javascriptSemanticPromises.ts @@ -443,7 +443,7 @@ const resolvePromiseExpression = ( const binding = resolveSemanticBindingState(state, node, node.name); if (binding === undefined || seenBindings.has(binding.bindingId)) return unresolvedPromise(); - const read = semanticBindingAtRead(binding, node, state.parentsByNode); + const read = semanticBindingAtRead(binding, node, state); if ( read.status !== "ordered" || !read.hasDefiniteInitializer || diff --git a/src/domain/javascript/javascriptSemanticRequireOrigin.ts b/src/domain/javascript/javascriptSemanticRequireOrigin.ts index 426caf95f37..ffb0caf2749 100644 --- a/src/domain/javascript/javascriptSemanticRequireOrigin.ts +++ b/src/domain/javascript/javascriptSemanticRequireOrigin.ts @@ -493,11 +493,7 @@ const selectedRequireSourcesAt = ( } if (facts === undefined) { unknown = true; - const retained = semanticBindingAtRead( - binding, - node, - state.parentsByNode, - ).binding; + const retained = semanticBindingAtRead(binding, node, state).binding; pending.push( ...inheritLoaderSourceContext( current, @@ -1266,7 +1262,7 @@ const hasCommonJsModuleSource = ( continue; } if (binding === undefined) continue; - const read = semanticBindingAtRead(binding, value, state.parentsByNode); + const read = semanticBindingAtRead(binding, value, state); const retainsMainModule = mainModulePath && commonJsWrapperBindingDeclaration(value, "require", state) !== diff --git a/src/domain/javascript/javascriptSemanticReturnedReferences.ts b/src/domain/javascript/javascriptSemanticReturnedReferences.ts index cd9a1717c77..4a3e93cb006 100644 --- a/src/domain/javascript/javascriptSemanticReturnedReferences.ts +++ b/src/domain/javascript/javascriptSemanticReturnedReferences.ts @@ -390,11 +390,7 @@ export const createSemanticReturnedReferences = ( result.precision = "widened"; if (sourceGenericInvocation) result.unresolvedInvocation = true; } - const selected = semanticBindingAtRead( - binding, - node, - state.parentsByNode, - ).binding; + const selected = semanticBindingAtRead(binding, node, state).binding; for (const initializer of [ ...selected.initializers, ...selected.referenceInitializers, diff --git a/src/domain/javascript/javascriptSemanticReturns.ts b/src/domain/javascript/javascriptSemanticReturns.ts index a34b7be7805..31e23057013 100644 --- a/src/domain/javascript/javascriptSemanticReturns.ts +++ b/src/domain/javascript/javascriptSemanticReturns.ts @@ -166,7 +166,7 @@ const callableIdsForBinding = ( const selected = read === undefined ? binding - : semanticBindingAtRead(binding, read, state.parentsByNode).binding; + : semanticBindingAtRead(binding, read, state).binding; const initializer = selected.initializers[0]; if ( initializer === undefined || diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index 11b48f96633..bc2e07e9f15 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -682,11 +682,7 @@ const evaluateExpressionValue = ( const binding = resolveSemanticBindingState(context.state, node, node.name); if (binding === undefined) return { status: "unknown", reason: `Unbound identifier ${node.name}.` }; - const read = semanticBindingAtRead( - binding, - node, - context.state.parentsByNode, - ); + const read = semanticBindingAtRead(binding, node, context.state); if ( read.status === "unresolved" && binding.mutable && @@ -1377,7 +1373,7 @@ const provenanceForBindingAtRead = ( const { binding: snapshot } = semanticBindingAtRead( binding, read, - context.state.parentsByNode, + context.state, ); if (snapshot === binding) return provenanceForBinding(binding, context); if (context.bindings.has(binding.bindingId)) diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index 01513cc9b49..e7f28c44e55 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -87,18 +87,27 @@ cliTest.for(["CLI", "stdio MCP"] as const)( }, ); -cliTest.for(["CLI", "stdio MCP"] as const)( +cliTest.for([ + ["CLI", false], + ["stdio MCP", false], + ["CLI", true], + ["stdio MCP", true], +] as const)( "preserves classic global initialization uncertainty through %s", - async (surface, { cli }) => { + async ([surface, alias], { cli }) => { const root = await createTestTempDirectory( "rea-electron-global-initialization-", ); + const activation = alias + ? "root.createWindow();" + : "globalThis.createWindow();"; const source = (early: boolean) => ` const { BrowserWindow } = require("electron"); - ${early ? "globalThis.createWindow();" : ""} + ${alias ? "const root = globalThis;" : ""} + ${early ? activation : ""} const webPreferences = { nodeIntegration: true }; function createWindow() { return new BrowserWindow({ webPreferences }); } - ${early ? "" : "globalThis.createWindow();"} + ${early ? "" : activation} createWindow(); throw new Error("must not execute source"); `; From 507b50a97ca70bab1e25bbb3c201aff1097c522c Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Mon, 2 Nov 2026 23:20:20 +0800 Subject: [PATCH 08/21] fix(javascript): retain uncertain global activation timing --- .../electronStaticAnalysisOptions.test.ts | 36 ++++++ .../javascriptSemanticMutationInitializers.ts | 106 ++++++++++++++---- 2 files changed, 122 insertions(+), 20 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 2badb176c71..4282fdbc9de 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -349,6 +349,10 @@ describe("Classic-script global function activation", () => { "this.createWindow();", "const root = globalThis; root.createWindow();", "const root = window; const alias = root; alias.createWindow();", + "const root = globalThis.window; root.createWindow();", + "const { root } = { root: globalThis }; root.createWindow();", + "const key = 'createWindow'; globalThis[key]();", + "with ({}) { createWindow(); }", ])("keeps early global access unresolved: %s", (activation) => { const body = (early: boolean) => ` const { BrowserWindow } = require("electron"); @@ -389,6 +393,38 @@ describe("Classic-script global function activation", () => { }); }); + it("keeps callbacks in hoisted default parameters uncertain", () => { + const source = ` + const { BrowserWindow } = require("electron"); + createWindow(); + const webPreferences = { nodeIntegration: true }; + function createWindow(make = () => new BrowserWindow({ webPreferences })) { return make(); } + `; + expect(() => + runInNewContext(source, { require: () => ({ BrowserWindow: class {} }) }), + ).toThrow(/before initialization/); + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ web_preferences_status: "dynamic", web_preferences: [] }); + }); + + it("keeps a long flat global alias chain stack safe", () => { + const aliases = ["const root0 = globalThis;"]; + for (let index = 1; index < 6000; index++) + aliases.push("const root" + index + " = root" + (index - 1) + ";"); + const source = ` + const { BrowserWindow } = require("electron"); + ${aliases.join("\n")} + root5999.createWindow(); + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + createWindow(); + `; + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ web_preferences_status: "dynamic", web_preferences: [] }); + }); + it("does not confuse an unrelated parameter with the module function", () => { const source = ` const { BrowserWindow } = require("electron"); diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index d4222308eb5..f617dabab2b 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -870,24 +870,62 @@ const moduleFunctionFirstRead = ( firstStatement === undefined ? undefined : parents.get(firstStatement); const classicScript = t.isProgram(program) && program.sourceType === "script"; - const globalReceiver = ( - input: t.Node, - seen = new Set(), - ): boolean => { - const node = unwrapJavaScriptExpression(input).node; - if (t.isThisExpression(node)) return true; - if (!t.isIdentifier(node)) return false; - const binding = - state === undefined - ? undefined - : resolveSemanticBindingState(state, node, node.name); - if (binding === undefined) - return ["globalThis", "window", "self"].includes(node.name); - if (seen.has(binding.bindingId)) return false; - seen.add(binding.bindingId); - return binding.initializers.some(({ node: value }) => - globalReceiver(value, seen), - ); + const globalReceivers = new WeakMap(); + const globalReceiver = (input: t.Node): boolean | null => { + if (globalReceivers.has(input)) return globalReceivers.get(input) ?? null; + const pending = [input]; + const seen = new Set(); + let unknown = false; + let global = false; + while (pending.length > 0) { + const current = pending.pop(); + if (current === undefined) continue; + if (seen.has(current)) { + unknown = true; + continue; + } + seen.add(current); + if (globalReceivers.has(current)) { + const cached = globalReceivers.get(current); + if (cached === true) global = true; + if (cached === null) unknown = true; + continue; + } + const node = unwrapJavaScriptExpression(current).node; + if (t.isThisExpression(node)) global = true; + else if (t.isIdentifier(node)) { + const binding = + state === undefined + ? undefined + : resolveSemanticBindingState(state, node, node.name); + if (binding === undefined) { + if (["globalThis", "window", "self"].includes(node.name)) + global = true; + else unknown = true; + } else { + if ( + binding.initializers.length === 0 || + binding.referenceInitializers.length > 0 + ) + unknown = true; + for (const initializer of binding.initializers) { + if (initializer.projection.length > 0) unknown = true; + else pending.push(initializer.node); + } + } + } else if ( + !t.isObjectExpression(node) && + !t.isArrayExpression(node) && + !t.isLiteral(node) && + !t.isFunction(node) + ) + unknown = true; + } + const result = global ? true : unknown ? null : false; + globalReceivers.set(input, result); + // These are conservative may-alias facts, shared within this source scan. + for (const node of seen) globalReceivers.set(node, result); + return result; }; const active = new Set(); for (let index = 0; index < body.length; index++) { @@ -907,6 +945,19 @@ const moduleFunctionFirstRead = ( state === undefined ? undefined : resolveSemanticBindingState(state, node, node.name); + if ( + candidate != null && + state !== undefined && + semanticResolutionBlocked(state, node, node.name) + ) { + const current = indexedReads.get(candidate); + if (current !== null && current !== undefined) + indexedReads.set( + candidate, + active.size > 0 ? null : Math.min(current, index), + ); + return; + } if ( state === undefined || (candidate != null && @@ -922,8 +973,21 @@ const moduleFunctionFirstRead = ( const receiver = unwrapJavaScriptExpression(node.object).node; // Classic scripts expose hoisted functions through the global object. // Property names are not referenced identifiers; keep their read timing too. - if (globalReceiver(receiver)) + if (globalReceiver(receiver) !== false) { name = semanticStaticPropertyKey(node.property, node.computed); + if (name === null) { + for (const fn of functions.values()) { + if (fn == null) continue; + const current = indexedReads.get(fn); + if (current !== null && current !== undefined) + indexedReads.set( + fn, + active.size > 0 ? null : Math.min(current, index), + ); + } + return; + } + } } if (name === null) return; const fn = functions.get(name); @@ -1068,8 +1132,10 @@ export const semanticBindingAtRead = ( let owner = parents.get(enclosingFunction); owner !== undefined; owner = parents.get(owner) - ) + ) { + if (t.isFunction(owner)) return null; if (t.isStatement(owner)) return statementPosition(owner, parents); + } return null; }; const functionPosition = moduleConstBinding From acf94528c38dde086fc0be27b6d201e19fd094d4 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Mon, 2 Nov 2026 23:47:50 +0800 Subject: [PATCH 09/21] fix(javascript): isolate receiver facts and share computed reads --- .../electronStaticAnalysisOptions.test.ts | 3 ++ .../javascriptSemanticMutationInitializers.ts | 30 ++++++++++++------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 4282fdbc9de..7cc21a17431 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -465,6 +465,9 @@ describe("Classic-script global function activation", () => { const source = ` const { BrowserWindow } = require("electron"); const other = { createWindow() {} }; + let root = other; + root = globalThis; + root.document; other.createWindow(); const webPreferences = { nodeIntegration: true }; function createWindow() { return new BrowserWindow({ webPreferences }); } diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index f617dabab2b..08a179d7f06 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -922,12 +922,12 @@ const moduleFunctionFirstRead = ( unknown = true; } const result = global ? true : unknown ? null : false; + // The union belongs to this receiver, not each of its possible origins. globalReceivers.set(input, result); - // These are conservative may-alias facts, shared within this source scan. - for (const node of seen) globalReceivers.set(node, result); return result; }; const active = new Set(); + let unknownPropertyRead: number | null = Infinity; for (let index = 0; index < body.length; index++) { const statement = body[index]; if (statement === undefined) continue; @@ -976,15 +976,11 @@ const moduleFunctionFirstRead = ( if (globalReceiver(receiver) !== false) { name = semanticStaticPropertyKey(node.property, node.computed); if (name === null) { - for (const fn of functions.values()) { - if (fn == null) continue; - const current = indexedReads.get(fn); - if (current !== null && current !== undefined) - indexedReads.set( - fn, - active.size > 0 ? null : Math.min(current, index), - ); - } + if (unknownPropertyRead !== null) + unknownPropertyRead = + active.size > 0 + ? null + : Math.min(unknownPropertyRead, index); return; } } @@ -1007,6 +1003,18 @@ const moduleFunctionFirstRead = ( }, }); } + // Unknown global keys share one timing fact across the module functions. + for (const fn of functions.values()) { + if (fn == null) continue; + const current = indexedReads.get(fn); + if (current !== null && current !== undefined) + indexedReads.set( + fn, + unknownPropertyRead === null + ? null + : Math.min(current, unknownPropertyRead), + ); + } } const first = reads.get(declaration); return first !== undefined && Number.isFinite(first) ? first : null; From 438a745ba7a8e8a5b4e053103cf009c3c8771ad7 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 09:09:31 +0800 Subject: [PATCH 10/21] fix(javascript): retain projected and opaque global activations --- .../electronStaticAnalysisOptions.test.ts | 17 ++- .../javascriptSemanticMutationInitializers.ts | 111 +++++++++++++----- 2 files changed, 100 insertions(+), 28 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 7cc21a17431..102c74d5356 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -353,6 +353,11 @@ describe("Classic-script global function activation", () => { "const { root } = { root: globalThis }; root.createWindow();", "const key = 'createWindow'; globalThis[key]();", "with ({}) { createWindow(); }", + "const { createWindow: start } = globalThis; start();", + "const start = (createWindow ||= null); start();", + "const root = { __proto__: globalThis }; root.createWindow();", + "const root = { ...globalThis }; root.createWindow();", + "(0, eval)('createWindow()');", ])("keeps early global access unresolved: %s", (activation) => { const body = (early: boolean) => ` const { BrowserWindow } = require("electron"); @@ -407,11 +412,21 @@ describe("Classic-script global function activation", () => { analyzeJavaScriptStaticSource(source).electron.browser_windows[0], ).toMatchObject({ web_preferences_status: "dynamic", web_preferences: [] }); }); +}); +describe("Classic-script global receiver identity", () => { it("keeps a long flat global alias chain stack safe", () => { const aliases = ["const root0 = globalThis;"]; for (let index = 1; index < 6000; index++) - aliases.push("const root" + index + " = root" + (index - 1) + ";"); + aliases.push( + "const root" + + index + + " = root" + + (index - 1) + + "; root" + + index + + ".document;", + ); const source = ` const { BrowserWindow } = require("electron"); ${aliases.join("\n")} diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 08a179d7f06..4effec94197 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -10,6 +10,7 @@ import { import { semanticStaticPropertyKey, + semanticWriteSiteReadsFirst, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; import { @@ -872,27 +873,47 @@ const moduleFunctionFirstRead = ( t.isProgram(program) && program.sourceType === "script"; const globalReceivers = new WeakMap(); const globalReceiver = (input: t.Node): boolean | null => { - if (globalReceivers.has(input)) return globalReceivers.get(input) ?? null; - const pending = [input]; - const seen = new Set(); - let unknown = false; - let global = false; + const pending: { node: t.Node; finish: boolean }[] = [ + { node: input, finish: false }, + ]; + const visiting = new Set(); + const origins = new WeakMap< + t.Node, + { dependencies: t.Node[]; unknown: boolean; global: boolean } + >(); while (pending.length > 0) { - const current = pending.pop(); - if (current === undefined) continue; - if (seen.has(current)) { - unknown = true; + const frame = pending.pop(); + if (frame === undefined) continue; + const current = frame.node; + if (frame.finish) { + const fact = origins.get(current); + if (fact === undefined) continue; + let global = fact.global; + let unknown = fact.unknown; + for (const dependency of fact.dependencies) { + const answer = globalReceivers.get(dependency); + if (answer === true) global = true; + if (answer === null || answer === undefined) unknown = true; + } + globalReceivers.set(current, global ? true : unknown ? null : false); + visiting.delete(current); continue; } - seen.add(current); - if (globalReceivers.has(current)) { - const cached = globalReceivers.get(current); - if (cached === true) global = true; - if (cached === null) unknown = true; + if (globalReceivers.has(current)) continue; + if (visiting.has(current)) { + // A back edge has no finite identity proof; retain uncertainty. + globalReceivers.set(current, null); continue; } + visiting.add(current); + const fact = { + dependencies: [] as t.Node[], + unknown: false, + global: false, + }; const node = unwrapJavaScriptExpression(current).node; - if (t.isThisExpression(node)) global = true; + if (node !== current) fact.dependencies.push(node); + else if (t.isThisExpression(node)) fact.global = true; else if (t.isIdentifier(node)) { const binding = state === undefined @@ -900,33 +921,42 @@ const moduleFunctionFirstRead = ( : resolveSemanticBindingState(state, node, node.name); if (binding === undefined) { if (["globalThis", "window", "self"].includes(node.name)) - global = true; - else unknown = true; + fact.global = true; + else fact.unknown = true; } else { if ( binding.initializers.length === 0 || binding.referenceInitializers.length > 0 ) - unknown = true; + fact.unknown = true; for (const initializer of binding.initializers) { - if (initializer.projection.length > 0) unknown = true; - else pending.push(initializer.node); + if (initializer.projection.length > 0) fact.unknown = true; + else fact.dependencies.push(initializer.node); } } + } else if (t.isObjectExpression(node)) { + fact.unknown = node.properties.some( + (property) => + t.isSpreadElement(property) || + (t.isObjectProperty(property) && + semanticStaticPropertyKey(property.key, property.computed) === + "__proto__"), + ); } else if ( - !t.isObjectExpression(node) && !t.isArrayExpression(node) && !t.isLiteral(node) && !t.isFunction(node) ) - unknown = true; + fact.unknown = true; + origins.set(current, fact); + pending.push({ node: current, finish: true }); + for (const dependency of fact.dependencies) + pending.push({ node: dependency, finish: false }); } - const result = global ? true : unknown ? null : false; - // The union belongs to this receiver, not each of its possible origins. - globalReceivers.set(input, result); - return result; + return globalReceivers.get(input) ?? null; }; const active = new Set(); + const opaqueGlobalSites = new Set(state?.opaqueEffects.globalSites ?? []); let unknownPropertyRead: number | null = Infinity; for (let index = 0; index < body.length; index++) { const statement = body[index]; @@ -934,11 +964,22 @@ const moduleFunctionFirstRead = ( traverseJavaScriptAst(statement, { enter(node, parent) { if (t.isFunction(node)) active.add(node); + if ( + classicScript && + opaqueGlobalSites.has(node as t.CallExpression) + ) { + if (unknownPropertyRead !== null) + unknownPropertyRead = + active.size > 0 ? null : Math.min(unknownPropertyRead, index); + } let name: string | null = null; if ( t.isIdentifier(node) && parent !== null && - t.isReferenced(node, parent) + (t.isReferenced(node, parent) || + (t.isAssignmentExpression(parent) && + parent.left === node && + semanticWriteSiteReadsFirst(parent))) ) { const candidate = functions.get(node.name); const binding = @@ -966,6 +1007,22 @@ const moduleFunctionFirstRead = ( )) ) name = node.name; + } else if ( + classicScript && + t.isObjectProperty(node) && + t.isObjectPattern(parent) + ) { + const declaration = parents.get(parent); + if ( + t.isVariableDeclarator(declaration) && + declaration.init != null && + globalReceiver(declaration.init) !== false + ) { + name = semanticStaticPropertyKey(node.key, node.computed); + if (name === null && unknownPropertyRead !== null) + unknownPropertyRead = + active.size > 0 ? null : Math.min(unknownPropertyRead, index); + } } else if ( classicScript && (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) From c347f9ad462f812a128a514dc35954b370c3d10d Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 09:59:10 +0800 Subject: [PATCH 11/21] fix(javascript): refresh activation bounds as opaque effects grow --- .../electronStaticAnalysisOptions.test.ts | 1 + .../javascriptSemanticMutationInitializers.ts | 18 ++++++++++++++---- .../electronModuleInitializationCli.test.ts | 11 ++++++++--- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 102c74d5356..58ea5ea50d4 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -358,6 +358,7 @@ describe("Classic-script global function activation", () => { "const root = { __proto__: globalThis }; root.createWindow();", "const root = { ...globalThis }; root.createWindow();", "(0, eval)('createWindow()');", + "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');", ])("keeps early global access unresolved: %s", (activation) => { const body = (early: boolean) => ` const { BrowserWindow } = require("electron"); diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 4effec94197..ba4b39ca960 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -59,7 +59,10 @@ interface InitializerPositionCache { readonly enclosingFunction: WeakMap; readonly moduleFunctionReads: WeakMap< readonly t.Statement[], - WeakMap + { + readonly opaqueGlobalSiteCount: number; + readonly reads: WeakMap; + } >; readonly evaluationChildren: WeakMap< t.Node, @@ -844,10 +847,17 @@ const moduleFunctionFirstRead = ( state?: JavaScriptSemanticAnalysisState, ): number | null => { const cache = initializerPositionCache(parents).moduleFunctionReads; - let reads = cache.get(body); - if (reads === undefined) { + const opaqueGlobalSiteCount = state?.opaqueEffects.globalSites.length ?? 0; + const cached = cache.get(body); + let reads = cached?.reads; + // Callee resolution can query timing while the ambient walk is still + // appending opaque global effects. Reuse only facts from the same prefix. + if ( + reads === undefined || + cached?.opaqueGlobalSiteCount !== opaqueGlobalSiteCount + ) { reads = new WeakMap(); - cache.set(body, reads); + cache.set(body, { opaqueGlobalSiteCount, reads }); const functions = new Map(); for (const statement of body) { const exported = diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index e7f28c44e55..2ab0c5315b4 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -92,15 +92,20 @@ cliTest.for([ ["stdio MCP", false], ["CLI", true], ["stdio MCP", true], + ["CLI", "cached-eval"], + ["stdio MCP", "cached-eval"], ] as const)( "preserves classic global initialization uncertainty through %s", async ([surface, alias], { cli }) => { const root = await createTestTempDirectory( "rea-electron-global-initialization-", ); - const activation = alias - ? "root.createWindow();" - : "globalThis.createWindow();"; + const activation = + alias === "cached-eval" + ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" + : alias + ? "root.createWindow();" + : "globalThis.createWindow();"; const source = (early: boolean) => ` const { BrowserWindow } = require("electron"); ${alias ? "const root = globalThis;" : ""} From e2e3576f238df648d9fd714b1425d0769a9be153 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 10:08:21 +0800 Subject: [PATCH 12/21] fix(ci): format website watch directories without changing configuration --- website/wrangler.toml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/website/wrangler.toml b/website/wrangler.toml index 7c64886b300..649d31cfe12 100644 --- a/website/wrangler.toml +++ b/website/wrangler.toml @@ -15,7 +15,12 @@ not_found_handling = "none" [build] cwd = ".." command = "python3 scripts/website.py check" -watch_dir = ["./public", "./locales", "./templates", "../.agents/skills/reverse-engineer-anything"] +watch_dir = [ + "./public", + "./locales", + "./templates", + "../.agents/skills/reverse-engineer-anything", +] # Public HTTPS depends on zone activation and certificate readiness. [env.production] From e4cf01fa4a9ccfa766c5ad9427be4fd0c40f60c3 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 10:19:34 +0800 Subject: [PATCH 13/21] fix(javascript): share source reads across opaque-effect updates --- .../electronStaticAnalysisOptions.test.ts | 1 + .../javascriptSemanticMutationInitializers.ts | 50 ++++++++++++------- 2 files changed, 33 insertions(+), 18 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 58ea5ea50d4..a71de01e0e8 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -359,6 +359,7 @@ describe("Classic-script global function activation", () => { "const root = { ...globalThis }; root.createWindow();", "(0, eval)('createWindow()');", "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');", + "const noop = () => {}; (0, eval)(''); function unused() { noop(); } (0, eval)('createWindow()');", ])("keeps early global access unresolved: %s", (activation) => { const body = (early: boolean) => ` const { BrowserWindow } = require("electron"); diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 4690f0eb35b..6425d80504c 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -61,8 +61,10 @@ interface InitializerPositionCache { readonly moduleFunctionReads: WeakMap< readonly t.Statement[], { - readonly opaqueGlobalSiteCount: number; readonly reads: WeakMap; + readonly opaquePositions: WeakMap; + opaqueSitesIndexed: number; + firstOpaqueRead: number | null; } >; readonly evaluationChildren: WeakMap< @@ -869,17 +871,16 @@ const moduleFunctionFirstRead = ( state?: JavaScriptSemanticAnalysisState, ): number | null => { const cache = initializerPositionCache(parents).moduleFunctionReads; - const opaqueGlobalSiteCount = state?.opaqueEffects.globalSites.length ?? 0; - const cached = cache.get(body); - let reads = cached?.reads; - // Callee resolution can query timing while the ambient walk is still - // appending opaque global effects. Reuse only facts from the same prefix. - if ( - reads === undefined || - cached?.opaqueGlobalSiteCount !== opaqueGlobalSiteCount - ) { - reads = new WeakMap(); - cache.set(body, { opaqueGlobalSiteCount, reads }); + let retained = cache.get(body); + if (retained === undefined) { + const reads = new WeakMap(); + retained = { + reads, + opaquePositions: new WeakMap(), + opaqueSitesIndexed: 0, + firstOpaqueRead: Infinity, + }; + cache.set(body, retained); const functions = new Map(); for (const statement of body) { const exported = @@ -988,7 +989,7 @@ const moduleFunctionFirstRead = ( return globalReceivers.get(input) ?? null; }; const active = new Set(); - const opaqueGlobalSites = new Set(state?.opaqueEffects.globalSites ?? []); + const opaquePositions = retained.opaquePositions; let unknownPropertyRead: number | null = Infinity; for (let index = 0; index < body.length; index++) { const statement = body[index]; @@ -998,11 +999,9 @@ const moduleFunctionFirstRead = ( if (t.isFunction(node)) active.add(node); if ( classicScript && - opaqueGlobalSites.has(node as t.CallExpression) + (t.isCallExpression(node) || t.isOptionalCallExpression(node)) ) { - if (unknownPropertyRead !== null) - unknownPropertyRead = - active.size > 0 ? null : Math.min(unknownPropertyRead, index); + opaquePositions.set(node, active.size > 0 ? null : index); } let name: string | null = null; if ( @@ -1105,7 +1104,22 @@ const moduleFunctionFirstRead = ( ); } } - const first = reads.get(declaration); + // Callee resolution can query timing during the ambient walk. Source reads + // stay fixed; consume each newly observed opaque call once without rescanning. + const sites = state?.opaqueEffects.globalSites ?? []; + while (retained.opaqueSitesIndexed < sites.length) { + const site = sites[retained.opaqueSitesIndexed++]; + const position = + site === undefined ? undefined : retained.opaquePositions.get(site); + if (position === undefined || retained.firstOpaqueRead === null) continue; + retained.firstOpaqueRead = + position === null ? null : Math.min(retained.firstOpaqueRead, position); + } + const read = retained.reads.get(declaration); + const first = + read === undefined || read === null || retained.firstOpaqueRead === null + ? null + : Math.min(read, retained.firstOpaqueRead); return first !== undefined && Number.isFinite(first) ? first : null; }; From 13f5340e8bfe199766d6af982ff4342520a11626 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 10:51:38 +0800 Subject: [PATCH 14/21] fix(javascript): retain constructed-code global activation bounds --- .../electronStaticAnalysisOptions.test.ts | 25 ++++++++++++++++ .../javascript/javascriptSemanticAnalysis.ts | 11 +++---- .../javascriptSemanticMutationInitializers.ts | 4 ++- .../javascriptSemanticOpaqueEffects.ts | 29 ++++++++++++++----- .../javascript/javascriptSemanticState.ts | 8 +++-- .../electronModuleInitializationCli.test.ts | 14 +++++---- 6 files changed, 71 insertions(+), 20 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index a71de01e0e8..5758bf92165 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -339,6 +339,24 @@ it.each([ ); describe("Classic-script global function activation", () => { + it("keeps a shadowed Function constructor independent of global activation", () => { + const source = `const { BrowserWindow } = require('electron'); + const Function = () => () => {}; Function('createWindow()')(); + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + createWindow();`; + expect(() => + runInNewContext(source, { require: () => ({ BrowserWindow: class {} }) }), + ).not.toThrow(); + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + }); it.each([ "globalThis.createWindow();", 'globalThis["createWindow"]();', @@ -358,6 +376,13 @@ describe("Classic-script global function activation", () => { "const root = { __proto__: globalThis }; root.createWindow();", "const root = { ...globalThis }; root.createWindow();", "(0, eval)('createWindow()');", + "Function('createWindow()')();", + "new Function('createWindow()')();", + "const F = Function; F('createWindow()')();", + "Function.call(null, 'createWindow()')();", + "Function.apply(null, ['createWindow()'])();", + "globalThis.Function('createWindow()')();", + "const F = Function.bind(null); F('createWindow()')();", "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');", "const noop = () => {}; (0, eval)(''); function unused() { noop(); } (0, eval)('createWindow()');", ])("keeps early global access unresolved: %s", (activation) => { diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index ac0dd13d7ca..d2fb401fb66 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -1043,7 +1043,7 @@ const createState = ( arrayIterationUnknown: false, program, opaqueEffects: { - mayReferenceGlobalEval: false, + mayReferenceGlobalCode: false, sites: new WeakSet(), sloppySites: new WeakSet(), byScope: new Map(), @@ -1081,8 +1081,9 @@ const createState = ( }; }; -const globalEvalRoots = new Set([ +const globalCodeRoots = new Set([ "eval", + "Function", "globalThis", "global", "window", @@ -1213,10 +1214,10 @@ function* collectDefinitionsSteps( bindInnerDeclaration(node, parent, scope, state); if (t.isThrowStatement(node)) thrownValues.push({ node, ancestors: readAncestors() }); - // Every supported global eval origin starts with one of these decoded + // Every supported global-code origin starts with one of these decoded // identifiers, including computed properties and destructured aliases. - if (t.isIdentifier(node) && globalEvalRoots.has(node.name)) - state.opaqueEffects.mayReferenceGlobalEval = true; + if (t.isIdentifier(node) && globalCodeRoots.has(node.name)) + state.opaqueEffects.mayReferenceGlobalCode = true; if ( t.isCallExpression(node) && t.isIdentifier(unwrapJavaScriptExpression(node.callee).node, { diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 6425d80504c..f67c462799e 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -999,7 +999,9 @@ const moduleFunctionFirstRead = ( if (t.isFunction(node)) active.add(node); if ( classicScript && - (t.isCallExpression(node) || t.isOptionalCallExpression(node)) + (t.isCallExpression(node) || + t.isOptionalCallExpression(node) || + t.isNewExpression(node)) ) { opaquePositions.set(node, active.size > 0 ? null : index); } diff --git a/src/domain/javascript/javascriptSemanticOpaqueEffects.ts b/src/domain/javascript/javascriptSemanticOpaqueEffects.ts index c213557f4ef..ea9ad8fd66e 100644 --- a/src/domain/javascript/javascriptSemanticOpaqueEffects.ts +++ b/src/domain/javascript/javascriptSemanticOpaqueEffects.ts @@ -60,37 +60,52 @@ export const createSemanticOpaqueGlobalObserver = ( intrinsicPath: (node: t.Node) => readonly string[] | undefined; }, ) => { + intrinsicPath: (node: t.Node) => readonly string[] | undefined; intrinsicInvocation: ( node: t.CallExpression | t.OptionalCallExpression, ) => { readonly path: readonly string[] } | undefined; }; }, ): ((node: t.Node) => void) | undefined => { - if (!state.opaqueEffects.mayReferenceGlobalEval) return undefined; + if (!state.opaqueEffects.mayReferenceGlobalCode) return undefined; const ambientPaths = dependencies.createAmbientPathResolver(state, true); let invocationSite: t.Node | undefined; const interop = dependencies.createSemanticModuleInterop(state, { intrinsicPath: (node) => { const paths = ambientPaths(node, invocationSite).paths; - const path = paths.find((path) => path[1] === "eval") ?? paths[0]; + const path = + paths.find((path) => path[1] === "eval" || path[1] === "Function") ?? + paths[0]; if (path?.[0] !== "global" || path.some((key) => key === null)) return undefined; // Keep the global callable owner for generic call/apply/bind resolution. - return path[1] === "eval" + return path[1] === "eval" || path[1] === "Function" ? ["intrinsic", ...(path as readonly string[])] : ["intrinsic", ...(path.slice(1) as readonly string[])]; }, }); return (node) => { - if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node)) return; + if ( + !t.isCallExpression(node) && + !t.isOptionalCallExpression(node) && + !t.isNewExpression(node) + ) + return; invocationSite = node; - const invocation = interop.intrinsicInvocation(node); - if (invocation?.path.join(".") === "intrinsic.global.eval") + const path = t.isNewExpression(node) + ? interop.intrinsicPath(node.callee) + : interop.intrinsicInvocation(node)?.path; + // Constructed code may escape and activate a classic-script global. Keep + // its creation as a conservative timing bound, not proof of execution. + if ( + path?.join(".") === "intrinsic.global.eval" || + path?.join(".") === "intrinsic.global.Function" + ) state.opaqueEffects.globalSites.push(node); }; }; -/** Indirect eval can change globals, but cannot rebind its caller's locals. */ +/** Global code can affect globals, but cannot rebind its caller's locals. */ export const semanticOpaqueGlobalMayHaveChanged = ( read: t.Node, state: JavaScriptSemanticAnalysisState, diff --git a/src/domain/javascript/javascriptSemanticState.ts b/src/domain/javascript/javascriptSemanticState.ts index 946ac319779..61b8a6710cf 100644 --- a/src/domain/javascript/javascriptSemanticState.ts +++ b/src/domain/javascript/javascriptSemanticState.ts @@ -119,12 +119,16 @@ export interface JavaScriptSemanticScopeState { /** One source owns sites and the minimal scope tree reaching them; O(AST) storage. */ export interface JavaScriptOpaqueScopeEffects { /** Cheap source evidence collected with declarations, before alias queries. */ - mayReferenceGlobalEval: boolean; + mayReferenceGlobalCode: boolean; readonly sites: WeakSet; readonly sloppySites: WeakSet; readonly byScope: Map; readonly children: Map>; - readonly globalSites: (t.CallExpression | t.OptionalCallExpression)[]; + readonly globalSites: ( + | t.CallExpression + | t.OptionalCallExpression + | t.NewExpression + )[]; } /** Shared state for semantic collection and evaluation. */ diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index 2ab0c5315b4..8cf7ea8af8f 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -94,6 +94,8 @@ cliTest.for([ ["stdio MCP", true], ["CLI", "cached-eval"], ["stdio MCP", "cached-eval"], + ["CLI", "constructed-function"], + ["stdio MCP", "constructed-function"], ] as const)( "preserves classic global initialization uncertainty through %s", async ([surface, alias], { cli }) => { @@ -101,11 +103,13 @@ cliTest.for([ "rea-electron-global-initialization-", ); const activation = - alias === "cached-eval" - ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" - : alias - ? "root.createWindow();" - : "globalThis.createWindow();"; + alias === "constructed-function" + ? "new Function('createWindow()')();" + : alias === "cached-eval" + ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" + : alias + ? "root.createWindow();" + : "globalThis.createWindow();"; const source = (early: boolean) => ` const { BrowserWindow } = require("electron"); ${alias ? "const root = globalThis;" : ""} From 1016f6c9d433727e1cc3b2ef8dba1461458958bb Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 11:33:12 +0800 Subject: [PATCH 15/21] fix(javascript): share runtime activation and receiver facts --- .../electronStaticAnalysisOptions.test.ts | 15 ++++++ .../javascriptSemanticCallResolution.test.ts | 29 ++++++++++++ .../javascriptSemanticMutationInitializers.ts | 39 ++++++++++++---- .../electronModuleInitializationCli.test.ts | 46 ++++++++++++------- 4 files changed, 103 insertions(+), 26 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 5758bf92165..a5a34bc9485 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -339,6 +339,21 @@ it.each([ ); describe("Classic-script global function activation", () => { + it("retains possible classic activation after an erased type import", () => { + const source = `import type { T } from './types'; + const { BrowserWindow } = require('electron'); globalThis.createWindow(); + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + createWindow();`; + expect(() => + runInNewContext(source.replace("import type { T } from './types';", ""), { + require: () => ({ BrowserWindow: class {} }), + }), + ).toThrow(/before initialization/); + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ web_preferences_status: "dynamic", web_preferences: [] }); + }); it("keeps a shadowed Function constructor independent of global activation", () => { const source = `const { BrowserWindow } = require('electron'); const Function = () => () => {}; Function('createWindow()')(); diff --git a/src/domain/javascript/javascriptSemanticCallResolution.test.ts b/src/domain/javascript/javascriptSemanticCallResolution.test.ts index f2dbe20cf78..23b3c6a5826 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.test.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.test.ts @@ -186,6 +186,35 @@ it("bounds shared partial callback alias expansion by AST size", () => { expect(large.referenceReads).toBeLessThan(3 * small.referenceReads); }); +it.each([true, false])( + "orders a module direct-eval activation with early=%s", + (early) => { + const { state } = indexed( + `export {}; ${early ? "eval('open()');" : ""} const make = () => 1; function open() { return make(); } ${early ? "" : "eval('open()');"} open();`, + ); + const binding = [...state.bindingsById.values()].find( + (binding) => binding.name === "make", + ); + if (binding === undefined) throw new Error("Missing make binding"); + let reads = 0; + traverseJavaScriptAst(state.program, { + enter(node) { + if ( + t.isCallExpression(node) && + t.isIdentifier(node.callee, { name: "make" }) + ) { + reads++; + expect( + semanticBindingAtRead(binding, node.callee, state) + .hasDefiniteInitializer, + ).toBe(!early); + } + }, + }); + expect(reads).toBe(1); + }, +); + it.each([ ["if(flag){cb=fallback;cb();}", true], ["if(flag)cb=fallback;cb();", false], diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index f67c462799e..733254c9012 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -1,5 +1,6 @@ import * as t from "@babel/types"; import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; +import { javaScriptRuntimeContext } from "./javascriptSourceParser.js"; import { delayedInstanceFieldValue, @@ -903,8 +904,12 @@ const moduleFunctionFirstRead = ( const program = firstStatement === undefined ? undefined : parents.get(firstStatement); const classicScript = - t.isProgram(program) && program.sourceType === "script"; + t.isProgram(program) && javaScriptRuntimeContext(program) === "unknown"; const globalReceivers = new WeakMap(); + const bindingReceivers = new WeakMap< + JavaScriptSemanticBindingState, + t.Node + >(); const globalReceiver = (input: t.Node): boolean | null => { const pending: { node: t.Node; finish: boolean }[] = [ { node: input, finish: false }, @@ -957,14 +962,20 @@ const moduleFunctionFirstRead = ( fact.global = true; else fact.unknown = true; } else { - if ( - binding.initializers.length === 0 || - binding.referenceInitializers.length > 0 - ) - fact.unknown = true; - for (const initializer of binding.initializers) { - if (initializer.projection.length > 0) fact.unknown = true; - else fact.dependencies.push(initializer.node); + const representative = bindingReceivers.get(binding); + if (representative !== undefined && representative !== current) { + fact.dependencies.push(representative); + } else { + bindingReceivers.set(binding, current); + if ( + binding.initializers.length === 0 || + binding.referenceInitializers.length > 0 + ) + fact.unknown = true; + for (const initializer of binding.initializers) { + if (initializer.projection.length > 0) fact.unknown = true; + else fact.dependencies.push(initializer.node); + } } } } else if (t.isObjectExpression(node)) { @@ -997,6 +1008,16 @@ const moduleFunctionFirstRead = ( traverseJavaScriptAst(statement, { enter(node, parent) { if (t.isFunction(node)) active.add(node); + // Direct eval sees lexical module/CommonJS bindings too. Its + // scope-owned sites are complete before ambient indexing starts. + if ( + t.isCallExpression(node) && + state?.opaqueEffects.sites.has(node) + ) { + if (unknownPropertyRead !== null) + unknownPropertyRead = + active.size > 0 ? null : Math.min(unknownPropertyRead, index); + } if ( classicScript && (t.isCallExpression(node) || diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index 8cf7ea8af8f..7ff042b49b3 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -96,6 +96,10 @@ cliTest.for([ ["stdio MCP", "cached-eval"], ["CLI", "constructed-function"], ["stdio MCP", "constructed-function"], + ["CLI", "erased-type"], + ["stdio MCP", "erased-type"], + ["CLI", "module-eval"], + ["stdio MCP", "module-eval"], ] as const)( "preserves classic global initialization uncertainty through %s", async ([surface, alias], { cli }) => { @@ -103,28 +107,36 @@ cliTest.for([ "rea-electron-global-initialization-", ); const activation = - alias === "constructed-function" - ? "new Function('createWindow()')();" - : alias === "cached-eval" - ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" - : alias - ? "root.createWindow();" - : "globalThis.createWindow();"; + alias === "module-eval" + ? "eval('createWindow()');" + : alias === "erased-type" + ? "globalThis.createWindow();" + : alias === "constructed-function" + ? "new Function('createWindow()')();" + : alias === "cached-eval" + ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" + : alias + ? "root.createWindow();" + : "globalThis.createWindow();"; const source = (early: boolean) => ` - const { BrowserWindow } = require("electron"); + ${alias === "erased-type" ? "import type { T } from './types';" : alias === "module-eval" ? "export {};" : ""} + ${alias === "module-eval" ? 'import { BrowserWindow } from "electron";' : 'const { BrowserWindow } = require("electron");'} ${alias ? "const root = globalThis;" : ""} ${early ? activation : ""} const webPreferences = { nodeIntegration: true }; function createWindow() { return new BrowserWindow({ webPreferences }); } - ${early ? "" : activation} + ${early || alias === "module-eval" ? "" : activation} createWindow(); throw new Error("must not execute source"); `; + const extension = + alias === "erased-type" ? "ts" : alias === "module-eval" ? "mjs" : "js"; + const earlyName = `early.${extension}`; + const lateName = `late.${extension}`; await writeFixtureFiles(root, { - "early.js": source(true), - "late.js": source(false), - "index.html": - '', + [earlyName]: source(true), + [lateName]: source(false), + "index.html": ``, }); const result = await analyzeJavaScriptDirectory(surface, cli, root); expect(result.statistics.parse_failures).toBe(0); @@ -141,13 +153,13 @@ cliTest.for([ evidence.location.value.kind === "source-range" && evidence.location.value.source === name, ); - expect(inSource("early.js")).toHaveLength(1); - expect(inSource("early.js")[0]?.properties).toMatchObject({ + expect(inSource(earlyName)).toHaveLength(1); + expect(inSource(earlyName)[0]?.properties).toMatchObject({ web_preferences_status: "dynamic", web_preferences: [], }); - expect(inSource("late.js")).toHaveLength(1); - expect(inSource("late.js")[0]?.properties).toMatchObject({ + expect(inSource(lateName)).toHaveLength(1); + expect(inSource(lateName)[0]?.properties).toMatchObject({ web_preferences_status: "object-literal", web_preferences: [ { name: "nodeIntegration", value: { status: "literal", value: true } }, From 5b8594a6c806d0fd7dc9386f38f3ea7ba47d7f5c Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 12:03:18 +0800 Subject: [PATCH 16/21] fix(javascript): reuse pattern reads and function positions --- .../electronStaticAnalysisOptions.test.ts | 4 + .../javascriptSemanticCallResolution.test.ts | 38 +++++++ .../javascriptSemanticMutationInitializers.ts | 101 ++++++++++-------- .../electronModuleInitializationCli.test.ts | 30 ++++-- 4 files changed, 118 insertions(+), 55 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index a5a34bc9485..b1da2c89c81 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -387,6 +387,10 @@ describe("Classic-script global function activation", () => { "const key = 'createWindow'; globalThis[key]();", "with ({}) { createWindow(); }", "const { createWindow: start } = globalThis; start();", + "let start; ({ createWindow: start } = globalThis); start();", + "let start; for ({ createWindow: start } of [globalThis]) start();", + "for (const { createWindow: start } of [globalThis]) start();", + "let start; ({ root: { createWindow: start } } = { root: globalThis }); start();", "const start = (createWindow ||= null); start();", "const root = { __proto__: globalThis }; root.createWindow();", "const root = { ...globalThis }; root.createWindow();", diff --git a/src/domain/javascript/javascriptSemanticCallResolution.test.ts b/src/domain/javascript/javascriptSemanticCallResolution.test.ts index 23b3c6a5826..3fccf6c7027 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.test.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.test.ts @@ -186,6 +186,44 @@ it("bounds shared partial callback alias expansion by AST size", () => { expect(large.referenceReads).toBeLessThan(3 * small.referenceReads); }); +it("reuses the immutable enclosing-function position across distinct captured reads", () => { + const { state } = indexed( + `const make=()=>1; ${"0;".repeat(64)} function use(){${"make();".repeat(64)}} use();`, + ); + const binding = [...state.bindingsById.values()].find( + (b) => b.name === "make", + ); + const fn = state.program.body.find( + (n) => t.isFunctionDeclaration(n) && n.id?.name === "use", + ); + if (binding === undefined || fn === undefined) + throw Error("Missing fixture binding"); + const lookup = vi.spyOn(state.program.body, "indexOf"); + let reads = 0; + try { + traverseJavaScriptAst(fn, { + enter(node) { + if ( + t.isCallExpression(node) && + t.isIdentifier(node.callee, { name: "make" }) + ) { + reads++; + expect( + semanticBindingAtRead(binding, node.callee, state) + .hasDefiniteInitializer, + ).toBe(true); + } + }, + }); + expect(reads).toBe(64); + expect( + lookup.mock.calls.filter(([node]) => node === fn).length, + ).toBeLessThanOrEqual(1); + } finally { + lookup.mockRestore(); + } +}); + it.each([true, false])( "orders a module direct-eval activation with early=%s", (early) => { diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 733254c9012..ab5513da6d0 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -1,6 +1,7 @@ import * as t from "@babel/types"; import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; import { javaScriptRuntimeContext } from "./javascriptSourceParser.js"; +import { semanticPropertyReadSources } from "./javascriptSemanticIterationSources.js"; import { delayedInstanceFieldValue, @@ -59,6 +60,7 @@ interface InitializerPositionCache { readonly reference: WeakMap; readonly read: WeakMap; readonly enclosingFunction: WeakMap; + readonly functionPosition: WeakMap; readonly moduleFunctionReads: WeakMap< readonly t.Statement[], { @@ -94,6 +96,7 @@ const initializerPositionCache = ( reference: new WeakMap(), read: new WeakMap(), enclosingFunction: new WeakMap(), + functionPosition: new WeakMap(), moduleFunctionReads: new WeakMap(), evaluationChildren: new WeakMap(), expressionAncestry: undefined, @@ -1000,6 +1003,23 @@ const moduleFunctionFirstRead = ( return globalReceivers.get(input) ?? null; }; const active = new Set(); + const retainNamedRead = ( + name: string, + parent: t.Node | null, + index: number, + ): void => { + const fn = functions.get(name); + if (fn == null || active.has(fn)) return; + const current = indexedReads.get(fn); + if (current === null || current === undefined) return; + // Indirect activations and live exports have no proven module timing. + indexedReads.set( + fn, + active.size > 0 || t.isExportSpecifier(parent) + ? null + : Math.min(current, index), + ); + }; const opaquePositions = retained.opaquePositions; let unknownPropertyRead: number | null = Infinity; for (let index = 0; index < body.length; index++) { @@ -1026,6 +1046,20 @@ const moduleFunctionFirstRead = ( ) { opaquePositions.set(node, active.size > 0 ? null : index); } + if (classicScript) { + for (const source of semanticPropertyReadSources(node, parent)) { + const projected = + source.iterationSources !== undefined || + source.projection.length > 1; + if (!projected && globalReceiver(source.node) === false) continue; + const key = source.projection[0]; + if (!projected && typeof key === "string") + retainNamedRead(key, parent, index); + else if (unknownPropertyRead !== null) + unknownPropertyRead = + active.size > 0 ? null : Math.min(unknownPropertyRead, index); + } + } let name: string | null = null; if ( t.isIdentifier(node) && @@ -1061,22 +1095,6 @@ const moduleFunctionFirstRead = ( )) ) name = node.name; - } else if ( - classicScript && - t.isObjectProperty(node) && - t.isObjectPattern(parent) - ) { - const declaration = parents.get(parent); - if ( - t.isVariableDeclarator(declaration) && - declaration.init != null && - globalReceiver(declaration.init) !== false - ) { - name = semanticStaticPropertyKey(node.key, node.computed); - if (name === null && unknownPropertyRead !== null) - unknownPropertyRead = - active.size > 0 ? null : Math.min(unknownPropertyRead, index); - } } else if ( classicScript && (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) @@ -1096,18 +1114,7 @@ const moduleFunctionFirstRead = ( } } } - if (name === null) return; - const fn = functions.get(name); - if (fn == null || active.has(fn)) return; - const current = indexedReads.get(fn); - if (current === null || current === undefined) return; - // Indirect activations and live exports have no proven module timing. - indexedReads.set( - fn, - active.size > 0 || t.isExportSpecifier(parent) - ? null - : Math.min(current, index), - ); + if (name !== null) retainNamedRead(name, parent, index); }, exit(node) { if (t.isFunction(node)) active.delete(node); @@ -1258,23 +1265,29 @@ export const semanticBindingAtRead = ( const enclosingFunction = moduleConstBinding ? bindingEnclosingFunction(read, parents) : undefined; - const functionStatementPosition = (): StatementPosition | null => { - if (enclosingFunction === undefined) return null; - if (t.isStatement(enclosingFunction)) - return statementPosition(enclosingFunction, parents); - for ( - let owner = parents.get(enclosingFunction); - owner !== undefined; - owner = parents.get(owner) - ) { - if (t.isFunction(owner)) return null; - if (t.isStatement(owner)) return statementPosition(owner, parents); + let functionPosition: StatementPosition | null = null; + if (enclosingFunction !== undefined) { + const positions = initializerPositionCache(parents).functionPosition; + const cached = positions.get(enclosingFunction); + if (cached !== undefined) functionPosition = cached; + else { + const compute = (): StatementPosition | null => { + if (t.isStatement(enclosingFunction)) + return statementPosition(enclosingFunction, parents); + for ( + let owner = parents.get(enclosingFunction); + owner !== undefined; + owner = parents.get(owner) + ) { + if (t.isFunction(owner)) return null; + if (t.isStatement(owner)) return statementPosition(owner, parents); + } + return null; + }; + functionPosition = compute(); + positions.set(enclosingFunction, functionPosition); } - return null; - }; - const functionPosition = moduleConstBinding - ? functionStatementPosition() - : null; + } const firstFunctionRead = moduleConstBinding && sourcePosition !== null && diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index 7ff042b49b3..b753f4397be 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -100,6 +100,10 @@ cliTest.for([ ["stdio MCP", "erased-type"], ["CLI", "module-eval"], ["stdio MCP", "module-eval"], + ["CLI", "assignment-pattern"], + ["stdio MCP", "assignment-pattern"], + ["CLI", "iteration-pattern"], + ["stdio MCP", "iteration-pattern"], ] as const)( "preserves classic global initialization uncertainty through %s", async ([surface, alias], { cli }) => { @@ -107,17 +111,21 @@ cliTest.for([ "rea-electron-global-initialization-", ); const activation = - alias === "module-eval" - ? "eval('createWindow()');" - : alias === "erased-type" - ? "globalThis.createWindow();" - : alias === "constructed-function" - ? "new Function('createWindow()')();" - : alias === "cached-eval" - ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" - : alias - ? "root.createWindow();" - : "globalThis.createWindow();"; + alias === "assignment-pattern" + ? "let start; ({createWindow:start}=globalThis); start();" + : alias === "iteration-pattern" + ? "for(const {createWindow:start} of [globalThis]) start();" + : alias === "module-eval" + ? "eval('createWindow()');" + : alias === "erased-type" + ? "globalThis.createWindow();" + : alias === "constructed-function" + ? "new Function('createWindow()')();" + : alias === "cached-eval" + ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" + : alias + ? "root.createWindow();" + : "globalThis.createWindow();"; const source = (early: boolean) => ` ${alias === "erased-type" ? "import type { T } from './types';" : alias === "module-eval" ? "export {};" : ""} ${alias === "module-eval" ? 'import { BrowserWindow } from "electron";' : 'const { BrowserWindow } = require("electron");'} From f45be16b7317585797ef736a31fde40d1c61849c Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 14:46:10 +0800 Subject: [PATCH 17/21] fix(javascript): isolate copied paths and preserve runtime reads --- .../electronStaticAnalysisOptions.test.ts | 31 +++++++++- src/domain/javascript/javascriptRouteScan.ts | 6 +- .../javascriptSemanticAmbientWrites.ts | 2 +- .../javascriptSemanticCopiedReferencePaths.ts | 57 +++++++++++++++++++ .../javascriptSemanticIterationSources.ts | 3 +- .../javascriptSemanticMemberMutations.ts | 3 +- .../javascriptSemanticMutationInitializers.ts | 35 +++++++++++- .../javascriptSemanticProjectedSources.ts | 3 +- .../javascriptSemanticReferenceSources.ts | 53 ----------------- 9 files changed, 130 insertions(+), 63 deletions(-) create mode 100644 src/domain/javascript/javascriptSemanticCopiedReferencePaths.ts diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index b1da2c89c81..48add2aa8ca 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -1,7 +1,11 @@ import { runInNewContext } from "node:vm"; import { describe, expect, it } from "vitest"; -import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js"; +import { parseJavaScriptSource } from "./javascriptSourceParser.js"; +import { + analyzeParsedJavaScriptStaticSource, + analyzeJavaScriptStaticSource, +} from "./javascriptStaticAnalysis.js"; describe("Electron constant option evidence", () => { it("keeps mixed constant, inline and unresolved windows in construction order", () => { @@ -339,6 +343,31 @@ it.each([ ); describe("Classic-script global function activation", () => { + it.each([ + "const { nested: { value } } = { nested: { value: 1 } };", + "let value; ({ nested: { value } } = { nested: { value: 1 } });", + "export type { createWindow };", + "export { type createWindow };", + ])("preserves settings across runtime-independent syntax: %s", (prefix) => { + const source = `${prefix === "export { type createWindow };" ? "import { BrowserWindow } from 'electron';" : "const { BrowserWindow } = require('electron');"} + ${prefix} + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({ webPreferences }); } + createWindow();`; + const parsed = parseJavaScriptSource(source, "fixture.ts"); + expect(parsed).not.toBeNull(); + if (parsed === null) throw new Error("fixture did not parse"); + expect( + analyzeParsedJavaScriptStaticSource(source, parsed).electron + .browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { name: "nodeIntegration", value: { status: "literal", value: true } }, + ], + }); + }); + it("retains possible classic activation after an erased type import", () => { const source = `import type { T } from './types'; const { BrowserWindow } = require('electron'); globalThis.createWindow(); diff --git a/src/domain/javascript/javascriptRouteScan.ts b/src/domain/javascript/javascriptRouteScan.ts index 06c55f45579..137b772fe92 100644 --- a/src/domain/javascript/javascriptRouteScan.ts +++ b/src/domain/javascript/javascriptRouteScan.ts @@ -23,10 +23,8 @@ import { type JavaScriptBindingIndex, type JavaScriptSemanticBindingState, } from "./javascriptSemanticState.js"; -import { - semanticCopiedReferencePath, - semanticReferenceSourcesInactive, -} from "./javascriptSemanticReferenceSources.js"; +import { semanticReferenceSourcesInactive } from "./javascriptSemanticReferenceSources.js"; +import { semanticCopiedReferencePath } from "./javascriptSemanticCopiedReferencePaths.js"; import { semanticAliasSelectionChoices, type SemanticAliasSelectionPath, diff --git a/src/domain/javascript/javascriptSemanticAmbientWrites.ts b/src/domain/javascript/javascriptSemanticAmbientWrites.ts index 99b63daed29..2eb49e67b68 100644 --- a/src/domain/javascript/javascriptSemanticAmbientWrites.ts +++ b/src/domain/javascript/javascriptSemanticAmbientWrites.ts @@ -38,10 +38,10 @@ import { } from "./javascriptSemanticGlobalReference.js"; import { readSemanticRequireLoader } from "./javascriptSemanticRequireOriginSlot.js"; import { - semanticCopiedReferencePath, semanticReferenceIterationUnknown, semanticReferenceSourcesInactive, } from "./javascriptSemanticReferenceSources.js"; +import { semanticCopiedReferencePath } from "./javascriptSemanticCopiedReferencePaths.js"; export { isUnmodifiedGlobalReference, diff --git a/src/domain/javascript/javascriptSemanticCopiedReferencePaths.ts b/src/domain/javascript/javascriptSemanticCopiedReferencePaths.ts new file mode 100644 index 00000000000..72102111395 --- /dev/null +++ b/src/domain/javascript/javascriptSemanticCopiedReferencePaths.ts @@ -0,0 +1,57 @@ +import { + semanticArrayIndex, + type JavaScriptSemanticPropertyPath as PropertyPath, +} from "./javascriptSemanticPropertyPaths.js"; +import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; + +interface CopiedReferenceSource { + readonly projection: PropertyPath; + readonly copyKind?: "object-rest" | "array-rest"; + readonly copyProjectionOffset?: number; + readonly copyExcludedKeys?: readonly string[]; + readonly copyStartIndex?: number; +} + +/** Map copied child selections once; the fresh copy itself keeps its own identity. */ +export const semanticCopiedReferencePath = ( + initializer: CopiedReferenceSource, + path: PropertyPath, + effect: "write" | "escape" | "identity", +): PropertyPath | null => { + const offset = initializer.copyProjectionOffset; + if (offset === undefined) return [...initializer.projection, ...path]; + const copiedPath = [...initializer.projection.slice(offset + 1), ...path]; + if (effect === "identity" && copiedPath.length === 0) return null; + if (effect === "write" && copiedPath.length < 2) return null; + let [key, ...remaining] = copiedPath; + if (initializer.copyKind === "array-rest") { + const startIndex = initializer.copyStartIndex ?? 0; + if (key === undefined || key === null) + key = { excludedKeys: [], startIndex }; + else if (typeof key === "object") + key = { + excludedKeys: key.excludedKeys.flatMap((name) => { + const index = semanticArrayIndex(name); + return index === null ? [] : [String(index + startIndex)]; + }), + startIndex: (key.startIndex ?? 0) + startIndex, + }; + else { + const index = semanticArrayIndex(key); + if (index === null) return null; + key = index + startIndex; + } + } else { + const excludedKeys = initializer.copyExcludedKeys ?? []; + if (key === undefined || key === null) key = { excludedKeys }; + else if (typeof key === "object") + key = { + ...key, + excludedKeys: [...new Set([...key.excludedKeys, ...excludedKeys])].sort( + compareUnicodeCodePoints, + ), + }; + else if (excludedKeys.includes(String(key))) return null; + } + return [...initializer.projection.slice(0, offset), key, ...remaining]; +}; diff --git a/src/domain/javascript/javascriptSemanticIterationSources.ts b/src/domain/javascript/javascriptSemanticIterationSources.ts index 70e8581ffaf..dc182c5bfaa 100644 --- a/src/domain/javascript/javascriptSemanticIterationSources.ts +++ b/src/domain/javascript/javascriptSemanticIterationSources.ts @@ -11,7 +11,8 @@ import { type JavaScriptSemanticPropertyPath, } from "./javascriptSemanticPropertyPaths.js"; import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; -import { semanticCopiedReferencePath } from "./javascriptSemanticReferenceSources.js"; + +import { semanticCopiedReferencePath } from "./javascriptSemanticCopiedReferencePaths.js"; import type { IterationSourceValue, SemanticIterationSource, diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index ba978494cf7..8cc38e59026 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -69,11 +69,12 @@ import { import { semanticCoercionOperands } from "./javascriptSemanticLanguageInvocations.js"; import { SEMANTIC_ALIAS_SELECTION_LIMIT } from "./javascriptSemanticResourceLimits.js"; import { - semanticCopiedReferencePath, + semanticKnownArrayIteration, semanticReferenceSourcesInactive, semanticSelectedReferenceSlot, } from "./javascriptSemanticReferenceSources.js"; +import { semanticCopiedReferencePath } from "./javascriptSemanticCopiedReferencePaths.js"; import { semanticArrayIndex, joinSemanticPropertyPaths, diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index ab5513da6d0..0947278e934 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -1,5 +1,9 @@ import * as t from "@babel/types"; -import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js"; +import { + isErasedJavaScriptValueChild, + traverseJavaScriptAst, +} from "./javascriptSemanticTraversal.js"; +import { isTypeOnlyExportDeclaration } from "./javascriptModuleDeclaration.js"; import { javaScriptRuntimeContext } from "./javascriptSourceParser.js"; import { semanticPropertyReadSources } from "./javascriptSemanticIterationSources.js"; @@ -11,6 +15,7 @@ import { } from "./javascriptSemanticEvaluationOrder.js"; import { + staticObjectProperty, semanticStaticPropertyKey, semanticWriteSiteReadsFirst, unwrapJavaScriptExpression, @@ -890,6 +895,11 @@ const moduleFunctionFirstRead = ( const exported = t.isExportNamedDeclaration(statement) || t.isExportDefaultDeclaration(statement); + if ( + t.isExportNamedDeclaration(statement) && + isTypeOnlyExportDeclaration(statement) + ) + continue; const node = exported ? statement.declaration : statement; if (!t.isFunctionDeclaration(node)) continue; reads.set(node, exported ? null : Infinity); @@ -1026,6 +1036,9 @@ const moduleFunctionFirstRead = ( const statement = body[index]; if (statement === undefined) continue; traverseJavaScriptAst(statement, { + skip: (node) => + state?.erasedSyntaxNodes.has(node) === true || + isErasedJavaScriptValueChild(node, parents.get(node) ?? null), enter(node, parent) { if (t.isFunction(node)) active.add(node); // Direct eval sees lexical module/CommonJS bindings too. Its @@ -1052,6 +1065,26 @@ const moduleFunctionFirstRead = ( source.iterationSources !== undefined || source.projection.length > 1; if (!projected && globalReceiver(source.node) === false) continue; + // Select the receiver through the shared property-reference owner. + // Unknown/iterated sources retain possible activation. + if (projected && source.iterationSources === undefined) { + let receiver: t.Node | undefined = source.node; + for (const key of source.projection.slice(0, -1)) { + if (typeof key !== "string" && typeof key !== "number") { + receiver = undefined; + break; + } + const selected = staticObjectProperty(receiver, String(key)); + receiver = + selected.status === "explicit" ? selected.value : undefined; + if (receiver === undefined) break; + } + if ( + receiver !== undefined && + globalReceiver(receiver) === false + ) + continue; + } const key = source.projection[0]; if (!projected && typeof key === "string") retainNamedRead(key, parent, index); diff --git a/src/domain/javascript/javascriptSemanticProjectedSources.ts b/src/domain/javascript/javascriptSemanticProjectedSources.ts index a1daf7e88b2..5973f96593a 100644 --- a/src/domain/javascript/javascriptSemanticProjectedSources.ts +++ b/src/domain/javascript/javascriptSemanticProjectedSources.ts @@ -18,10 +18,11 @@ import { semanticTopLevelEffectFollowsCapture, } from "./javascriptSemanticMutationInitializers.js"; import { - semanticCopiedReferencePath, + semanticReferenceIterationUnknown, semanticReferenceSourcesInactive, } from "./javascriptSemanticReferenceSources.js"; +import { semanticCopiedReferencePath } from "./javascriptSemanticCopiedReferencePaths.js"; import { semanticStoredSourceSelection } from "./javascriptSemanticIterationSources.js"; import { semanticEffectPathCandidates, diff --git a/src/domain/javascript/javascriptSemanticReferenceSources.ts b/src/domain/javascript/javascriptSemanticReferenceSources.ts index 58b1307c006..3a97d3a1570 100644 --- a/src/domain/javascript/javascriptSemanticReferenceSources.ts +++ b/src/domain/javascript/javascriptSemanticReferenceSources.ts @@ -5,7 +5,6 @@ import { semanticPropertyPathKeyMatches, type JavaScriptSemanticPropertyPath as PropertyPath, } from "./javascriptSemanticPropertyPaths.js"; -import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { evaluateSemanticExpression, semanticValueDefinitelyDefined, @@ -147,55 +146,3 @@ export const semanticSelectedReferenceSlot = ( path, ); }; - -interface CopiedReferenceSource { - readonly projection: PropertyPath; - readonly copyKind?: "object-rest" | "array-rest"; - readonly copyProjectionOffset?: number; - readonly copyExcludedKeys?: readonly string[]; - readonly copyStartIndex?: number; -} - -/** Map copied child selections once; the fresh copy itself keeps its own identity. */ -export const semanticCopiedReferencePath = ( - initializer: CopiedReferenceSource, - path: PropertyPath, - effect: "write" | "escape" | "identity", -): PropertyPath | null => { - const offset = initializer.copyProjectionOffset; - if (offset === undefined) return [...initializer.projection, ...path]; - const copiedPath = [...initializer.projection.slice(offset + 1), ...path]; - if (effect === "identity" && copiedPath.length === 0) return null; - if (effect === "write" && copiedPath.length < 2) return null; - let [key, ...remaining] = copiedPath; - if (initializer.copyKind === "array-rest") { - const startIndex = initializer.copyStartIndex ?? 0; - if (key === undefined || key === null) - key = { excludedKeys: [], startIndex }; - else if (typeof key === "object") - key = { - excludedKeys: key.excludedKeys.flatMap((name) => { - const index = semanticArrayIndex(name); - return index === null ? [] : [String(index + startIndex)]; - }), - startIndex: (key.startIndex ?? 0) + startIndex, - }; - else { - const index = semanticArrayIndex(key); - if (index === null) return null; - key = index + startIndex; - } - } else { - const excludedKeys = initializer.copyExcludedKeys ?? []; - if (key === undefined || key === null) key = { excludedKeys }; - else if (typeof key === "object") - key = { - ...key, - excludedKeys: [...new Set([...key.excludedKeys, ...excludedKeys])].sort( - compareUnicodeCodePoints, - ), - }; - else if (excludedKeys.includes(String(key))) return null; - } - return [...initializer.projection.slice(0, offset), key, ...remaining]; -}; From d9e845f7e5e17ebbb97feac71a6d9ab40cbe8215 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 14:51:05 +0800 Subject: [PATCH 18/21] style(javascript): format migrated reference imports --- src/domain/javascript/javascriptSemanticMemberMutations.ts | 1 - src/domain/javascript/javascriptSemanticProjectedSources.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index 8cc38e59026..096ebf1e6d7 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -69,7 +69,6 @@ import { import { semanticCoercionOperands } from "./javascriptSemanticLanguageInvocations.js"; import { SEMANTIC_ALIAS_SELECTION_LIMIT } from "./javascriptSemanticResourceLimits.js"; import { - semanticKnownArrayIteration, semanticReferenceSourcesInactive, semanticSelectedReferenceSlot, diff --git a/src/domain/javascript/javascriptSemanticProjectedSources.ts b/src/domain/javascript/javascriptSemanticProjectedSources.ts index 5973f96593a..963d0d89033 100644 --- a/src/domain/javascript/javascriptSemanticProjectedSources.ts +++ b/src/domain/javascript/javascriptSemanticProjectedSources.ts @@ -18,7 +18,6 @@ import { semanticTopLevelEffectFollowsCapture, } from "./javascriptSemanticMutationInitializers.js"; import { - semanticReferenceIterationUnknown, semanticReferenceSourcesInactive, } from "./javascriptSemanticReferenceSources.js"; From e13c376f13bce0d61306f8b4912b513f0c3734bc Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 16:03:09 +0800 Subject: [PATCH 19/21] fix(javascript): normalize constructor activation and receiver effects --- .../electronStaticAnalysisOptions.test.ts | 4 ++ .../javascriptIntrinsicInvocation.ts | 11 ++++- .../javascript/javascriptModuleInterop.ts | 2 +- .../javascript/javascriptSemanticAnalysis.ts | 2 + .../javascriptSemanticMutationInitializers.ts | 31 +++++++++++-- .../javascriptSemanticOpaqueEffects.ts | 6 +-- .../javascript/javascriptSemanticState.ts | 2 + .../electronModuleInitializationCli.test.ts | 46 +++++++++++++------ 8 files changed, 80 insertions(+), 24 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 48add2aa8ca..cdbf8a796cd 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -426,6 +426,10 @@ describe("Classic-script global function activation", () => { "(0, eval)('createWindow()');", "Function('createWindow()')();", "new Function('createWindow()')();", + "const F = Function.bind(null); new F('createWindow()')();", + "Reflect.construct(Function, ['createWindow()'])();", + "const root = {}; Object.setPrototypeOf(root, globalThis); root.createWindow();", + "const root = {}; Object.assign(root, globalThis); root.createWindow();", "const F = Function; F('createWindow()')();", "Function.call(null, 'createWindow()')();", "Function.apply(null, ['createWindow()'])();", diff --git a/src/domain/javascript/javascriptIntrinsicInvocation.ts b/src/domain/javascript/javascriptIntrinsicInvocation.ts index 082fe5006da..5573ac4ae8d 100644 --- a/src/domain/javascript/javascriptIntrinsicInvocation.ts +++ b/src/domain/javascript/javascriptIntrinsicInvocation.ts @@ -147,7 +147,7 @@ export const resolveJavaScriptGenericInvocation = ( * Binding a function alone is not a write; only its eventual call is examined. */ export const resolveJavaScriptIntrinsicInvocation = ( - node: t.CallExpression | t.OptionalCallExpression, + node: t.CallExpression | t.OptionalCallExpression | t.NewExpression, intrinsicPath: (node: t.Node) => readonly string[] | undefined, boundIntrinsic: (node: t.Node) => JavaScriptIntrinsicInvocation | undefined, intrinsicReadChanged: (node: t.Node, path: readonly string[]) => boolean, @@ -240,6 +240,15 @@ export const resolveJavaScriptIntrinsicInvocation = ( arguments_ = selected.context.arguments; continue; } + if (path.join(".") === "intrinsic.Reflect.construct") { + const callable = arguments_?.[0]; + if (!t.isExpression(callable)) return undefined; + callee = callable; + receiver = undefined; + explicitReceiver = true; + arguments_ = arrayArguments(arguments_?.[1], nativeArrayIteration); + continue; + } if (path.join(".") === "intrinsic.Reflect.apply") { const callable = arguments_?.[0]; if (!t.isExpression(callable)) return undefined; diff --git a/src/domain/javascript/javascriptModuleInterop.ts b/src/domain/javascript/javascriptModuleInterop.ts index 29957ae9e94..9a334884d51 100644 --- a/src/domain/javascript/javascriptModuleInterop.ts +++ b/src/domain/javascript/javascriptModuleInterop.ts @@ -626,7 +626,7 @@ export const createSemanticModuleInterop = ( callOrigin, intrinsicPath, intrinsicInvocation: ( - node: t.CallExpression | t.OptionalCallExpression, + node: t.CallExpression | t.OptionalCallExpression | t.NewExpression, callablePath = intrinsicPath, ) => resolveJavaScriptIntrinsicInvocation( diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index d2fb401fb66..6b9e83ad571 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -228,6 +228,7 @@ function* indexSemanticMemberMutationFactsSteps( (site, reference, path) => referenceEffectsMayHaveChanged(state, site, reference, path), ); + state.memberMutationFactsComplete = true; indexedMemberMutationStates.add(state); invalidateSemanticRequireDelegateWrites(state); } @@ -1041,6 +1042,7 @@ const createState = ( }; return { arrayIterationUnknown: false, + memberMutationFactsComplete: false, program, opaqueEffects: { mayReferenceGlobalCode: false, diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 0947278e934..369b0ed3376 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -70,6 +70,7 @@ interface InitializerPositionCache { readonly t.Statement[], { readonly reads: WeakMap; + readonly memberEffectsComplete: boolean; readonly opaquePositions: WeakMap; opaqueSitesIndexed: number; firstOpaqueRead: number | null; @@ -881,10 +882,14 @@ const moduleFunctionFirstRead = ( ): number | null => { const cache = initializerPositionCache(parents).moduleFunctionReads; let retained = cache.get(body); + const memberEffectsComplete = state?.memberMutationFactsComplete === true; + if (retained?.memberEffectsComplete !== memberEffectsComplete) + retained = undefined; if (retained === undefined) { const reads = new WeakMap(); retained = { reads, + memberEffectsComplete, opaquePositions: new WeakMap(), opaqueSitesIndexed: 0, firstOpaqueRead: Infinity, @@ -1012,6 +1017,25 @@ const moduleFunctionFirstRead = ( } return globalReceivers.get(input) ?? null; }; + const receiverAtRead = (input: t.Node, read: t.Node): boolean | null => { + const identity = globalReceiver(input); + if (identity !== false || state === undefined) return identity; + if (!memberEffectsComplete) return identity; + const root = unwrapJavaScriptExpression(input).node; + if (!t.isIdentifier(root)) return identity; + const binding = resolveSemanticBindingState(state, root, root.name); + if (binding === undefined) return null; + for (const effect of [...binding.memberWrites, ...binding.escapedPaths]) { + if ( + effect.node !== undefined && + semanticReadPrecedesEffectWithinActivation(read, effect.node, parents) + ) + continue; + if (semanticEffectTiming(read, effect.node, state) !== "after") + return null; + } + return identity; + }; const active = new Set(); const retainNamedRead = ( name: string, @@ -1064,7 +1088,8 @@ const moduleFunctionFirstRead = ( const projected = source.iterationSources !== undefined || source.projection.length > 1; - if (!projected && globalReceiver(source.node) === false) continue; + if (!projected && receiverAtRead(source.node, node) === false) + continue; // Select the receiver through the shared property-reference owner. // Unknown/iterated sources retain possible activation. if (projected && source.iterationSources === undefined) { @@ -1081,7 +1106,7 @@ const moduleFunctionFirstRead = ( } if ( receiver !== undefined && - globalReceiver(receiver) === false + receiverAtRead(receiver, node) === false ) continue; } @@ -1135,7 +1160,7 @@ const moduleFunctionFirstRead = ( const receiver = unwrapJavaScriptExpression(node.object).node; // Classic scripts expose hoisted functions through the global object. // Property names are not referenced identifiers; keep their read timing too. - if (globalReceiver(receiver) !== false) { + if (receiverAtRead(receiver, node) !== false) { name = semanticStaticPropertyKey(node.property, node.computed); if (name === null) { if (unknownPropertyRead !== null) diff --git a/src/domain/javascript/javascriptSemanticOpaqueEffects.ts b/src/domain/javascript/javascriptSemanticOpaqueEffects.ts index ea9ad8fd66e..8332330faa7 100644 --- a/src/domain/javascript/javascriptSemanticOpaqueEffects.ts +++ b/src/domain/javascript/javascriptSemanticOpaqueEffects.ts @@ -62,7 +62,7 @@ export const createSemanticOpaqueGlobalObserver = ( ) => { intrinsicPath: (node: t.Node) => readonly string[] | undefined; intrinsicInvocation: ( - node: t.CallExpression | t.OptionalCallExpression, + node: t.CallExpression | t.OptionalCallExpression | t.NewExpression, ) => { readonly path: readonly string[] } | undefined; }; }, @@ -92,9 +92,7 @@ export const createSemanticOpaqueGlobalObserver = ( ) return; invocationSite = node; - const path = t.isNewExpression(node) - ? interop.intrinsicPath(node.callee) - : interop.intrinsicInvocation(node)?.path; + const path = interop.intrinsicInvocation(node)?.path; // Constructed code may escape and activate a classic-script global. Keep // its creation as a conservative timing bound, not proof of execution. if ( diff --git a/src/domain/javascript/javascriptSemanticState.ts b/src/domain/javascript/javascriptSemanticState.ts index 61b8a6710cf..367743bb285 100644 --- a/src/domain/javascript/javascriptSemanticState.ts +++ b/src/domain/javascript/javascriptSemanticState.ts @@ -134,6 +134,8 @@ export interface JavaScriptOpaqueScopeEffects { /** Shared state for semantic collection and evaluation. */ export interface JavaScriptSemanticAnalysisState { arrayIterationUnknown: boolean; + /** Receiver isolation requires the completed member-effect inventory. */ + memberMutationFactsComplete: boolean; readonly program: t.Program; readonly opaqueEffects: JavaScriptOpaqueScopeEffects; /** Effective loader for static imports in this source artifact. */ diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index b753f4397be..3bd86ed5d74 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -100,6 +100,14 @@ cliTest.for([ ["stdio MCP", "erased-type"], ["CLI", "module-eval"], ["stdio MCP", "module-eval"], + ["CLI", "bound-constructor"], + ["stdio MCP", "bound-constructor"], + ["CLI", "reflect-constructor"], + ["stdio MCP", "reflect-constructor"], + ["CLI", "prototype-effect"], + ["stdio MCP", "prototype-effect"], + ["CLI", "assign-effect"], + ["stdio MCP", "assign-effect"], ["CLI", "assignment-pattern"], ["stdio MCP", "assignment-pattern"], ["CLI", "iteration-pattern"], @@ -111,21 +119,29 @@ cliTest.for([ "rea-electron-global-initialization-", ); const activation = - alias === "assignment-pattern" - ? "let start; ({createWindow:start}=globalThis); start();" - : alias === "iteration-pattern" - ? "for(const {createWindow:start} of [globalThis]) start();" - : alias === "module-eval" - ? "eval('createWindow()');" - : alias === "erased-type" - ? "globalThis.createWindow();" - : alias === "constructed-function" - ? "new Function('createWindow()')();" - : alias === "cached-eval" - ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" - : alias - ? "root.createWindow();" - : "globalThis.createWindow();"; + alias === "bound-constructor" + ? "const F = Function.bind(null); new F('createWindow()')();" + : alias === "reflect-constructor" + ? "Reflect.construct(Function, ['createWindow()'])();" + : alias === "prototype-effect" + ? "const changed = {}; Object.setPrototypeOf(changed, globalThis); changed.createWindow();" + : alias === "assign-effect" + ? "const changed = {}; Object.assign(changed, globalThis); changed.createWindow();" + : alias === "assignment-pattern" + ? "let start; ({createWindow:start}=globalThis); start();" + : alias === "iteration-pattern" + ? "for(const {createWindow:start} of [globalThis]) start();" + : alias === "module-eval" + ? "eval('createWindow()');" + : alias === "erased-type" + ? "globalThis.createWindow();" + : alias === "constructed-function" + ? "new Function('createWindow()')();" + : alias === "cached-eval" + ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" + : alias + ? "root.createWindow();" + : "globalThis.createWindow();"; const source = (early: boolean) => ` ${alias === "erased-type" ? "import type { T } from './types';" : alias === "module-eval" ? "export {};" : ""} ${alias === "module-eval" ? 'import { BrowserWindow } from "electron";' : 'const { BrowserWindow } = require("electron");'} From 5d9db0e818f5b4e5814ed9f9ff7b6bdf6de9a907 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 16:46:13 +0800 Subject: [PATCH 20/21] fix(javascript): retain aliased receiver timing and lexical global this --- .../electronStaticAnalysisOptions.test.ts | 147 ++++++++++-------- .../javascriptSemanticAmbientWrites.ts | 13 ++ .../javascript/javascriptSemanticAnalysis.ts | 5 +- .../javascriptSemanticCallResolution.test.ts | 53 +++++++ .../javascriptSemanticMutationInitializers.ts | 134 ++++++++++++++-- .../javascript/javascriptSourceParser.ts | 19 +++ .../electronModuleInitializationCli.test.ts | 58 ++++--- 7 files changed, 325 insertions(+), 104 deletions(-) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index cdbf8a796cd..7c256fad0c9 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -342,6 +342,47 @@ it.each([ }, ); +const CLASSIC_GLOBAL_ACTIVATIONS = [ + "globalThis.createWindow();", + 'globalThis["createWindow"]();', + "const early = globalThis.createWindow; early();", + "globalThis?.createWindow?.();", + "window.createWindow();", + 'self["createWindow"]();', + "this.createWindow();", + "const root = globalThis; root.createWindow();", + "const root = window; const alias = root; alias.createWindow();", + "const root = globalThis.window; root.createWindow();", + "const { root } = { root: globalThis }; root.createWindow();", + "const key = 'createWindow'; globalThis[key]();", + "with ({}) { createWindow(); }", + "const { createWindow: start } = globalThis; start();", + "let start; ({ createWindow: start } = globalThis); start();", + "let start; for ({ createWindow: start } of [globalThis]) start();", + "for (const { createWindow: start } of [globalThis]) start();", + "let start; ({ root: { createWindow: start } } = { root: globalThis }); start();", + "const start = (createWindow ||= null); start();", + "const root = { __proto__: globalThis }; root.createWindow();", + "const root = { ...globalThis }; root.createWindow();", + "(0, eval)('createWindow()');", + "Function('createWindow()')();", + "new Function('createWindow()')();", + "this['Function']('createWindow()')();", + "const root = {}; const alias = root; Object.setPrototypeOf(root, globalThis); alias.createWindow();", + "const root = {}; const alias = root; Object.assign(root, globalThis); alias.createWindow();", + "const F = Function.bind(null); new F('createWindow()')();", + "Reflect.construct(Function, ['createWindow()'])();", + "const root = {}; Object.setPrototypeOf(root, globalThis); root.createWindow();", + "const root = {}; Object.assign(root, globalThis); root.createWindow();", + "const F = Function; F('createWindow()')();", + "Function.call(null, 'createWindow()')();", + "Function.apply(null, ['createWindow()'])();", + "globalThis.Function('createWindow()')();", + "const F = Function.bind(null); F('createWindow()')();", + "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');", + "const noop = () => {}; (0, eval)(''); function unused() { noop(); } (0, eval)('createWindow()');", +]; + describe("Classic-script global function activation", () => { it.each([ "const { nested: { value } } = { nested: { value: 1 } };", @@ -401,44 +442,10 @@ describe("Classic-script global function activation", () => { ], }); }); - it.each([ - "globalThis.createWindow();", - 'globalThis["createWindow"]();', - "const early = globalThis.createWindow; early();", - "globalThis?.createWindow?.();", - "window.createWindow();", - 'self["createWindow"]();', - "this.createWindow();", - "const root = globalThis; root.createWindow();", - "const root = window; const alias = root; alias.createWindow();", - "const root = globalThis.window; root.createWindow();", - "const { root } = { root: globalThis }; root.createWindow();", - "const key = 'createWindow'; globalThis[key]();", - "with ({}) { createWindow(); }", - "const { createWindow: start } = globalThis; start();", - "let start; ({ createWindow: start } = globalThis); start();", - "let start; for ({ createWindow: start } of [globalThis]) start();", - "for (const { createWindow: start } of [globalThis]) start();", - "let start; ({ root: { createWindow: start } } = { root: globalThis }); start();", - "const start = (createWindow ||= null); start();", - "const root = { __proto__: globalThis }; root.createWindow();", - "const root = { ...globalThis }; root.createWindow();", - "(0, eval)('createWindow()');", - "Function('createWindow()')();", - "new Function('createWindow()')();", - "const F = Function.bind(null); new F('createWindow()')();", - "Reflect.construct(Function, ['createWindow()'])();", - "const root = {}; Object.setPrototypeOf(root, globalThis); root.createWindow();", - "const root = {}; Object.assign(root, globalThis); root.createWindow();", - "const F = Function; F('createWindow()')();", - "Function.call(null, 'createWindow()')();", - "Function.apply(null, ['createWindow()'])();", - "globalThis.Function('createWindow()')();", - "const F = Function.bind(null); F('createWindow()')();", - "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');", - "const noop = () => {}; (0, eval)(''); function unused() { noop(); } (0, eval)('createWindow()');", - ])("keeps early global access unresolved: %s", (activation) => { - const body = (early: boolean) => ` + it.each(CLASSIC_GLOBAL_ACTIVATIONS)( + "keeps early global access unresolved: %s", + (activation) => { + const body = (early: boolean) => ` const { BrowserWindow } = require("electron"); ${early ? activation : ""} const webPreferences = { nodeIntegration: true }; @@ -446,36 +453,40 @@ describe("Classic-script global function activation", () => { ${early ? "" : activation} createWindow(); `; - const runtime = () => ({ require: () => ({ BrowserWindow: class {} }) }); - expect(() => - runInNewContext( - "globalThis.window = globalThis; globalThis.self = globalThis;" + - body(true), - runtime(), - ), - ).toThrow(/before initialization/); - expect(() => - runInNewContext( - "globalThis.window = globalThis; globalThis.self = globalThis;" + - body(false), - runtime(), - ), - ).not.toThrow(); - expect( - analyzeJavaScriptStaticSource(body(true)).electron.browser_windows[0], - ).toMatchObject({ - web_preferences_status: "dynamic", - web_preferences: [], - }); - expect( - analyzeJavaScriptStaticSource(body(false)).electron.browser_windows[0], - ).toMatchObject({ - web_preferences_status: "object-literal", - web_preferences: [ - { name: "nodeIntegration", value: { status: "literal", value: true } }, - ], - }); - }); + const runtime = () => ({ require: () => ({ BrowserWindow: class {} }) }); + expect(() => + runInNewContext( + "globalThis.window = globalThis; globalThis.self = globalThis;" + + body(true), + runtime(), + ), + ).toThrow(/before initialization/); + expect(() => + runInNewContext( + "globalThis.window = globalThis; globalThis.self = globalThis;" + + body(false), + runtime(), + ), + ).not.toThrow(); + expect( + analyzeJavaScriptStaticSource(body(true)).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); + expect( + analyzeJavaScriptStaticSource(body(false)).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { + name: "nodeIntegration", + value: { status: "literal", value: true }, + }, + ], + }); + }, + ); it("keeps callbacks in hoisted default parameters uncertain", () => { const source = ` diff --git a/src/domain/javascript/javascriptSemanticAmbientWrites.ts b/src/domain/javascript/javascriptSemanticAmbientWrites.ts index 2eb49e67b68..0099de9908e 100644 --- a/src/domain/javascript/javascriptSemanticAmbientWrites.ts +++ b/src/domain/javascript/javascriptSemanticAmbientWrites.ts @@ -1,3 +1,4 @@ +import { javaScriptTopLevelThisMayBeGlobal } from "./javascriptSourceParser.js"; import * as t from "@babel/types"; import { @@ -319,6 +320,18 @@ export const createAmbientPathResolver = ( resolvedIdentity = true; continue; } + if ( + t.isThisExpression(root) && + javaScriptTopLevelThisMayBeGlobal( + root, + state.program, + state.parentsByNode, + ) + ) { + retain(["global", ...(suffix ?? [])]); + resolvedIdentity = true; + continue; + } if (t.isIdentifier(root)) { // The wrapper module object is distinct from globalThis.module. Keep // its identity through the same alias/projection owner used for writes. diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index 6b9e83ad571..37a89f9f309 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -1218,7 +1218,10 @@ function* collectDefinitionsSteps( thrownValues.push({ node, ancestors: readAncestors() }); // Every supported global-code origin starts with one of these decoded // identifiers, including computed properties and destructured aliases. - if (t.isIdentifier(node) && globalCodeRoots.has(node.name)) + if ( + t.isThisExpression(node) || + (t.isIdentifier(node) && globalCodeRoots.has(node.name)) + ) state.opaqueEffects.mayReferenceGlobalCode = true; if ( t.isCallExpression(node) && diff --git a/src/domain/javascript/javascriptSemanticCallResolution.test.ts b/src/domain/javascript/javascriptSemanticCallResolution.test.ts index 3fccf6c7027..d3f2223f949 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.test.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.test.ts @@ -4,6 +4,7 @@ import { expect, it, vi } from "vitest"; import { analyzeJavaScriptSemantics, indexJavaScriptBindingsSteps, + indexJavaScriptBindingsWithReceiversSteps, } from "./javascriptSemanticAnalysis.js"; import { resolveLocalCallables, @@ -607,3 +608,55 @@ it("resolves calls in computed method keys before subsequent pattern writes", () calleeCallableIds: [original?.callableId], }); }); + +it.each([64, 128])( + "indexes receiver effects once for %s reads before distinct writes", + (count) => { + const source = `const object = {}; ${"object.x;".repeat(count)} ${Array.from({ length: count }, (_, i) => `object.p${i}=1;`).join("")} const make=()=>1; function use(){make();} use();`; + const file = parseJavaScriptSource(source, "fixture.js"); + if (file === null) throw Error("Invalid fixture"); + const steps = indexJavaScriptBindingsWithReceiversSteps(file.program); + let step = steps.next(); + while (!step.done) step = steps.next(); + const index = step.value; + for (const _ of index.indexMemberMutationFactsSteps()) { + void _; + } + const state = index.bindings; + const object = [...state.bindingsById.values()].find( + (b) => b.name === "object", + ); + const make = [...state.bindingsById.values()].find( + (b) => b.name === "make", + ); + if (object === undefined || make === undefined) + throw Error("Missing fixture bindings"); + let visits = 0; + Object.defineProperty(object, "memberWrites", { + value: new Proxy(object.memberWrites, { + get(target, key, receiver) { + if (typeof key === "string" && /^\d+$/.test(key)) visits++; + return Reflect.get(target, key, receiver); + }, + }), + }); + let checked = 0; + traverseJavaScriptAst(file.program, { + enter(node) { + if ( + t.isCallExpression(node) && + t.isIdentifier(node.callee, { name: "make" }) + ) { + expect( + semanticBindingAtRead(make, node.callee, state) + .hasDefiniteInitializer, + ).toBe(true); + checked++; + } + }, + }); + expect(checked).toBe(1); + expect(object.memberWrites.length).toBe(count); + expect(visits).toBeLessThanOrEqual(count * 2); + }, +); diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 369b0ed3376..516c7dbf89a 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -1017,24 +1017,134 @@ const moduleFunctionFirstRead = ( } return globalReceivers.get(input) ?? null; }; + interface ReceiverBound { + index: number; + node?: t.Node; + ambiguous: boolean; + } + const receiverBounds = new WeakMap< + JavaScriptSemanticBindingState, + ReceiverBound | null + >(); + const receiverBound = ( + root: JavaScriptSemanticBindingState, + ): ReceiverBound | null => { + const pending = [{ binding: root, finish: false }]; + const activeBindings = new Set(); + const dependencies = new WeakMap< + JavaScriptSemanticBindingState, + JavaScriptSemanticBindingState[] + >(); + const merge = ( + left: ReceiverBound, + right: ReceiverBound, + ): ReceiverBound => { + if (left.index < right.index) return left; + if (right.index < left.index) return right; + return { + ...left, + ambiguous: + left.ambiguous || right.ambiguous || left.node !== right.node, + }; + }; + while (pending.length > 0) { + const frame = pending.pop()!; + const binding = frame.binding; + if (frame.finish) { + let bound: ReceiverBound | null = { + index: Infinity, + ambiguous: false, + }; + for (const effects of [binding.memberWrites, binding.escapedPaths]) { + for (const effect of effects) { + const position = + effect.node === undefined + ? null + : directMutationPosition(effect.node, parents); + if ( + effect.node === undefined || + position === null || + position.body !== body + ) { + bound = null; + break; + } + bound = merge(bound, { + index: position.index, + node: effect.node, + ambiguous: false, + }); + } + if (bound === null) break; + } + for (const dependency of dependencies.get(binding) ?? []) { + const inherited = receiverBounds.get(dependency); + if ( + bound === null || + inherited === null || + inherited === undefined + ) { + bound = null; + break; + } + bound = merge(bound, inherited); + } + receiverBounds.set(binding, bound); + activeBindings.delete(binding); + continue; + } + if (receiverBounds.has(binding)) continue; + if (activeBindings.has(binding)) { + receiverBounds.set(binding, null); + continue; + } + activeBindings.add(binding); + const selected: JavaScriptSemanticBindingState[] = []; + for (const initializer of binding.initializers) { + const node = unwrapJavaScriptExpression(initializer.node).node; + if (!t.isIdentifier(node) || state === undefined) continue; + const dependency = resolveSemanticBindingState( + state, + node, + node.name, + ); + if (dependency !== undefined) selected.push(dependency); + } + dependencies.set(binding, selected); + pending.push({ binding, finish: true }); + for (const dependency of selected) + pending.push({ binding: dependency, finish: false }); + } + return receiverBounds.get(root) ?? null; + }; const receiverAtRead = (input: t.Node, read: t.Node): boolean | null => { const identity = globalReceiver(input); - if (identity !== false || state === undefined) return identity; - if (!memberEffectsComplete) return identity; + if (identity !== false || state === undefined || !memberEffectsComplete) + return identity; const root = unwrapJavaScriptExpression(input).node; if (!t.isIdentifier(root)) return identity; const binding = resolveSemanticBindingState(state, root, root.name); if (binding === undefined) return null; - for (const effect of [...binding.memberWrites, ...binding.escapedPaths]) { - if ( - effect.node !== undefined && - semanticReadPrecedesEffectWithinActivation(read, effect.node, parents) - ) - continue; - if (semanticEffectTiming(read, effect.node, state) !== "after") - return null; - } - return identity; + const bound = receiverBound(binding); + if (bound === null) return null; + const position = bindingReadPosition(read, parents); + if ( + position.position === null || + position.repeatingLoop || + position.position.body !== body + ) + return null; + if (position.position.index < bound.index) return identity; + if (position.position.index > bound.index || bound.ambiguous) return null; + return bound.node !== undefined && + (semanticReadPrecedesEffectWithinActivation( + read, + bound.node, + parents, + ) || + semanticEffectTiming(read, bound.node, state) === "after") + ? identity + : null; }; const active = new Set(); const retainNamedRead = ( diff --git a/src/domain/javascript/javascriptSourceParser.ts b/src/domain/javascript/javascriptSourceParser.ts index 82bff08cb8d..82aefcc7e56 100644 --- a/src/domain/javascript/javascriptSourceParser.ts +++ b/src/domain/javascript/javascriptSourceParser.ts @@ -282,3 +282,22 @@ export const parseJavaScriptSource = ( return null; } }; + +/** A script's top-level lexical this may be its ambient global; wrappers and modules isolate it. */ +export const javaScriptTopLevelThisMayBeGlobal = ( + node: t.ThisExpression, + program: t.Program, + parents: WeakMap, +): boolean => { + if (javaScriptRuntimeContext(program) !== "unknown") return false; + let current: t.Node | undefined = parents.get(node); + while (current !== undefined && current !== program) { + if ( + (t.isFunction(current) && !t.isArrowFunctionExpression(current)) || + t.isClass(current) + ) + return false; + current = parents.get(current); + } + return current === program; +}; diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index 3bd86ed5d74..0e3c32e3716 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -108,6 +108,12 @@ cliTest.for([ ["stdio MCP", "prototype-effect"], ["CLI", "assign-effect"], ["stdio MCP", "assign-effect"], + ["CLI", "this-constructor"], + ["stdio MCP", "this-constructor"], + ["CLI", "alias-prototype"], + ["stdio MCP", "alias-prototype"], + ["CLI", "alias-assign"], + ["stdio MCP", "alias-assign"], ["CLI", "assignment-pattern"], ["stdio MCP", "assignment-pattern"], ["CLI", "iteration-pattern"], @@ -119,29 +125,35 @@ cliTest.for([ "rea-electron-global-initialization-", ); const activation = - alias === "bound-constructor" - ? "const F = Function.bind(null); new F('createWindow()')();" - : alias === "reflect-constructor" - ? "Reflect.construct(Function, ['createWindow()'])();" - : alias === "prototype-effect" - ? "const changed = {}; Object.setPrototypeOf(changed, globalThis); changed.createWindow();" - : alias === "assign-effect" - ? "const changed = {}; Object.assign(changed, globalThis); changed.createWindow();" - : alias === "assignment-pattern" - ? "let start; ({createWindow:start}=globalThis); start();" - : alias === "iteration-pattern" - ? "for(const {createWindow:start} of [globalThis]) start();" - : alias === "module-eval" - ? "eval('createWindow()');" - : alias === "erased-type" - ? "globalThis.createWindow();" - : alias === "constructed-function" - ? "new Function('createWindow()')();" - : alias === "cached-eval" - ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" - : alias - ? "root.createWindow();" - : "globalThis.createWindow();"; + alias === "this-constructor" + ? "this['Function']('createWindow()')();" + : alias === "alias-prototype" + ? "const changed = {}; const indirect = changed; Object.setPrototypeOf(changed, globalThis); indirect.createWindow();" + : alias === "alias-assign" + ? "const changed = {}; const indirect = changed; Object.assign(changed, globalThis); indirect.createWindow();" + : alias === "bound-constructor" + ? "const F = Function.bind(null); new F('createWindow()')();" + : alias === "reflect-constructor" + ? "Reflect.construct(Function, ['createWindow()'])();" + : alias === "prototype-effect" + ? "const changed = {}; Object.setPrototypeOf(changed, globalThis); changed.createWindow();" + : alias === "assign-effect" + ? "const changed = {}; Object.assign(changed, globalThis); changed.createWindow();" + : alias === "assignment-pattern" + ? "let start; ({createWindow:start}=globalThis); start();" + : alias === "iteration-pattern" + ? "for(const {createWindow:start} of [globalThis]) start();" + : alias === "module-eval" + ? "eval('createWindow()');" + : alias === "erased-type" + ? "globalThis.createWindow();" + : alias === "constructed-function" + ? "new Function('createWindow()')();" + : alias === "cached-eval" + ? "const noop = () => {}; function unused() { noop(); } (0, eval)('createWindow()');" + : alias + ? "root.createWindow();" + : "globalThis.createWindow();"; const source = (early: boolean) => ` ${alias === "erased-type" ? "import type { T } from './types';" : alias === "module-eval" ? "export {};" : ""} ${alias === "module-eval" ? 'import { BrowserWindow } from "electron";' : 'const { BrowserWindow } = require("electron");'} From 9da5935aff99a2b21134ac77f8247b879e26f380 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Tue, 3 Nov 2026 17:01:34 +0800 Subject: [PATCH 21/21] fix(javascript): preserve effect-free receiver identity across activations --- .../electronStaticAnalysisOptions.test.ts | 31 +++++++++++++++++++ .../javascriptSemanticMutationInitializers.ts | 1 + .../electronModuleInitializationCli.test.ts | 3 ++ 3 files changed, 35 insertions(+) diff --git a/src/domain/javascript/electronStaticAnalysisOptions.test.ts b/src/domain/javascript/electronStaticAnalysisOptions.test.ts index 7c256fad0c9..fab052406a7 100644 --- a/src/domain/javascript/electronStaticAnalysisOptions.test.ts +++ b/src/domain/javascript/electronStaticAnalysisOptions.test.ts @@ -566,6 +566,37 @@ describe("Classic-script global receiver identity", () => { }); }); + it.each([ + "function unused() { other.createWindow; }", + "for (const value of [1,2]) { other.createWindow; }", + "const alias = other; function unused() { alias.createWindow; }", + ])( + "preserves no-effect receiver identity across deferred reads: %s", + (read) => { + const source = `const { BrowserWindow } = require("electron"); + const other = { createWindow() {} }; ${read} + const webPreferences = { nodeIntegration: true }; + function createWindow() { return new BrowserWindow({webPreferences}); } + createWindow();`; + expect(() => + runInNewContext(source, { + require: () => ({ BrowserWindow: class {} }), + }), + ).not.toThrow(); + expect( + analyzeJavaScriptStaticSource(source).electron.browser_windows[0], + ).toMatchObject({ + web_preferences_status: "object-literal", + web_preferences: [ + { + name: "nodeIntegration", + value: { status: "literal", value: true }, + }, + ], + }); + }, + ); + it("keeps unrelated same-named member calls independent", () => { const source = ` const { BrowserWindow } = require("electron"); diff --git a/src/domain/javascript/javascriptSemanticMutationInitializers.ts b/src/domain/javascript/javascriptSemanticMutationInitializers.ts index 516c7dbf89a..65f0021d960 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -1127,6 +1127,7 @@ const moduleFunctionFirstRead = ( if (binding === undefined) return null; const bound = receiverBound(binding); if (bound === null) return null; + if (bound.index === Infinity) return identity; const position = bindingReadPosition(read, parents); if ( position.position === null || diff --git a/tests/acceptance/applications/electronModuleInitializationCli.test.ts b/tests/acceptance/applications/electronModuleInitializationCli.test.ts index 0e3c32e3716..eba4460ca60 100644 --- a/tests/acceptance/applications/electronModuleInitializationCli.test.ts +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -158,6 +158,9 @@ cliTest.for([ ${alias === "erased-type" ? "import type { T } from './types';" : alias === "module-eval" ? "export {};" : ""} ${alias === "module-eval" ? 'import { BrowserWindow } from "electron";' : 'const { BrowserWindow } = require("electron");'} ${alias ? "const root = globalThis;" : ""} + const unrelated = { createWindow() {} }; + function unusedReceiverRead() { unrelated.createWindow; } + for (const ignored of [1, 2]) { unrelated.createWindow; } ${early ? activation : ""} const webPreferences = { nodeIntegration: true }; function createWindow() { return new BrowserWindow({ webPreferences }); }