(
code: string,
sandbox: ICommonObject,
options: {
timeout?: number
useSandbox?: boolean
libraries?: string[]
streamOutput?: (output: string) => void
nodeVMOptions?: ICommonObject
} = {}
)
| 1589 | * @returns {Promise<any>} - The execution result |
| 1590 | */ |
| 1591 | export const executeJavaScriptCode = async ( |
| 1592 | code: string, |
| 1593 | sandbox: ICommonObject, |
| 1594 | options: { |
| 1595 | timeout?: number |
| 1596 | useSandbox?: boolean |
| 1597 | libraries?: string[] |
| 1598 | streamOutput?: (output: string) => void |
| 1599 | nodeVMOptions?: ICommonObject |
| 1600 | } = {} |
| 1601 | ): Promise<any> => { |
| 1602 | const { timeout = 300000, useSandbox = true, streamOutput, libraries = [], nodeVMOptions = {} } = options |
| 1603 | const shouldUseE2BSandbox = useSandbox && process.env.E2B_APIKEY |
| 1604 | |
| 1605 | let timeoutMs = timeout |
| 1606 | if (process.env.SANDBOX_TIMEOUT) { |
| 1607 | timeoutMs = parseInt(process.env.SANDBOX_TIMEOUT, 10) |
| 1608 | } |
| 1609 | |
| 1610 | if (shouldUseE2BSandbox) { |
| 1611 | try { |
| 1612 | const variableDeclarations = [] |
| 1613 | |
| 1614 | if (sandbox['$vars']) { |
| 1615 | variableDeclarations.push(`const $vars = ${JSON.stringify(sandbox['$vars'])};`) |
| 1616 | } |
| 1617 | |
| 1618 | if (sandbox['$flow']) { |
| 1619 | variableDeclarations.push(`const $flow = ${JSON.stringify(sandbox['$flow'])};`) |
| 1620 | } |
| 1621 | |
| 1622 | // Add other sandbox variables |
| 1623 | for (const [key, value] of Object.entries(sandbox)) { |
| 1624 | if ( |
| 1625 | key !== '$vars' && |
| 1626 | key !== '$flow' && |
| 1627 | key !== 'util' && |
| 1628 | key !== 'Symbol' && |
| 1629 | key !== 'child_process' && |
| 1630 | key !== 'fs' && |
| 1631 | key !== 'process' |
| 1632 | ) { |
| 1633 | variableDeclarations.push(`const ${key} = ${JSON.stringify(value)};`) |
| 1634 | } |
| 1635 | } |
| 1636 | |
| 1637 | // Handle import statements properly - they must be at the top |
| 1638 | const lines = code.split('\n') |
| 1639 | const importLines = [] |
| 1640 | const otherLines = [] |
| 1641 | |
| 1642 | for (const line of lines) { |
| 1643 | const trimmedLine = line.trim() |
| 1644 | |
| 1645 | // Skip node-fetch imports since Node.js has built-in fetch |
| 1646 | if (trimmedLine.includes('node-fetch') || trimmedLine.includes("'fetch'") || trimmedLine.includes('"fetch"')) { |
| 1647 | continue // Skip this line entirely |
| 1648 | } |
no test coverage detected