()
| 12 | * Creates a reusable safe-eval sandbox to execute code in. |
| 13 | */ |
| 14 | export function createSandbox(): <T>(code: string, context?: any) => T { |
| 15 | const sandbox = createContext({}); |
| 16 | return (code: string, context?: any) => { |
| 17 | const response = `SAFE_EVAL_${Math.floor(Math.random() * 1000000)}`; |
| 18 | sandbox[response] = {}; |
| 19 | if (context) { |
| 20 | Object.keys(context).forEach((key) => sandbox[key] = context[key]); |
| 21 | runInContext( |
| 22 | `try { ${response} = ${code} } catch (e) { ${response} = undefined }`, |
| 23 | sandbox |
| 24 | ); |
| 25 | for (const key of Object.keys(context)) { |
| 26 | delete sandbox[key]; |
| 27 | } |
| 28 | } else { |
| 29 | try { |
| 30 | runInContext(`${response} = ${code}`, sandbox); |
| 31 | } catch { |
| 32 | sandbox[response] = undefined; |
| 33 | } |
| 34 | } |
| 35 | return sandbox[response]; |
| 36 | }; |
| 37 | } |
| 38 | |
| 39 | export const safeEval = createSandbox(); |
| 40 |
no test coverage detected