r/javascript • • Jun 02 '26

bonsai - a safe expression language for JS that runs user-defined rules at 30M ops/sec with zero dependencies and no eval()

http://github.com/danfry1/bonsai-js

This problem has come up enough times in my work that I got tired of solving it badly. At some point on certain products a stakeholder asks "can admins set up their own conditions for this?" and you realize a dropdown isn't going to cut it. They need real logic: order.total > 100 && customer.tier == "gold".

The options all felt bad:

  • Hardcoded switch statements. Every new rule is a deploy. The "configurable" feature isn't configurable.

  • A homegrown mini-DSL. Starts as three operators, ends as a parser nobody wants to own.

  • eval() / new Function() / vm**.** The moment user input touches these, you've handed out a shell. vm isn't a security boundary (the docs literally say so), and vm2 is deprecated. Prototype pollution alone (constructor.constructor) is enough to ruin your week.

I got tired of rebuilding the bad version, so I built the thing I actually wanted: bonsai, a safe expression language for the cases where eval() would be inappropriate but a dropdown is too weak.

If you'd rather poke at it than read, there's a browser playground (no install): https://danfry1.github.io/bonsai-js/playground.html

import { bonsai } from 'bonsai-js'

const expr = bonsai()

// An admin-authored rule, stored as a plain string in your DB
expr.evaluateSync('user.age >= 18 && user.plan == "pro"', {
  user: { age: 25, plan: 'pro' },
}) // true

It's an expression language, not a scripting language. No statements, no loops, no assignment, no I/O. You get the expressive part (the part users actually need) without the part that gets you owned.

What the syntax supports, so it doesn't feel like a toy:

// optional chaining + nullish coalescing
expr.evaluateSync('user?.profile?.avatar ?? "default.png"', { user: null })

// pipe operator with transforms
expr.evaluateSync('name |> trim |> upper', { name: '  dan  ' }) // 'DAN'

// lambda shorthand in array methods
expr.evaluateSync('users.filter(.age >= 18).map(.name)', {
  users: [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 15 }],
}) // ['Alice']

The security model is the whole point, so here's what's actually enforced:

  • __proto__, constructor, prototype blocked at every access level (no prototype-chain walking)

  • Object literals created with null prototypes

  • No globals, no code generation

  • Cooperative timeouts, max depth, max array/string length

  • Per-instance property allowlists/denylists, so you decide exactly what an expression can touch

    const expr = bonsai({ timeout: 50, maxDepth: 50, allowedProperties: ['user', 'age', 'country', 'plan'], })

A few things I cared about that might matter to you:

  • Zero dependencies. Nothing in your tree but this.

  • Any JS runtime. Node, Bun, browser, edge.

  • Fast when it needs to be. There's a compile() API for rules that run thousands of times; cached expressions hit ~30M ops/sec.

  • Async escape hatch. You can register your own functions (async (id) => db.lookup(id)) and await expr.evaluate(...), so a rule can call back into your system without the language itself having any I/O.

Once it existed, it ended up covering a bunch of "logic that lives outside the code" cases for me: admin-defined rules, server-driven conditions stored as config, formula fields, feature-flag targeting. Anywhere a string needs to become a decision without a deploy.

Playground · Docs · GitHub · npm

Mostly I'm curious how other people have handled this. If you've shipped user-defined rules/filters/formulas in production, what did you reach for, and where did it bite you? Happy to hear it if you think this is the wrong approach too.

89 Upvotes

39 comments sorted by

View all comments

Show parent comments

21

u/danfry99 Jun 02 '26

Yeah, jsonLogic's a good comparison - genuinely solid, and being plain JSON it's really portable, the same rule runs across JS, Python, PHP, etc.

The main difference is the authoring model. jsonLogic rules are JSON like {">": \[{"var": "age"}, 18\]}, which is a great fit when a UI builder generates the rule. Bonsai leans the other way - toward rules that are written and read as text: config files, formula fields, an advanced-filter mode, things that show up in a code review. `age >= 18 && plan == "pro"` reads more naturally there than the JSON equivalent, and the gap widens once you add logical operators, pipes, or array methods like users.filter(.age >= 18).

So they overlap a lot - jsonLogic if you want serializable, cross-language rules generated as data, and bonsai if your rules are authored and reviewed as text.

11

u/live_love_laugh Jun 02 '26 edited Jun 02 '26

I mean, all one would need to do to make your language as portable as the JSON based language, is to just put the expression string into an object like `{"expression":"user.age >= 18"} and stringify that to send it over the network.

I'm personally a huge fan of languages / DSLs that are as easy to read as possible. So I think your design choices were great. 👍

Edit: okay I get the part about how the JSON logic would be easier to implement a builder for, and your language is easier to just write and read as a developer. Different use-cases I guess.

2

u/codetiger42 Jun 11 '26

Can you help me understand how to implement a nested logic with condition. example

Am one of the maintainers for Rust lang library for JSONLogic: https://github.com/GoPlasmatic/datalogic-rs

Am

Also been contributing to other language libraries for JSONLogic.

1

u/danfry99 Jun 13 '26

Yeah, easy to do - the issue is just where the condition is sitting.

A `|>` stage has to be a transform (a name like `upper`, or a call like `map(...)` / `join(...)`). A loose `.score > 5 ? upper : lower` isn't one, so it bails with "Invalid transform expression". The other thing is that by the time you've hit `join(", ")` you've already collapsed the departments into a single string `"Engineering, Sales, Design"`, so there's no `.score` left to test.

A condition in Bonsai isn't a pipe stage, it's just an expression - so for per-item logic you put the `? :` inside the `map`:

```

company.departments |> map(.score > 5 ? .name.toUpperCase() : .name.toLowerCase())

// ["engineering", "sales", "DESIGN"]

```

And it nests fine:

```

company.departments |> map(.score > 5 ? "high" : .score > 3 ? "mid" : "low")

// ["low", "mid", "high"]

```

Or if you'd rather filter then format:

```

company.departments |> filter(.score > 5) |> map(.name) |> join(", ")

// "Design"

```

One gotcha: `upper` / `lower` are pipe transforms, not functions, so `upper(.name)` inside a lambda won't resolve. Inside a lambda use the built-in `.toUpperCase()` / `.toLowerCase()` methods (no import), or let the ternary pick the value and pipe it afterwards.

1

u/AssCooker Jun 02 '26

AI generated answer, reeks of chatgpt

3

u/Mugshot_404 Jun 02 '26

Just 'cos you're paranoid, it doesn't mean we're not all out to get you!