adapted from this
convert your string-based JavaScript logic into a Function that can be run with a distinct scope and parameters
⚠️ WARNING ⚠️
- read and understand the warnings from this article
- don’t blindly evaluate strings from untrusted sources
- don’t assume this constructed scope has perfect isolation, or limited access to the outer context
const setup_safer_eval = function (lst_idents) {
const runCodeWithCustomFunction = (obj) => {
return Function(...lst_idents.map(x=>x[0]), `"use strict";return (${obj});`.trim())(...lst_idents.map(x=>x[1]))
}
return runCodeWithCustomFunction
}
const do_safereval_strscript = function (obj_eval_defines, the_strscript) {
const lst_idents = Object.entries(obj_eval_defines).map(([k,v])=>[k,v]).toSorted((a,b)=>(a[0]-b[0]))
const the_eval_func = setup_safer_eval(lst_idents)
const the_eval_result = the_eval_func(`
(function(){
${the_strscript}
return
})()
`.trim())
return the_eval_result
}
/*
// example:
do_safereval_strscript({ msg: "hello, world!" }, 'console.info(msg)')
*/