|
| 1 | +import { IAgent as Agent } from '@sre/types/Agent.types'; |
| 2 | +import { Component } from './Component.class'; |
| 3 | +import Joi from 'joi'; |
| 4 | +import { ConnectorService } from '@sre/Core/ConnectorsService'; |
| 5 | +import { CodeExecutionResult } from '@sre/ComputeManager/Code.service/CodeConnector'; |
| 6 | + |
| 7 | +export class ECMASandbox extends Component { |
| 8 | + protected configSchema = Joi.object({ |
| 9 | + code: Joi.string().max(500000).allow('').label('Code'), |
| 10 | + }); |
| 11 | + constructor() { |
| 12 | + super(); |
| 13 | + } |
| 14 | + init() {} |
| 15 | + async process(input, config, agent: Agent) { |
| 16 | + await super.process(input, config, agent); |
| 17 | + |
| 18 | + const logger = this.createComponentLogger(agent, config); |
| 19 | + try { |
| 20 | + let Output: any = {}; |
| 21 | + let _error = undefined; |
| 22 | + |
| 23 | + let codeInputs = {}; |
| 24 | + for (let fieldName in input) { |
| 25 | + const _type = typeof input[fieldName]; |
| 26 | + switch (_type) { |
| 27 | + case 'string': |
| 28 | + const b64encoded = Buffer.from(input[fieldName]).toString('base64'); |
| 29 | + codeInputs[fieldName] = `___internal.b64decode('${b64encoded}')`; |
| 30 | + break; |
| 31 | + case 'number': |
| 32 | + case 'boolean': |
| 33 | + codeInputs[fieldName] = input[fieldName]; |
| 34 | + break; |
| 35 | + default: |
| 36 | + codeInputs[fieldName] = input[fieldName]; |
| 37 | + break; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + const inputVarsCode = this.generateInputVarCode(codeInputs); |
| 42 | + const code = inputVarsCode + '\n' + config.data.code; |
| 43 | + |
| 44 | + logger.debug(`Running code: \n${code}\n`); |
| 45 | + |
| 46 | + const ecmaCodeConnector = ConnectorService.getCodeConnector('ECMASandbox'); |
| 47 | + |
| 48 | + const executionResponse: CodeExecutionResult = await ecmaCodeConnector.agent(agent.id).execute(config.id, { code }); |
| 49 | + if (executionResponse.success) { |
| 50 | + Output = executionResponse.output; |
| 51 | + } else { |
| 52 | + Output = undefined; |
| 53 | + _error = executionResponse.errors; |
| 54 | + } |
| 55 | + |
| 56 | + return { Output, _error, _debug: logger.output }; |
| 57 | + } catch (err: any) { |
| 58 | + const _error = err?.response?.data || err?.message || err.toString(); |
| 59 | + logger.error(`Error running code: \n${_error}\n`); |
| 60 | + return { Output: undefined, _error, _debug: logger.output }; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private generateInputVarCode(input: Record<string, any>) { |
| 65 | + let input_vars = ''; |
| 66 | + for (const key in input) { |
| 67 | + input_vars += `var ${key} = ${input[key]};\n`; |
| 68 | + } |
| 69 | + return input_vars; |
| 70 | + } |
| 71 | +} |
0 commit comments