Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

feat(wasm): use JsValue (JS objects) at the boundary instead of JSON strings

public

feat(wasm): use JsValue (JS objects) at the boundary instead of JSON strings

evaluate/evaluate_strict now take the context as a native JS object and
return a native JS value, bridging JsValue <-> serde_json::Value with
serde-wasm-bindgen and reusing the existing recursive mappers. Errors are
thrown as JS exceptions (idiomatic wasm-bindgen) rather than returned as
{error} objects. feel-core stays free of JSON/wasm knowledge.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changeset1010cad66ea7f8843a0227a4e6c4dca589502730
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents541814fd5e34
Children
Pushlog
by timo via ssh

modified Cargo.lock +13 −0

@@ -520,6 +520,8 @@
520520
 version = "0.1.0"
521521
 dependencies = [
522522
  "feel-core",
523
+ "serde",
524
+ "serde-wasm-bindgen",
523525
  "serde_json",
524526
  "wasm-bindgen",
525527
 ]
@@ -1502,6 +1504,17 @@
15021504
 dependencies = [
15031505
  "serde_core",
15041506
  "serde_derive",
1507
+]
1508
+
1509
+[[package]]
1510
+name = "serde-wasm-bindgen"
1511
+version = "0.6.5"
1512
+source = "registry+https://github.com/rust-lang/crates.io-index"
1513
+checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b"
1514
+dependencies = [
1515
+ "js-sys",
1516
+ "serde",
1517
+ "wasm-bindgen",
15051518
 ]
15061519
 
15071520
 [[package]]

modified README.md +15 −1

@@ -9,7 +9,7 @@
99
 ```text
1010
 crates/feel-core   pure engine (lalrpop grammar + AST + evaluator); no target deps
1111
 crates/feel-pg     pgrx wrapper:  feel_eval(text, jsonb) RETURNS jsonb
12
-crates/feel-wasm   wasm-bindgen wrapper:  evaluate(expr, context_json) -> JSON string
12
+crates/feel-wasm   wasm-bindgen wrapper:  evaluate(expr, context) -> JS value
1313
 tools/ingest_tck.py  DMN-TCK literal-expression -> feel-core fixture (with deviations)
1414
 ```
1515
 
@@ -166,6 +166,20 @@
166166
 node crates/feel-wasm/smoke.mjs        # one line per case, then "smoke test passed"
167167
 ```
168168
 
169
+The context is a native JS object and the result is a native JS value (no JSON
170
+strings). Parse/eval errors throw; `evaluate_strict` also throws on a null that
171
+arose from a type/domain error.
172
+
173
+```js
174
+import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js";
175
+
176
+evaluate("1 + 1", {});                         // => 2
177
+evaluate("person.age", { person: { age: 42 } }); // => 42
178
+evaluate("{a: 1, b: a + 1}", {});              // => { a: 1, b: 2 }
179
+evaluate("1 + true", {});                      // => null  (lenient)
180
+evaluate_strict("1 + true", {});               // throws   (strict)
181
+```
182
+
169183
 Compile-only check without wasm-pack:
170184
 
171185
 ```sh

modified crates/feel-wasm/Cargo.toml +2 −0

@@ -10,5 +10,7 @@
1010
 
1111
 [dependencies]
1212
 wasm-bindgen = "0.2"
13
+serde-wasm-bindgen = "0.6"
14
+serde = { version = "1", features = ["derive"] }
1315
 serde_json.workspace = true
1416
 feel-core = { path = "../feel-core" }

modified crates/feel-wasm/smoke.mjs +32 −21

@@ -16,42 +16,53 @@
1616
 
1717
 import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js";
1818
 
