Repository navigation
fix(javascript): resolve module-level Electron options in functions - #8634
ShuaixinHuang wants to merge 7 commits into
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9611e5cbe8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| name = semanticStaticPropertyKey(node.property, node.computed); | ||
| } | ||
| if (name === null) return; |
There was a problem hiding this comment.
Keep unresolved global accesses in the activation check
For a classic script containing const key = 'createWindow'; globalThis[key](); before the preferences declaration and a later bare createWindow(), the early access is dropped: semanticStaticPropertyKey cannot resolve the identifier key, so name stays null. The late call then makes hasDefiniteInitializer true although the early activation reaches the captured const in its temporal dead zone, enabling incorrect literal-option resolution through optionObjectCandidate. Resolve the computed key through the semantic owner or invalidate the timing proof for unresolved global accesses; an unresolved function identity is not evidence that no early access occurred.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
| let owner = parents.get(enclosingFunction); | ||
| owner !== undefined; | ||
| owner = parents.get(owner) | ||
| ) | ||
| if (t.isStatement(owner)) return statementPosition(owner, parents); |
There was a problem hiding this comment.
Stop creation-position lookup at enclosing callable boundaries
With createWindow(); const webPreferences = {nodeIntegration: true}; function createWindow(make = () => new BrowserWindow({webPreferences})) { make(); } after the Electron import, this walk reaches the outer FunctionDeclaration and treats its later source position as the arrow's creation time, even though the hoisted function was already activated. The early call throws on webPreferences, but the new branch returns hasDefiniteInitializer: true, enabling literal-option resolution. Stop at intervening callable boundaries, or prove the outer activation's timing, rather than using its declaration order.
Useful? React with 👍 / 👎.
[Medium impact] The change reaches shared JavaScript static-analysis results across several analysis paths. The PR needs corrections before merging because early calls can be missed and long alias chains can break file analysis. FindingsFix with agent prompt### Issue 1
src/domain/javascript/javascriptSemanticMutationInitializers.ts:909-915
`resolveSemanticBindingState` drops uncertain bindings, so the scan ignores `with ({}) { createWindow(); }` before the `webPreferences` initializer. A later bare `createWindow()` then looks like the first use. The early call can reach the hoisted function before initialization, yet Electron analysis reports literal preferences.
Keep possible matches unknown instead of dropping them. The repository requires unresolved identity to remain unknown.
### Issue 2
src/domain/javascript/javascriptSemanticMutationInitializers.ts:886-890
`globalReceiver` adds one nested call per alias with no depth bound. A valid flat script with thousands of aliases and a member access through the last alias can exhaust the call stack when a captured module constant starts this scan. The `seen` set stops cycles, not long chains. The worker reports a resource failure before retaining the file's static results.
Use an iterative, bounded walk and reuse its results across member accesses. Repository rules require bounded resource use and shared work.
### Issue 3
src/domain/javascript/javascriptSemanticMutationInitializers.ts:871-872
A plain `.cjs` file has `program.sourceType === "script"`, but its top-level functions belong to Node's wrapper. For example, `exports.createWindow = () => {}; this.createWindow();` before the preferences initializer calls an exported function, not the separate local `createWindow`. This scan counts it as an early local call, so valid preferences used by a later bare call stay unknown.
Use the parser-owned `javaScriptRuntimeContext` to exclude CommonJS. The repository requires consumers to use the owner's parsed facts; that requirement must be satisfied before merging.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryThis PR recovers module-level Electron options inside functions while keeping early calls uncertain.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A["Captured module constant"] --> B["Find enclosing function"]
B --> C{"Initializer precedes first possible use?"}
C -->|"No or unknown"| D["Keep options dynamic"]
C -->|"Yes"| E["Mark initialized; keep capture order unknown"]
E --> F{"Relevant writes or escapes?"}
F -->|"Yes"| D
F -->|"No"| G["Report literal Electron options"]
Reviews (2) · Last reviewed commit: "fix(javascript): bind first activations ..." · Reviewed by Greptile |
| : resolveSemanticBindingState(state, node, node.name); | ||
| if ( | ||
| state === undefined || | ||
| (candidate != null && | ||
| binding?.initializers.some( | ||
| ({ node: value }) => value === candidate, | ||
| )) |
There was a problem hiding this comment.
resolveSemanticBindingState drops uncertain bindings, so the scan ignores with ({}) { createWindow(); } before the webPreferences initializer. A later bare createWindow() then looks like the first use. The early call can reach the hoisted function before initialization, yet Electron analysis reports literal preferences.
Keep possible matches unknown instead of dropping them. The repository requires unresolved identity to remain unknown.
Context Used: AGENTS.md (source)
Knowledge Base Used: Artifact and application analysis
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptSemanticMutationInitializers.ts
Line: 909-915
Comment:
**Early calls are skipped**
`resolveSemanticBindingState` drops uncertain bindings, so the scan ignores `with ({}) { createWindow(); }` before the `webPreferences` initializer. A later bare `createWindow()` then looks like the first use. The early call can reach the hoisted function before initialization, yet Electron analysis reports literal preferences.
Keep possible matches unknown instead of dropping them. The repository requires unresolved identity to remain unknown.
**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))
**Knowledge Base Used:** [Artifact and application analysis](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fartifact-and-application-analysis.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| if (seen.has(binding.bindingId)) return false; | ||
| seen.add(binding.bindingId); | ||
| return binding.initializers.some(({ node: value }) => | ||
| globalReceiver(value, seen), | ||
| ); |
There was a problem hiding this comment.
Long aliases break file analysis
globalReceiver adds one nested call per alias with no depth bound. A valid flat script with thousands of aliases and a member access through the last alias can exhaust the call stack when a captured module constant starts this scan. The seen set stops cycles, not long chains. The worker reports a resource failure before retaining the file's static results.
Use an iterative, bounded walk and reuse its results across member accesses. Repository rules require bounded resource use and shared work.
Context Used: AGENTS.md (source)
Knowledge Base Used: Artifact and application analysis
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptSemanticMutationInitializers.ts
Line: 886-890
Comment:
**Long aliases break file analysis**
`globalReceiver` adds one nested call per alias with no depth bound. A valid flat script with thousands of aliases and a member access through the last alias can exhaust the call stack when a captured module constant starts this scan. The `seen` set stops cycles, not long chains. The worker reports a resource failure before retaining the file's static results.
Use an iterative, bounded walk and reuse its results across member accesses. Repository rules require bounded resource use and shared work.
**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))
**Knowledge Base Used:** [Artifact and application analysis](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fartifact-and-application-analysis.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| const classicScript = | ||
| t.isProgram(program) && program.sourceType === "script"; |
There was a problem hiding this comment.
A plain .cjs file has program.sourceType === "script", but its top-level functions belong to Node's wrapper. For example, exports.createWindow = () => {}; this.createWindow(); before the preferences initializer calls an exported function, not the separate local createWindow. This scan counts it as an early local call, so valid preferences used by a later bare call stay unknown.
Use the parser-owned javaScriptRuntimeContext to exclude CommonJS. The repository requires consumers to use the owner's parsed facts; that requirement must be satisfied before merging.
Context Used: AGENTS.md (source)
Knowledge Base Used: Artifact and application analysis
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptSemanticMutationInitializers.ts
Line: 871-872
Comment:
**CommonJS calls hide settings**
A plain `.cjs` file has `program.sourceType === "script"`, but its top-level functions belong to Node's wrapper. For example, `exports.createWindow = () => {}; this.createWindow();` before the preferences initializer calls an exported function, not the separate local `createWindow`. This scan counts it as an early local call, so valid preferences used by a later bare call stay unknown.
Use the parser-owned `javaScriptRuntimeContext` to exclude CommonJS. The repository requires consumers to use the owner's parsed facts; that requirement must be satisfied before merging.
**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))
**Knowledge Base Used:** [Artifact and application analysis](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fartifact-and-application-analysis.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4cd804cbcc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| (candidate != null && | ||
| binding?.initializers.some( | ||
| ({ node: value }) => value === candidate, | ||
| )) |
There was a problem hiding this comment.
Preserve possible function reads through with scopes
When a classic-script createWindow captures webPreferences, an early with ({}) { createWindow(); } followed by the preferences declaration and a later bare call is incorrectly considered safe. semanticBindingLookupAt returns uncertain-binding for the early call, but resolveSemanticBindingState reduces it to undefined, so this condition drops the possible reference and moduleFunctionFirstRead retains only the late call. The new branch consequently sets hasDefiniteInitializer: true even though the early call accesses the captured const in its temporal dead zone, enabling incorrect literal preferences through optionObjectCandidate. Use the tagged lookup to retain the possible outer binding and invalidate its timing proof.
AGENTS.md reference: AGENTS.md:L21-L21
Useful? React with 👍 / 👎.
Superseded by #8666 at the author's request: #8666 . Same published branch/HEAD; original discussion and historical validation are preserved below.
Current review correction
Current HEAD:
4cd804cbcc17dc76f02c27f327f577d2fc7b3665.Reproduced the global-object-alias early-call case and the unrelated same-named parameter case (3 new cases failed on the prior head). The shared initializer timing owner now consumes existing lexical binding state: identifier reads match the actual function binding, and classic-script global receivers follow binding-owned initializer aliases with a cycle guard. All production callers now pass their existing analysis state rather than only its parent map; low-level parent-map-only tests retain their API. No target source is executed by analysis. Validation: 112 passed across initializer, call-resolution, Electron options and compiled CLI/stdio MCP files, plus 277 sibling binding/loader/fingerprint cases; check:fast 2/2 passed (43.349s). The VM controls confirm the early alias call reaches the temporal dead zone while the late control succeeds. These are synthetic source/VM and actual compiled CLI/MCP checks, not a real Electron application run.
The new HEAD requires its own hosted CI; earlier green runs below belong to earlier commits. Existing human declarations remain in force. The original replacement description and its execution points follow as historical context.
Supersedes #8495 at the author's explicit request to resubmit all current PRs. Same published branch and HEAD
9611e5cbe8d0d3639f87df529d2989e69a63d1f2. Original discussion and historical validation remain at #8495. This new PR requires its own hosted CI and a new human declaration for this PR ID; prior review declarations are historical.Supersedes #8250 at the author's explicit request to resubmit the existing PRs. This replacement reuses the identical published head
cc2bb1242a5611527bfb99935bc7dbcf85e902f7and full three-file patch. Prior discussion and historical verification remain at #8250 (earlier #8087). No code changes or new local test runs were made for this resubmission. This new PR requires its own hosted CI. The owner has specifically confirmed review of this replacement PR's final diff, evidence, limitations and unresolved P1, accepted full responsibility, and approved it for initial maintainer review. The P1 remains a before-merge blocker.Outstanding review follow-up — addressed in the current published revision
The known P1 review finding was addressed in the current head. In a classic script, an early
globalThis.createWindow()followed by a later bare call can make module-constant initialization appear definite even though the early activation encounters the temporal dead zone. The previously reported 115-test verification below does not establish that this additional case is fixed.A separate local draft follow-up has 67 focused tests and three build tasks passing, plus
check:fast; expanded verification and commit/push are not complete. That draft is not part of this PR's published commit or diff, and those draft results are not claimed as a fix in this revision. The prior finding is covered by the current-head regression; hosted CI and maintainer review still apply; the original review is preserved rather than marked resolved.Supersedes #8087 at the author's request. This replacement reuses verified head cc2bb12 and preserves the original discussion and validation record at #8087. Historical revision-specific validation below remains at its stated execution points. This new PR must pass its own hosted CI.
Problem and resulting behavior
Fixes #7227. Electron static analysis loses module-level immutable
webPreferencesread inside a later activation. Retain those settings when initialization precedes the function's module-level uses, while preserving uncertainty when a hoisted function can run earlier.For example, this source must remain dynamic rather than report a proven
nodeIntegration: true:Moving the call after the const initializer yields
object-literalwith the literal setting, including when the function declaration appears before the initializer.Owning change and scope
Initialization coverage stays in
javascriptSemanticMutationInitializers.ts; Electron consumers use that fact without reinterpreting declaration order. A hoisted declaration's position does not prove activation timing. The owner indexes module-level function references once per immutable module body and treats earlier aliases, indirect activations, live exports and unproven timing conservatively. This is a bounded reference-order check, not a general call graph or runtime execution proof.The existing ancestry cache also retains the enclosing function, avoiding repeated walks from deep reads. Initialization coverage remains separate from cross-function capture ordering: the latter stays unresolved so named child-process argv shapes retain their existing uncertainty. No public schema, provider, execution authority, deadline, resource ceiling or assertion was weakened.
Validation at the current follow-up
Windows, Node 24.22.1 / npm 11.16.0:
fb2532ad61ceb4cce7d233131fc1edd4305925ff, with the new source regressions: 4 failed / 47 passed. Three cases expose early direct, aliased and forwarding calls; the fourth exposes a late-call positive control.9bafc838629358fb8ebc0ce86abefa5c82c8a0ab: 112/112 passed across six complete files: Electron options 51, existing scope-depth/resource controls 14, binding initializers 13, argument shapes 30, existing child-process compiled CLI/stdio MCP 2, and new Electron initialization compiled CLI/stdio MCP 2. Three build prerequisite tasks passed.The earlier head's independent hosted CI passed, but it did not cover this hoisted-declaration review case. The new head requires its own hosted CI; an earlier green run does not validate it. Local checks use synthetic JavaScript through production static analysis and real local compiled CLI/stdio MCP. No real Electron application or Linux/macOS execution is claimed.
Loop ownership review follow-up
Commit
cc2bb1242a5611527bfb99935bc7dbcf85e902f7keeps enclosing-function identity in its own immutable ancestry cache. Loop ordering remains uncertain; entering a loop no longer erases which function owns the read. This retains initialized module-level Electron settings inside for-of, for and while loops while keeping early calls dynamic. No downstream reinterpretation or call graph expansion was added.On exact preceding head
9bafc838, the three new loop source cases fail while the existing 51 pass. With the correction, six complete files pass 115/115 (Electron 54, scope-depth 14, initializers 13, shapes 30, existing child-process CLI/MCP 2, Electron initialization CLI/MCP 2). The public adapter cases include both early and late calls inside loops and outside loops, with source provenance. All three committed files match the tested bytes exactly after normal precommit hooks. Three build tasks passed; normal prepush typecheck/lint passed 2/2, 46.166 seconds. No assertions or resource controls were relaxed.The earlier
9bafc838own hosted workflow41009833080completed successfully; the newcc2bb124head requires independent hosted validation. Validation uses synthetic inert JavaScript and real local compiled CLI/stdio MCP on Windows, Node 24.22.1 / npm 11.16.0; no real Electron application or Linux/macOS run is claimed.Author readiness
Human owner: @ShuaixinHuang
Before merge
type(scope): outcome.Current-head P1 correction
Commit
9611e5cbe8d0d3639f87df529d2989e69a63d1f2covers the classic-script global activation case. Focused domain and CLI/stdio MCP validation passed 67/67 tests;check:fastpassed 2/2. The local regression covers early and lateglobalThis/window/self/thisactivations without expanding call-graph or authority semantics.This replacement preserves the prior PR discussion and validation history at #8331. It reuses the verified published head and requires its own hosted CI.