Bugfix/Custom Function Libraries (#5472)

* Updated the executeJavaScriptCode function to automatically detect and install required libraries from import/require statements in the provided code.

* Update utils.ts

* lint-fix
This commit is contained in:
Henry Heng
2025-11-15 20:57:42 +00:00
committed by GitHub
parent 3cab803918
commit 888994bc8f
2 changed files with 24 additions and 4 deletions
+22 -2
View File
@@ -1500,9 +1500,29 @@ export const executeJavaScriptCode = async (
const sbx = await Sandbox.create({ apiKey: process.env.E2B_APIKEY, timeoutMs })
// Determine which libraries to install
const librariesToInstall = new Set<string>(libraries)
// Auto-detect required libraries from code
// Extract required modules from import/require statements
const importRegex = /(?:import\s+.*?\s+from\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g
let match
while ((match = importRegex.exec(code)) !== null) {
const moduleName = match[1] || match[2]
// Extract base module name (e.g., 'typeorm' from 'typeorm/something')
const baseModuleName = moduleName.split('/')[0]
librariesToInstall.add(baseModuleName)
}
// Install libraries
for (const library of libraries) {
await sbx.commands.run(`npm install ${library}`)
for (const library of librariesToInstall) {
// Validate library name to prevent command injection.
const validPackageNameRegex = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/
if (validPackageNameRegex.test(library)) {
await sbx.commands.run(`npm install ${library}`)
} else {
console.warn(`[Sandbox] Skipping installation of invalid module: ${library}`)
}
}
// Separate imports from the rest of the code for proper ES6 module structure