19
-// [expression, context-json, expected-json]. These mirror the feel-core and
20
-// feel-pg tests, demonstrating "same core, same result" across all three
21
-// targets.
19
+// [expression, context-object, expected-value]. The context is a native JS
20
+// object and the result is a native JS value (no JSON strings). These mirror the
21
+// feel-core and feel-pg tests, demonstrating "same core, same result" across all
22
+// three targets.
2223
 const cases = [
23
-  ["1 + 1", "{}", "2"],
24
-  ["5 in [1..10]", "{}", "true"],
25
-  ["if 1 < 2 then 10 else 20", "{}", "10"],
26
-  ["for i in [1,2,3] return i + 1", "{}", "[2,3,4]"],
27
-  ['"apple" < "banana"', "{}", "true"],
28
-  // Context literal -> JSON object, and path access into a nested input context.
29
-  ["{a: 1, b: a + 1}", "{}", '{"a":1,"b":2}'],
30
-  ["person.age", '{"person": {"age": 42}}', "42"],
24
+  ["1 + 1", {}, 2],
25
+  ["5 in [1..10]", {}, true],
26
+  ["if 1 < 2 then 10 else 20", {}, 10],
27
+  ["for i in [1,2,3] return i + 1", {}, [2, 3, 4]],
28
+  ['"apple" < "banana"', {}, true],
29
+  // Context literal -> JS object, and path access into a nested input context.
30
+  ["{a: 1, b: a + 1}", {}, { a: 1, b: 2 }],
31
+  ["person.age", { person: { age: 42 } }, 42],
3132
 ];
33
+
34
+const eq = (a, b) => JSON.stringify(a) === JSON.stringify(b);
3235
 
3336
 let ok = true;
