diff --git a/docs/javascript-artifact-reconstruction.md b/docs/javascript-artifact-reconstruction.md index 1dd3c99d585..3381815cc50 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 e164a237c2b..fab052406a7 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", () => { @@ -200,6 +204,425 @@ 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: [], + }); +}); +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 } }, + ], + }); +}); + +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 = () => { + 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], + ).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: [], + }); + }, +); + +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 } };", + "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(); + 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()')(); + 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(CLASSIC_GLOBAL_ACTIVATIONS)( + "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("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: [] }); + }); +}); + +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) + + "; root" + + index + + ".document;", + ); + 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"); + 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"; + 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.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"); + const other = { createWindow() {} }; + let root = other; + root = globalThis; + root.document; + 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/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/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/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..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, @@ -452,7 +450,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 +1018,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..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 { @@ -38,10 +39,10 @@ import { } from "./javascriptSemanticGlobalReference.js"; import { readSemanticRequireLoader } from "./javascriptSemanticRequireOriginSlot.js"; import { - semanticCopiedReferencePath, semanticReferenceIterationUnknown, semanticReferenceSourcesInactive, } from "./javascriptSemanticReferenceSources.js"; +import { semanticCopiedReferencePath } from "./javascriptSemanticCopiedReferencePaths.js"; export { isUnmodifiedGlobalReference, @@ -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. @@ -345,7 +358,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/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index ac0dd13d7ca..37a89f9f309 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,9 +1042,10 @@ const createState = ( }; return { arrayIterationUnknown: false, + memberMutationFactsComplete: false, program, opaqueEffects: { - mayReferenceGlobalEval: false, + mayReferenceGlobalCode: false, sites: new WeakSet(), sloppySites: new WeakSet(), byScope: new Map(), @@ -1081,8 +1083,9 @@ const createState = ( }; }; -const globalEvalRoots = new Set([ +const globalCodeRoots = new Set([ "eval", + "Function", "globalThis", "global", "window", @@ -1213,10 +1216,13 @@ 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.isThisExpression(node) || + (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/javascriptSemanticAsyncEffects.ts b/src/domain/javascript/javascriptSemanticAsyncEffects.ts index ea9e990bd18..88f209570ff 100644 --- a/src/domain/javascript/javascriptSemanticAsyncEffects.ts +++ b/src/domain/javascript/javascriptSemanticAsyncEffects.ts @@ -234,7 +234,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, @@ -313,7 +313,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 e96889419a7..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, @@ -186,6 +187,73 @@ 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) => { + 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], @@ -207,7 +275,7 @@ it.each([ ) { reads++; expect( - semanticBindingAtRead(binding, node.callee, state.parentsByNode) + semanticBindingAtRead(binding, node.callee, state) .hasDefiniteInitializer, ).toBe(expected); } @@ -412,7 +480,7 @@ it.each(["||=", "??="])( ) { reads++; expect( - semanticBindingAtRead(binding, node.callee, state.parentsByNode) + semanticBindingAtRead(binding, node.callee, state) .hasDefiniteInitializer, ).toBe(true); } @@ -540,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/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/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/javascriptSemanticDataEffects.ts b/src/domain/javascript/javascriptSemanticDataEffects.ts index f2bfa6ee881..3efcb4f46d2 100644 --- a/src/domain/javascript/javascriptSemanticDataEffects.ts +++ b/src/domain/javascript/javascriptSemanticDataEffects.ts @@ -272,11 +272,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/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/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 21737b1976c..096ebf1e6d7 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -69,11 +69,11 @@ 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, @@ -162,11 +162,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 6a062f36818..65f0021d960 100644 --- a/src/domain/javascript/javascriptSemanticMutationInitializers.ts +++ b/src/domain/javascript/javascriptSemanticMutationInitializers.ts @@ -1,4 +1,11 @@ import * as t from "@babel/types"; +import { + isErasedJavaScriptValueChild, + traverseJavaScriptAst, +} from "./javascriptSemanticTraversal.js"; +import { isTypeOnlyExportDeclaration } from "./javascriptModuleDeclaration.js"; +import { javaScriptRuntimeContext } from "./javascriptSourceParser.js"; +import { semanticPropertyReadSources } from "./javascriptSemanticIterationSources.js"; import { delayedInstanceFieldValue, @@ -8,7 +15,9 @@ import { } from "./javascriptSemanticEvaluationOrder.js"; import { + staticObjectProperty, semanticStaticPropertyKey, + semanticWriteSiteReadsFirst, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; import { @@ -55,6 +64,18 @@ interface InitializerPositionCache { readonly mutation: WeakMap; readonly reference: WeakMap; readonly read: WeakMap; + readonly enclosingFunction: WeakMap; + readonly functionPosition: WeakMap; + readonly moduleFunctionReads: WeakMap< + readonly t.Statement[], + { + readonly reads: WeakMap; + readonly memberEffectsComplete: boolean; + readonly opaquePositions: WeakMap; + opaqueSitesIndexed: number; + firstOpaqueRead: number | null; + } + >; readonly evaluationChildren: WeakMap< t.Node, ReadonlyMap | null @@ -80,6 +101,9 @@ const initializerPositionCache = ( mutation: new WeakMap(), reference: new WeakMap(), read: new WeakMap(), + enclosingFunction: new WeakMap(), + functionPosition: new WeakMap(), + moduleFunctionReads: new WeakMap(), evaluationChildren: new WeakMap(), expressionAncestry: undefined, }; @@ -731,6 +755,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, @@ -820,11 +873,465 @@ 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, + state?: JavaScriptSemanticAnalysisState, +): 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, + }; + cache.set(body, retained); + const functions = new Map(); + for (const statement of body) { + 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); + 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 firstStatement = body[0]; + const program = + firstStatement === undefined ? undefined : parents.get(firstStatement); + const classicScript = + 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 }, + ]; + const visiting = new Set(); + const origins = new WeakMap< + t.Node, + { dependencies: t.Node[]; unknown: boolean; global: boolean } + >(); + while (pending.length > 0) { + 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; + } + 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 (node !== current) fact.dependencies.push(node); + else if (t.isThisExpression(node)) fact.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)) + fact.global = true; + else fact.unknown = true; + } else { + 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)) { + fact.unknown = node.properties.some( + (property) => + t.isSpreadElement(property) || + (t.isObjectProperty(property) && + semanticStaticPropertyKey(property.key, property.computed) === + "__proto__"), + ); + } else if ( + !t.isArrayExpression(node) && + !t.isLiteral(node) && + !t.isFunction(node) + ) + 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 }); + } + 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 || !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; + const bound = receiverBound(binding); + if (bound === null) return null; + if (bound.index === Infinity) return identity; + 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 = ( + 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++) { + 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 + // 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) || + t.isOptionalCallExpression(node) || + t.isNewExpression(node)) + ) { + 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 && 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) { + 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 && + receiverAtRead(receiver, 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) && + parent !== null && + (t.isReferenced(node, parent) || + (t.isAssignmentExpression(parent) && + parent.left === node && + semanticWriteSiteReadsFirst(parent))) + ) { + const candidate = functions.get(node.name); + const binding = + 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 && + 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 (receiverAtRead(receiver, node) !== false) { + name = semanticStaticPropertyKey(node.property, node.computed); + if (name === null) { + if (unknownPropertyRead !== null) + unknownPropertyRead = + active.size > 0 + ? null + : Math.min(unknownPropertyRead, index); + return; + } + } + } + if (name !== null) retainNamedRead(name, parent, index); + }, + exit(node) { + if (t.isFunction(node)) active.delete(node); + }, + }); + } + // 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), + ); + } + } + // 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; +}; + 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 @@ -919,11 +1426,66 @@ 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; + 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); + } + } + const firstFunctionRead = + moduleConstBinding && + sourcePosition !== null && + functionPosition !== null && + sourcePosition.body === functionPosition.body && + t.isFunctionDeclaration(enclosingFunction) + ? moduleFunctionFirstRead( + enclosingFunction, + sourcePosition.body, + parents, + state, + ) + : null; + const moduleConstInitializedBeforeActivation = + moduleConstBinding && + sourcePosition !== null && + functionPosition !== null && + sourcePosition.body === functionPosition.body && + (t.isFunctionDeclaration(enclosingFunction) + ? firstFunctionRead !== null && sourcePosition.index < firstFunctionRead + : positionPrecedes(sourcePosition, functionPosition)); const uncertainOrder = repeatingLoop || sourcePosition === null || position === null || sourcePosition.body !== position.body; + if (uncertainOrder && moduleConstInitializedBeforeActivation) + // 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); @@ -1271,7 +1833,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/javascriptSemanticOpaqueEffects.ts b/src/domain/javascript/javascriptSemanticOpaqueEffects.ts index c213557f4ef..8332330faa7 100644 --- a/src/domain/javascript/javascriptSemanticOpaqueEffects.ts +++ b/src/domain/javascript/javascriptSemanticOpaqueEffects.ts @@ -60,37 +60,50 @@ export const createSemanticOpaqueGlobalObserver = ( intrinsicPath: (node: t.Node) => readonly string[] | undefined; }, ) => { + 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; }; }, ): ((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 = 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/javascriptSemanticProjectedSources.ts b/src/domain/javascript/javascriptSemanticProjectedSources.ts index 152271cfb46..963d0d89033 100644 --- a/src/domain/javascript/javascriptSemanticProjectedSources.ts +++ b/src/domain/javascript/javascriptSemanticProjectedSources.ts @@ -18,10 +18,10 @@ import { semanticTopLevelEffectFollowsCapture, } from "./javascriptSemanticMutationInitializers.js"; import { - semanticCopiedReferencePath, semanticReferenceIterationUnknown, semanticReferenceSourcesInactive, } from "./javascriptSemanticReferenceSources.js"; +import { semanticCopiedReferencePath } from "./javascriptSemanticCopiedReferencePaths.js"; import { semanticStoredSourceSelection } from "./javascriptSemanticIterationSources.js"; import { semanticEffectPathCandidates, @@ -227,7 +227,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/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]; -}; diff --git a/src/domain/javascript/javascriptSemanticRequireOrigin.ts b/src/domain/javascript/javascriptSemanticRequireOrigin.ts index 1e924ab607f..59475e18d6d 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, @@ -1265,7 +1261,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/javascriptSemanticState.ts b/src/domain/javascript/javascriptSemanticState.ts index 946ac319779..367743bb285 100644 --- a/src/domain/javascript/javascriptSemanticState.ts +++ b/src/domain/javascript/javascriptSemanticState.ts @@ -119,17 +119,23 @@ 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. */ 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/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/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 new file mode 100644 index 00000000000..eba4460ca60 --- /dev/null +++ b/tests/acceptance/applications/electronModuleInitializationCli.test.ts @@ -0,0 +1,208 @@ +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"); + require("./early-loop.cjs"); + require("./late-loop.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"); + `, + "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(4); + 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, + ); + 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 }, + }, + ], + }); + } + }, +); + +cliTest.for([ + ["CLI", false], + ["stdio MCP", false], + ["CLI", true], + ["stdio MCP", true], + ["CLI", "cached-eval"], + ["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"], + ["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", "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"], + ["stdio MCP", "iteration-pattern"], +] as const)( + "preserves classic global initialization uncertainty through %s", + async ([surface, alias], { cli }) => { + const root = await createTestTempDirectory( + "rea-electron-global-initialization-", + ); + const activation = + 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");'} + ${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 }); } + ${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, { + [earlyName]: source(true), + [lateName]: 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(earlyName)).toHaveLength(1); + expect(inSource(earlyName)[0]?.properties).toMatchObject({ + web_preferences_status: "dynamic", + web_preferences: [], + }); + 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 } }, + ], + }); + }, +); 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]