| 5 | * @returns The result of executing the function |
| 6 | */ |
| 7 | export function execute( |
| 8 | code: string, |
| 9 | payload: Record<string, unknown>, |
| 10 | ): unknown { |
| 11 | try { |
| 12 | // Create the function code that will be executed |
| 13 | // 'use strict' ensures 'this' is undefined (not global object) |
| 14 | const funcCode = ` |
| 15 | 'use strict'; |
| 16 | return (${code})(payload); |
| 17 | `; |
| 18 | |
| 19 | // Create function with safe globals in scope |
| 20 | const func = new Function('payload', funcCode); |
| 21 | |
| 22 | // Execute the function |
| 23 | return func(payload); |
| 24 | } catch (error) { |
| 25 | throw new Error( |
| 26 | `Error executing JavaScript template: ${ |
| 27 | error instanceof Error ? error.message : String(error) |
| 28 | }`, |
| 29 | ); |
| 30 | } |
| 31 | } |