Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/heavy-bananas-dream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cloudflare/sandbox": patch
---

fix JS and TS executors to await Promise in context execution
47 changes: 32 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/sandbox-container/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
},
"dependencies": {
"@repo/shared": "*",
"acorn": "^8.14.0",
"esbuild": "^0.27.0",
"zod": "^3.22.3"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { fileURLToPath } from 'node:url';
import * as util from 'node:util';
import * as vm from 'node:vm';
import type { RichOutput } from '../../process-pool';
import { transformForAsyncExecution } from '../shared/code-transformer';
import { isThenable } from '../shared/thenable';

// Create CommonJS-like globals for the sandbox
const __filename = fileURLToPath(import.meta.url);
Expand Down Expand Up @@ -83,7 +85,14 @@ rl.on('line', async (line: string) => {
options.timeout = timeout;
}

result = vm.runInContext(code, context, options);
// Transform code to support top-level await and capture last expression
const wrappedCode = transformForAsyncExecution(code);
result = vm.runInContext(wrappedCode, context, options);

// Result is always a Promise from async IIFE - await it
if (isThenable(result)) {
result = await result;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical timeout bypass: vm.runInContext timeout only applies to sync execution. When awaiting the Promise here, long-running or infinite Promises ignore the timeout entirely.

Wrap in Promise.race:

if (isThenable(result)) {
  if (timeout !== undefined) {
    const timeoutPromise = new Promise((_, reject) => 
      setTimeout(() => reject(new Error('Execution timeout')), timeout)
    );
    result = await Promise.race([result, timeoutPromise]);
  } else {
    result = await result;
  }
}

} catch (error: unknown) {
const err = error as Error;
stderr += err.stack || err.toString();
Expand Down
Loading