Registry / serialization / generate-function

generate-function

JSON →
library2.3.1jsnpmunverified

generate-function is a specialized Node.js utility designed to assist in creating dynamic JavaScript functions programmatically. Its primary use case is in scenarios demanding extreme performance optimization, such as constructing schema validators or parsers where static code generation can significantly reduce runtime overhead. The library is currently at version 2.3.1. It maintains a stable, low-cadence release schedule, as it addresses a specific, mature problem domain. A key differentiator is its focus on robust, safe code generation primitives like `gen.sym()` for unique identifiers and `gen.property()` for safe property access, which abstract away common pitfalls of manual string concatenation for code. It provides methods to append source code incrementally and to close over external variables safely by passing a scope object to `toFunction()`.

npm install generate-function
INSTALL
IMPORT
SIG · GENERATE-FUNCTION
G
generate-function
serializationjavascriptv2.3.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

genfun
✓ const genfun = require('generate-function')
✗ import genfun from 'generate-function'
The library primarily uses CommonJS `require` syntax. Direct ES Module `import` is not officially supported without a transpiler or wrapper.
d
✓ const { d } = require('generate-function').formats
✗ import { d } from 'generate-function/formats'
The `d` helper for safe data interpolation is accessed via the `formats` property of the main export.
toFunction
✓ gen.toFunction(scope)
✗ gen.toFunction() // when closing over variables
When your generated function needs to access variables from its creation scope, they must be explicitly passed as an object to `toFunction(scope)`.

This quickstart demonstrates creating dynamic functions, interpolating values safely, generating unique variable names, and closing over external variables using `toFunction(scope)`.

const genfun = require('generate-function'); function createDynamicAdder(baseValue) { const gen = genfun(); const { d } = genfun.formats; // For safe data interpolation // Generate a unique variable name for internal use const tempVar = gen.sym('result'); gen(` function (input) { if (typeof input !== 'number') { throw new Error('Input must be a number'); } const ${tempVar} = input + ${d(baseValue)}; return ${tempVar}; } `); // Optional: pass variables to close over, e.g., for complex operations // For this simple example, no external scope is strictly needed. const dynamicAddFunc = gen.toFunction(); console.log('Generated function source:\n' + dynamicAddFunc.toString()); return dynamicAddFunc; } const add5 = createDynamicAdder(5); console.log('10 + 5 =', add5(10)); console.log('20 + 5 =', add5(20)); function createScopedMultiplier(factor) { const gen = genfun(); const { d } = genfun.formats; // Define a helper function that the generated code will call const multiplyHelper = (a, b) => a * b; gen(` function (value) { if (typeof value !== 'number') { throw new Error('Value must be a number'); } // Call the 'multiplyHelper' from the scope passed to toFunction return multiplyHelper(${d(factor)}, value); } `); // Pass multiplyHelper into the scope of the generated function const scopedMultiplyFunc = gen.toFunction({ multiplyHelper }); console.log('\nGenerated scoped function source:\n' + scopedMultiplyFunc.toString()); return scopedMultiplyFunc; } const multiplyBy3 = createScopedMultiplier(3); console.log('4 * 3 =', multiplyBy3(4));
Debug
Known issues
gotchaGenerating code dynamically is complex and should primarily be used for performance-critical scenarios where static code generation significantly improves execution speed (e.g., schema validators, parsers). Misuse can lead to difficult-to-debug issues and potential security vulnerabilities if input is not carefully sanitized.
fix
Thoroughly test generated functions, validate all inputs, and use `gen.sym()` and `gen.property()` for safe identifier and property access within generated code.
affects: >=1.0.0
gotchaSecurity vulnerability due to improper input sanitization when concatenating user-provided strings directly into the generated function's source can lead to arbitrary code execution (injection attacks).
fix
Always use `gen.formats.d()` for data interpolation to ensure values are correctly serialized and escaped. Avoid direct string concatenation of untrusted input into `gen()` calls. Only pass trusted, pre-validated values.
affects: >=1.0.0
gotchaWhen closing over variables, ensure all necessary external references are explicitly passed in the scope object to `toFunction(scope)`. Variables not in the scope or not globally accessible will result in `ReferenceError`s at runtime.
fix
Review the generated function's source (`gen.toString()`) to identify missing variables. Pass all required external variables as properties of an object to `gen.toFunction({ var1, var2 })`.
affects: >=1.0.0
Errors
Common errors & fixes
ReferenceError: someVariable is not defined
The generated function attempts to access a variable (e.g., `someVariable`) that was not defined within its own generated scope and was not passed in the `scope` object to `gen.toFunction()`.
fix
Ensure `someVariable` is either defined directly in the generated source or is included in the object passed to `gen.toFunction({ someVariable })`.
SyntaxError: Unexpected token '...' (or similar parsing error)
The string passed to `gen()` contains invalid JavaScript syntax, often due to incorrect concatenation, unescaped characters, or malformed template literals.
fix
Carefully review the source string passed to `gen()` and `gen.formats.d()` calls. Use `gen.toString()` to inspect the complete generated function source code and identify the syntax error.
TypeError: genfun is not a function (when using `import genfun from 'generate-function'`)
The `generate-function` module primarily exports a CommonJS module with `module.exports = function (...)`. When used with ES Modules, `import genfun from 'generate-function'` might attempt a default import where there isn't one, or it might incorrectly interpret the export.
fix
Use the CommonJS `require` syntax: `const genfun = require('generate-function');` in Node.js environments. If using ES Modules, you might need `import * as genfun from 'generate-function'` or configure your build tool to handle CJS interop correctly.
Upgrade
Version history
2.3.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
6
Resources
generate-function — npm install generate-function · libregistry