| 84 | * @returns The execution result |
| 85 | */ |
| 86 | export async function executeCode( |
| 87 | code: string, |
| 88 | options: { |
| 89 | stream?: boolean; |
| 90 | language?: "python" | "javascript" | "typescript"; |
| 91 | timeout?: number; |
| 92 | } = {}, |
| 93 | ): Promise<ExecutionResult> { |
| 94 | const sandbox = await createSandbox(); |
| 95 | |
| 96 | try { |
| 97 | // Prepare the code based on the language |
| 98 | let preparedCode = code; |
| 99 | const language = options.language || "python"; |
| 100 | |
| 101 | if (language === "typescript" && !code.includes("///@ts-nocheck")) { |
| 102 | // Add ts-nocheck to avoid TypeScript errors in the sandbox |
| 103 | preparedCode = "///@ts-nocheck\n" + code; |
| 104 | } |
| 105 | |
| 106 | if ( |
| 107 | language === "python" && !code.trim().startsWith("!pip") && !code.trim().startsWith("import") |
| 108 | ) { |
| 109 | // For Python, ensure basic imports are available |
| 110 | preparedCode = "import sys\nimport os\n" + preparedCode; |
| 111 | } |
| 112 | |
| 113 | // Set up execution options |
| 114 | const execOptions: any = { |
| 115 | language, |
| 116 | }; |
| 117 | |
| 118 | if (options.stream) { |
| 119 | execOptions.onStdout = (data: any) => console.log("[stdout]", data); |
| 120 | execOptions.onStderr = (data: any) => console.error("[stderr]", data); |
| 121 | } |
| 122 | |
| 123 | // Execute the code with timeout |
| 124 | let execution: any; |
| 125 | if (options.timeout) { |
| 126 | // Create a promise that rejects after the timeout |
| 127 | const timeoutPromise = new Promise<never>((_, reject) => { |
| 128 | setTimeout( |
| 129 | () => reject(new Error(`Execution timed out after ${options.timeout}ms`)), |
| 130 | options.timeout, |
| 131 | ); |
| 132 | }); |
| 133 | |
| 134 | // Race the execution against the timeout |
| 135 | // @ts-ignore - Ignore TypeScript errors for API compatibility |
| 136 | execution = await Promise.race([ |
| 137 | sandbox.runCode(preparedCode, execOptions), |
| 138 | timeoutPromise, |
| 139 | ]); |
| 140 | } else { |
| 141 | // @ts-ignore - Ignore TypeScript errors for API compatibility |
| 142 | execution = await sandbox.runCode(preparedCode, execOptions); |
| 143 | } |