Tamedevil is a JavaScript/TypeScript library designed to mitigate the inherent dangers and complexities associated with `eval` and `new Function` for dynamic code generation. It achieves this by leveraging tagged template literals, ensuring that all string segments interpolated into the generated code are either trusted author-written code or properly escaped data. This approach significantly reduces the risk of code injection vulnerabilities. The library also addresses garbage collection concerns by ensuring generated functions operate without capturing ephemeral closure data, requiring all parameters to be passed explicitly. Currently at version `0.1.0` and actively developed as part of the Graphile Crystal ecosystem, it aims to provide a safer, more performant method for building dynamic functions where traditional `eval` is typically avoided.
npm install tamedevilVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to safely build a dynamic JavaScript function using `tamedevil`'s tagged template literal and helpers like `te.ref` (for injecting variables) and `te.lit` (for embedding string literals safely), then executes it.
Always use `te.lit(myString)` for any literal string content that should be treated as data within the generated code, and `te.ref(variableName)` for injecting runtime variables or functions into the evaluated context to prevent accidental code injection.
Ensure all necessary external data, functions, or objects are passed into the `te` template literal using `te.ref(myVariable)` to make them accessible within the generated function's scope.
Implement robust and comprehensive testing for any dynamically generated code paths. Avoid overly complex or deeply nested dynamic logic if debugging clarity is a primary concern for that specific code segment.
Upgrade your Node.js environment to version 22 or newer to ensure compatibility and proper functioning of `tamedevil`.
To make `someVariable` available inside the generated function, pass it using `te.ref`: `const someVariable = 'value'; const code = te`return ${te.ref(someVariable)};``If the content is meant to be a literal string within the generated code (e.g., a search query, a message), use `te.lit()` to ensure it's properly escaped: `const userQuery = 'some user input; delete *'; const code = te`const q = ${te.lit(userQuery)}; // Now safe`No dependency data recorded yet.