Skip to content

Commit 4730d8a

Browse files
Copilotna-trium-144
andcommitted
Fix JavaScript worker to use direct eval for state persistence
Co-authored-by: na-trium-144 <100704180+na-trium-144@users.noreply.github.com>
1 parent 6b0ede3 commit 4730d8a

File tree

1 file changed

+4
-18
lines changed

1 file changed

+4
-18
lines changed

public/javascript.worker.js

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// JavaScript web worker
22
let jsOutput = [];
33
let executedCommands = []; // Store successfully executed commands for state recovery
4-
let globalScope = {}; // Store global variables and functions
54

65
// Helper function to capture console output
76
function createConsoleProxy() {
@@ -24,7 +23,6 @@ function createConsoleProxy() {
2423
async function init(id) {
2524
// Initialize the worker
2625
executedCommands = [];
27-
globalScope = {};
2826
self.postMessage({ id, payload: { success: true } });
2927
}
3028

@@ -34,14 +32,9 @@ async function runJavaScript(id, payload) {
3432
// Create a console proxy to capture output
3533
const console = createConsoleProxy();
3634

37-
// Execute the code with eval in the global scope
38-
// Use Function constructor with global scope to maintain state across calls
39-
const func = new Function('console', 'globalScope', `
40-
with (globalScope) {
41-
return eval(${JSON.stringify(code)});
42-
}
43-
`);
44-
const result = func(console, globalScope);
35+
// Execute code directly with eval in the worker global scope
36+
// This will preserve variables across calls
37+
const result = eval(code);
4538

4639
if (result !== undefined) {
4740
jsOutput.push({
@@ -104,25 +97,18 @@ async function restoreState(id) {
10497
const commandsToRestore = [...executedCommands];
10598
executedCommands = []; // Clear before re-executing
10699
jsOutput = []; // Clear output for restoration
107-
const newGlobalScope = {}; // Create a fresh global scope
108100

109101
for (const command of commandsToRestore) {
110102
try {
111103
const console = createConsoleProxy();
112-
const func = new Function('console', 'globalScope', `
113-
with (globalScope) {
114-
return eval(${JSON.stringify(command)});
115-
}
116-
`);
117-
func(console, newGlobalScope);
104+
eval(command);
118105
executedCommands.push(command);
119106
} catch (e) {
120107
// If restoration fails, we still continue with other commands
121108
console.error("Failed to restore command:", command, e);
122109
}
123110
}
124111

125-
globalScope = newGlobalScope; // Update the global scope
126112
jsOutput = []; // Clear any output from restoration
127113
self.postMessage({ id, payload: { success: true } });
128114
}

0 commit comments

Comments
 (0)