Skip to content

bonsai(options?)

Create one configured evaluator instance and reuse it anywhere you need expression execution, validation, or compiled rules.

ts
import { bonsai } from 'bonsai-js'

// Default instance
const expr = bonsai()

// Restricted instance for user-authored expressions
const safe = bonsai({
  timeout: 50,
  maxDepth: 50,
  maxArrayLength: 10000,
  allowedProperties: ['user', 'age', 'country', 'plan']
})

Choose the right API

If you need...Use...
Repeated evaluations with custom options, plugins, or cache reusebonsai()
A quick one-off evaluation with default behaviorevaluateExpression()
A reusable hot-path rule objectcompile()
Syntax checks and reference extraction before executionvalidate()
Async transforms or async functionsevaluate()
Lowest-overhead sync executionevaluateSync()

Options

OptionTypeDefaultDescription
timeoutnumber0Evaluation timeout in milliseconds. 0 disables timeout checks.
maxDepthnumber100Maximum traversal depth before a MAX_DEPTH security error is thrown.
maxArrayLengthnumber100000Maximum array literal or expanded spread size.
cacheSizenumber256Per-instance cache size for compiled expressions and parsed AST reuse.
allowedPropertiesstring[]-Allowlist checked against every accessed identifier and member name.
deniedPropertiesstring[]-Denylist checked against every accessed identifier and member name.

Blocked names like __proto__, constructor, and prototype are always denied. If you want to allow user.name, you must allow both user and name.

Common setups

ScenarioSuggested approach
App-owned expressions in trusted codeUse bonsai() with defaults and load only the stdlib/plugins you need.
User-authored rules in an admin UISet timeout, maxDepth, maxArrayLength, and an allowedProperties allowlist.
Large catalog of repeated expressionsReuse one instance and consider increasing cacheSize if you have many distinct expression strings.

Create the instance once at startup and reuse it

Recreating instances on every request throws away the cache and defeats most of the performance work.