Added function execution logic locally instead of 3P API using vm, modified executor to handle connection block (still testing)

This commit is contained in:
Waleed Latif
2025-02-08 14:21:41 -08:00
parent f366b557d5
commit 30d3e934db
11 changed files with 557 additions and 265 deletions
+89
View File
@@ -0,0 +1,89 @@
import { NextRequest, NextResponse } from 'next/server'
import { Script, createContext } from 'vm'
// Explicitly export allowed methods
export const dynamic = 'force-dynamic' // Disable static optimization
export const runtime = 'nodejs' // Use Node.js runtime
export async function POST(req: NextRequest) {
const startTime = Date.now()
let stdout = ''
try {
const body = await req.json()
const { code, timeout = 3000 } = body
// Check if code contains unresolved template variables
if (code.includes('<') && code.includes('>')) {
throw new Error(
'Code contains unresolved template variables. Please ensure all variables are resolved before execution.'
)
}
// Create a secure context with console logging
const context = createContext({
console: {
log: (...args: any[]) => {
const logMessage =
args
.map((arg) => (typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)))
.join(' ') + '\n'
stdout += logMessage
},
error: (...args: any[]) => {
const errorMessage =
args
.map((arg) => (typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)))
.join(' ') + '\n'
console.error('❌ Code Console Error:', errorMessage.trim())
stdout += 'ERROR: ' + errorMessage
},
},
})
// Create and run the script
const script = new Script(`
(async () => {
try {
${code}
} catch (error) {
console.error(error);
throw error;
}
})()
`)
const result = await script.runInContext(context, {
timeout,
displayErrors: true,
})
const executionTime = Date.now() - startTime
const response = {
success: true,
output: {
result,
stdout,
executionTime,
},
}
return NextResponse.json(response)
} catch (error: any) {
const executionTime = Date.now() - startTime
const errorResponse = {
success: false,
error: error.message || 'Code execution failed',
output: {
result: null,
stdout,
executionTime,
},
}
return NextResponse.json(errorResponse, { status: 500 })
}
}