SandboxJS
SandboxJS copied to clipboard
Reuse compiled code
After attempt use compiled code with different contexts I catching error
ReferenceError: plus is not defined
and my code
function plus(n,u){return n+u};function minus(n,u){return n-u};var a=plus(value,10);return minus(a,5);
.
In documentation I didn't see nothing about this restriction.
So its bug on not?
Please provide sample code on how you are using different contexts
for example
const body = 'function plus(n,u){return n+u};function minus(n,u){return n-u};var a=plus(value,10);return minus(a,5);'
const s = sandbox.compile(body, true);
console.log(s({value: 1}).run());
console.log(s({value: 2}).run());
I found that after first run context.tree
will be modified, that broke second call.
This workaround help me
const parsed = Sandbox.parse(body);
const context = sandbox.createContext(sandbox.context, parsed);
const tree = context.tree;
return (scope) => {
context.tree = structuredClone(tree);
return sandbox.executeTree(context, [scope]).result;
};
Just bumped into this problem. The code:
function printValue(value) {
console.log(value)
}
printValue(row)
Executed with: exec({ row }).run()
The above only works in the first execution, and in the others it throws printValue is not defined
.
This works normally, though:
const printValue = (value) => {
console.log(value)
}
printValue(row)
So SandboxJS doesn't work well with hoisted functions?