(
_code: string,
globals: Record<string, any> = {}
)
| 63 | * Only run code with isolated-vm |
| 64 | */ |
| 65 | export async function runCodeInIVM( |
| 66 | _code: string, |
| 67 | globals: Record<string, any> = {} |
| 68 | ): Promise<IVMExecutionResult> { |
| 69 | const start = Date.now(); |
| 70 | // const transformedCode = await transformTypescriptCode(_code); |
| 71 | let sourceCode = _code; |
| 72 | |
| 73 | if (env.enableFunctionWorkerTypescriptSupport) { |
| 74 | sourceCode = await transformTypescriptCode(sourceCode); |
| 75 | } |
| 76 | |
| 77 | // avoid end comment with line break |
| 78 | const code = `${environmentScript} |
| 79 | |
| 80 | ${sourceCode}`; |
| 81 | |
| 82 | const isolate = new ivm.Isolate({ memoryLimit: env.sandbox.memoryLimit }); |
| 83 | const logger: any[][] = []; |
| 84 | |
| 85 | let res: any; |
| 86 | let err: any; |
| 87 | let context: ivm.Context | undefined; |
| 88 | let script: ivm.Script | undefined; |
| 89 | |
| 90 | try { |
| 91 | context = await isolate.createContext(); |
| 92 | script = await isolate.compileScript(code); |
| 93 | |
| 94 | buildSandbox(context, { |
| 95 | globals, |
| 96 | console: { |
| 97 | log: (...args: any[]) => { |
| 98 | logger.push(['log', Date.now(), ...args]); |
| 99 | }, |
| 100 | warn: (...args: any[]) => { |
| 101 | logger.push(['warn', Date.now(), ...args]); |
| 102 | }, |
| 103 | error: (...args: any[]) => { |
| 104 | logger.push(['error', Date.now(), ...args]); |
| 105 | }, |
| 106 | }, |
| 107 | }); |
| 108 | |
| 109 | try { |
| 110 | res = await script.run(context, { |
| 111 | promise: true, |
| 112 | copy: true, |
| 113 | }); |
| 114 | } catch (e) { |
| 115 | console.trace(e); |
| 116 | err = e; |
| 117 | } |
| 118 | |
| 119 | const cpuTime = Number(isolate.cpuTime); // unit: ns |
| 120 | const memoryUsage = await isolate.getHeapStatistics(); // unit: bytes |
| 121 | |
| 122 | return { |
no test coverage detected