farm-plugin-comptime-stdlib
v0.2.0
Published
Compile-time standard library for FarmFE — provides built-in functions (range, math, etc.) that expand statically at build time
Maintainers
Readme
farm-plugin-comptime-stdlib
Compile-time standard library for FarmFE — provides built-in functions that expand statically at build time.
Install
npm install farm-plugin-comptime-stdlibDependencies: This plugin uses core-ast-ts internally. Installed automatically.
Concept
Like C++ constexpr — this plugin provides utility functions that are expanded at compile time when all arguments are literals. Unlike lodash (a runtime library), these functions disappear from the output entirely when they can be statically evaluated.
When arguments are dynamic (not known at compile time), the call is kept and a minimal runtime polyfill is injected.
Usage
import comptimeStdlib from 'farm-plugin-comptime-stdlib'
export default {
plugins: [comptimeStdlib()],
}Provided Functions
Range and Repeat
const indices = $range(0, 5)
// → [0, 1, 2, 3, 4] (static array literal)
const steps = $range(0, 10, 2)
// → [0, 2, 4, 6, 8]
const zeros = $repeat(3, 0)
// → [0, 0, 0]Math (Constant Folding)
const area = $times(3.14, 4)
// → 12.56
const total = $add(100, 200)
// → 300
const diff = $sub(500, 200)
// → 300
const ratio = $div(22, 7)
// → 3.142857142857143
const rem = $mod(10, 3)
// → 1
const power = $pow(2, 10)
// → 1024
const lo = $min(1, 5, 3)
// → 1
const hi = $max(1, 5, 3)
// → 5
const val = $clamp(15, 0, 10)
// → 10String/Number Conversions
const h = $hex(255)
// → "0xff"
const o = $oct(8)
// → "0o10"
const b = $bin(5)
// → "0b101"
const code = $charCode('A')
// → 65
const ch = $fromCharCode(65)
// → "A"Dynamic Arguments (Runtime Fallback)
// n is a runtime variable — can't fold statically
const indices = $range(0, n)
// → kept as $range(0, n), runtime polyfill injected automaticallyThe plugin tracks which functions need runtime versions and injects only the necessary polyfills via a virtual module.
How It Works
- Scans code for
$-prefixed stdlib function calls - If all arguments are literals → evaluate and inline the result as a literal
- If any argument is dynamic → keep the call, inject runtime polyfill
- Runtime polyfill module is generated on-demand (
virtual:farm-plugin-comptime-stdlib/runtime)
License
MIT
