(
code: string,
options: RunCodeOptions = {}
)
| 73 | * @returns The execution result |
| 74 | */ |
| 75 | export async function executeCode( |
| 76 | code: string, |
| 77 | options: RunCodeOptions = {} |
| 78 | ): Promise<ExecutionResult> { |
| 79 | const sandbox = await createSandbox(); |
| 80 | |
| 81 | try { |
| 82 | // Prepare the code based on the language |
| 83 | let preparedCode = code; |
| 84 | const language = options.language || "python"; |
| 85 | |
| 86 | if (language === "typescript" && !code.includes("///@ts-nocheck")) { |
| 87 | // Add ts-nocheck to avoid TypeScript errors in the sandbox |
| 88 | preparedCode = "///@ts-nocheck\n" + code; |
| 89 | } |
| 90 | |
| 91 | if (language === "python" && !code.trim().startsWith("!pip") && !code.trim().startsWith("import")) { |
| 92 | // For Python, ensure basic imports are available |
| 93 | preparedCode = "import sys\nimport os\n" + preparedCode; |
| 94 | } |
| 95 | |
| 96 | // Set up execution options |
| 97 | const execOptions: any = { |
| 98 | language |
| 99 | }; |
| 100 | |
| 101 | if (options.stream) { |
| 102 | execOptions.onStdout = (data: any) => console.log("[stdout]", data); |
| 103 | execOptions.onStderr = (data: any) => console.error("[stderr]", data); |
| 104 | } |
| 105 | |
| 106 | // Execute the code with timeout |
| 107 | let execution: any; |
| 108 | if (options.timeout) { |
| 109 | // Create a promise that rejects after the timeout |
| 110 | const timeoutPromise = new Promise<never>((_, reject) => { |
| 111 | setTimeout(() => reject(new Error(`Execution timed out after ${options.timeout}ms`)), options.timeout); |
| 112 | }); |
| 113 | |
| 114 | // Race the execution against the timeout |
| 115 | // @ts-ignore - Ignore TypeScript errors for API compatibility |
| 116 | execution = await Promise.race([ |
| 117 | sandbox.runCode(preparedCode, execOptions), |
| 118 | timeoutPromise |
| 119 | ]); |
| 120 | } else { |
| 121 | // @ts-ignore - Ignore TypeScript errors for API compatibility |
| 122 | execution = await sandbox.runCode(preparedCode, execOptions); |
| 123 | } |
| 124 | |
| 125 | // Format the result to match our ExecutionResult interface |
| 126 | const result: ExecutionResult = { |
| 127 | text: execution.text || "", |
| 128 | results: execution.results || [], |
| 129 | error: execution.error ? { |
| 130 | type: "error", |
| 131 | value: typeof execution.error === 'string' ? execution.error : JSON.stringify(execution.error) |
| 132 | } : null, |
no test coverage detected