3437
 for (const [expr, ctx, expected] of cases) {
3538
   const got = evaluate(expr, ctx);
36
-  console.log(`${expr} => ${got}`);
37
-  if (got !== expected) {
39
+  console.log(`${expr} => ${JSON.stringify(got)}`);
40
+  if (!eq(got, expected)) {
3841
     console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
3942
     ok = false;
4043
   }
4144
 }
4245
 
4346
 // Boundary policy (ADR-14): a type error is a lenient `null`, but `evaluate_strict`
44
-// surfaces it as an {"error": ...} object instead of letting it pass silently.
47
+// surfaces it as a thrown exception instead of letting it pass silently as `null`.
48
+const threw = (fn) => {
49
+  try {
50
+    fn();
51
+    return false;
52
+  } catch {
53
+    return true;
54
+  }
55
+};
56
+
4557
 const strictCases = [
46
-  ["1 + true", "{}", "null", true], // lenient: null; strict: error
47
-  ["null", "{}", "null", false], // a genuine value-null is fine even in strict
58
+  ["1 + true", {}, null, true], // lenient: null; strict: throws
59
+  ["null", {}, null, false], // a genuine value-null is fine even in strict
4860
 ];
49
-for (const [expr, ctx, expectedLenient, expectStrictError] of strictCases) {
61
+for (const [expr, ctx, expectedLenient, expectStrictThrow] of strictCases) {
5062
   const lenient = evaluate(expr, ctx);
51
-  const strict = evaluate_strict(expr, ctx);
52
-  console.log(`${expr} => lenient ${lenient} | strict ${strict}`);
53
-  const strictIsError = strict.includes('"error"');
54
-  if (lenient !== expectedLenient || strictIsError !== expectStrictError) {
63
+  const strictThrew = threw(() => evaluate_strict(expr, ctx));
64
+  console.log(`${expr} => lenient ${JSON.stringify(lenient)} | strict throws: ${strictThrew}`);
65
+  if (!eq(lenient, expectedLenient) || strictThrew !== expectStrictThrow) {
5566
     console.error(`FAIL: ${expr} lenient/strict mismatch`);
5667
     ok = false;
5768
   }

modified crates/feel-wasm/src/lib.rs +35 −26

@@ -1,48 +1,57 @@
11
 //! WASM wrapper for `feel-core`, built with wasm-bindgen.
22
 //!
3
-//! Exposes `evaluate(expr, context_json) -> String`, returning the result as a
4
-//! JSON string. The JSON boundary mapping lives here (not in `feel-core`), per
5
-//! the project's boundary-mapping decision.
3
+//! Exposes `evaluate(expr, context) -> JsValue`, taking the context as a native
4
+//! JS object and returning the result as a native JS value. The boundary mapping
5
+//! lives here (not in `feel-core`), per the project's boundary-mapping decision:
6
+//! `JsValue` is bridged to `serde_json::Value` with `serde-wasm-bindgen`, then to
7
+//! `feel-core`'s [`Value`] by the existing recursive helpers.
68
 
79
 use feel_core::{evaluate as core_evaluate, Context, Value};
10
+use serde::Serialize;
811
 use wasm_bindgen::prelude::*;
912
 
1013
 /// Evaluate a FEEL expression (lenient boundary policy).
1114
 ///
12
-/// `context_json` is a JSON object string (e.g. `"{}"`). The result is returned
13
-/// as a JSON string. On error, a JSON object `{"error": "..."}` is returned so
14
-/// the JS side never has to deal with thrown exceptions for plain eval errors.
15
-/// A null arising from a type/domain error is emitted as plain JSON `null` (the
16
-/// spec-shaped result); see `evaluate_strict` to surface such errors instead.
15
+/// `context` is a native JS object (e.g. `{}`); `undefined`/`null` is treated as
16
+/// an empty context. The result is returned as a native JS value. Parse and eval
17
+/// errors are thrown as JS exceptions. A null arising from a type/domain error is
18
+/// returned as plain `null` (the spec-shaped result); see `evaluate_strict` to
19
+/// surface such errors as a thrown exception instead.
1720
 #[wasm_bindgen]
18
-pub fn evaluate(expr: &str, context_json: &str) -> String {
19
-    match eval_value(expr, context_json) {
20
-        Ok(value) => value_to_json(&value).to_string(),
21
-        Err(message) => serde_json::json!({ "error": message }).to_string(),
22
-    }
21
+pub fn evaluate(expr: &str, context: JsValue) -> Result<JsValue, JsError> {
22
+    let value = eval_value(expr, context).map_err(|m| JsError::new(&m))?;
23
+    to_js(&value_to_json(&value))
2324
 }
2425
 
2526
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
26
-/// contains, a null that arose from a type/domain error, return
27
-/// `{"error": "..."}` instead of letting the error pass silently as `null`
28
-/// (ADR-14). A plain (value) null is still returned as `null`.
27
+/// contains, a null that arose from a type/domain error, throw instead of letting
28
+/// the error pass silently as `null` (ADR-14). A plain (value) null is still
29
+/// returned as `null`.
2930
 #[wasm_bindgen]
30
-pub fn evaluate_strict(expr: &str, context_json: &str) -> String {
31
-    match eval_value(expr, context_json) {
32
-        Ok(value) if value.contains_error() => serde_json::json!({
33
-            "error": "evaluation produced a null from a type or domain error"
34
-        })
35
-        .to_string(),
36
-        Ok(value) => value_to_json(&value).to_string(),
37
-        Err(message) => serde_json::json!({ "error": message }).to_string(),
31
+pub fn evaluate_strict(expr: &str, context: JsValue) -> Result<JsValue, JsError> {
32
+    let value = eval_value(expr, context).map_err(|m| JsError::new(&m))?;
33
+    if value.contains_error() {
34
+        return Err(JsError::new(
35
+            "evaluation produced a null from a type or domain error",
36
+        ));
3837
     }
38
+    to_js(&value_to_json(&value))
3939
 }
4040
 
41
-fn eval_value(expr: &str, context_json: &str) -> Result<Value, String> {
41
+fn eval_value(expr: &str, context: JsValue) -> Result<Value, String> {
4242
     let parsed: serde_json::Value =
43
-        serde_json::from_str(context_json).map_err(|e| format!("invalid context JSON: {e}"))?;
43
+        serde_wasm_bindgen::from_value(context).map_err(|e| format!("invalid context: {e}"))?;
4444
     let ctx = context_from_json(&parsed)?;
4545
     core_evaluate(expr, &ctx).map_err(|e| e.to_string())
46
+}
47
+
48
+/// Serialize a JSON value to a native `JsValue`. The `json_compatible` serializer
49
+/// maps objects to plain JS objects (not `Map`); integral numbers stay JS numbers.
50
+fn to_js(value: &serde_json::Value) -> Result<JsValue, JsError> {
51
+    let serializer = serde_wasm_bindgen::Serializer::json_compatible();
52
+    value
53
+        .serialize(&serializer)
54
+        .map_err(|e| JsError::new(&e.to_string()))
4655
 }
4756
 
4857
 /// Map a `feel-core` [`Value`] to a JSON value for the string boundary.