Public repository: timo / feel

Reader

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

feel / crates / feel-wasm / smoke.mjs · 9.3 KB · at 90f493059be5 · raw

1
// Smoke test for the WASM build.
2
//
3
// Build first:
4
//   wasm-pack build crates/feel-wasm --target nodejs
5
// Then run:
6
//   node crates/feel-wasm/smoke.mjs
7
//
8
// Expected output (one line per case):
9
//   1 + 1 => 2
10
//   5 in [1..10] => true
11
//   if 1 < 2 then 10 else 20 => 10
12
//   for i in [1,2,3] return i + 1 => [2,3,4]
13
//   "apple" < "banana" => true
14
//   {a: 1, b: a + 1} => {"a":1,"b":2}
15
//   person.age (ctx {"person":{"age":42}}) => 42
16
17
import { evaluate, evaluate_strict, compile } from "./pkg/feel_wasm.js";
18
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.
23
const cases = [
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],
32
  // Regex builtins run on the host JS RegExp engine (ADR-16).
33
  ['matches("foobar", "^fo*b")', {}, true],
34
  ['replace("banana", "a", "o")', {}, "bonono"],
35
  ['split("a;b;c;;", ";")', {}, ["a", "b", "c", "", ""]],
36
];
37
38
const eq = (a, b) => JSON.stringify(a) === JSON.stringify(b);
39
40
let ok = true;
41
for (const [expr, ctx, expected] of cases) {
42
  const got = evaluate(expr, ctx);
43
  console.log(`${expr} => ${JSON.stringify(got)}`);
44
  if (!eq(got, expected)) {
45
    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
46
    ok = false;
47
  }
48
}
49
50
// Temporal (ADR-18): date-family results come back as native JS `Date` objects,
51
// durations as ISO-8601 strings, and `Date` objects are accepted in the context.
52
const dateResult = evaluate("date(2017, 8, 3)", {});
53
console.log(`date(2017, 8, 3) => ${dateResult instanceof Date ? dateResult.toISOString() : JSON.stringify(dateResult)}`);
54
if (!(dateResult instanceof Date) || !dateResult.toISOString().startsWith("2017-08-03")) {
55
  console.error("FAIL: date(...) should be a Date object");
56
  ok = false;
57
}
58
const durResult = evaluate('duration("P1Y2M")', {});
59
console.log(`duration("P1Y2M") => ${JSON.stringify(durResult)}`);
60
if (durResult !== "P1Y2M") {
61
  console.error("FAIL: duration should be an ISO-8601 string");
62
  ok = false;
63
}
64
const yearFromDate = evaluate("d.year", { d: new Date("2017-08-03T00:00:00Z") });
65
console.log(`d.year (ctx { d: Date }) => ${JSON.stringify(yearFromDate)}`);
66
if (yearFromDate !== 2017) {
67
  console.error("FAIL: a Date object should be accepted in the context");
68
  ok = false;
69
}
70
71
// Lazy host-object access (ADR-21): an object in the context is wrapped and its
72
// members resolve on demand via `Reflect.get`, which *fires JS accessor getters*.
73
const getterObj = {
74
  get name() {
75
    return "Ada";
76
  },
77
};
78
const getterResult = evaluate("o.name", { o: getterObj });
79
console.log(`o.name (getter) => ${JSON.stringify(getterResult)}`);
80
if (getterResult !== "Ada") {
81
  console.error("FAIL: a JS getter should fire on path access");
82
  ok = false;
83
}
84
// Lazy navigation through nested getters (the ORM lazy-load shape).
85
const orderObj = {
86
  get customer() {
87
    return {
88
      get address() {
89
        return { city: "Paris" };
90
      },
91
    };
92
  },
93
};
94
const nested = evaluate("o.customer.address.city", { o: orderObj });
95
console.log(`o.customer.address.city => ${JSON.stringify(nested)}`);
96
if (nested !== "Paris") {
97
  console.error("FAIL: nested getter navigation");
98
  ok = false;
99
}
100
// Output pass-through: a host object that reaches the result is the *same* object.
101
const origObj = { city: "Berlin" };
102
const passed = evaluate("o", { o: origObj });
103
console.log(`o passthrough identity => ${passed === origObj}`);
104
if (passed !== origObj) {
105
  console.error("FAIL: a Foreign result should pass the original object through");
106
  ok = false;
107
}
108
// A cyclic object needs no guard in lazy mode: a finite path terminates.
109
const cyc = { a: 1 };
110
cyc.self = cyc;
111
const cycResult = evaluate("x.self.self.a", { x: cyc });
112
console.log(`x.self.self.a (cyclic) => ${JSON.stringify(cycResult)}`);
113
if (cycResult !== 1) {
114
  console.error("FAIL: a finite path over a cyclic object should terminate");
115
  ok = false;
116
}
117
118
// Descendant `e ... name` (DMN 10.3.2.7): recursively collect every value bound to
119
// `name` in `e` and all nested contexts. Unlike the lazy `.`, it is an *unbounded*
120
// traversal, so a cyclic object would loop forever without the WeakMap-based
121
// identity (JS exposes no cheap object address, so object identity is derived via a
122
// WeakMap<object, number>).
123
const descendantCases = [
124
  ["{a: {b: {b: 1}}} ... b", {}, [{ b: 1 }, 1]],
125
  ["[{x:1},{x:2}] ... x", {}, [1, 2]],
126
  ["{a:1} ... z", {}, []],
127
  ["o ... name", { o: { customer: { name: "Ada" } } }, ["Ada"]],
128
];
129
for (const [expr, ctx, expected] of descendantCases) {
130
  const got = evaluate(expr, ctx);
131
  console.log(`${expr} => ${JSON.stringify(got)}`);
132
  if (!eq(got, expected)) {
133
    console.error(`FAIL: ${expr} expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
134
    ok = false;
135
  }
136
}
137
// The descendant traversal over a *cyclic* object must terminate: the back-edge into
138
// the same object (same WeakMap id) is cut after the first re-entry. `cyc2.next`
139
// points back to `cyc2`, so `value` is collected twice before the cycle is broken.
140
const cyc2 = { value: 42 };
141
cyc2.next = cyc2;
142
const cycDesc = evaluate("c ... value", { c: cyc2 });
143
console.log(`c ... value (cyclic) => ${JSON.stringify(cycDesc)}`);
144
if (!eq(cycDesc, [42, 42])) {
145
  console.error(`FAIL: descendant over a cyclic object should terminate with [42,42], got ${JSON.stringify(cycDesc)}`);
146
  ok = false;
147
}
148
149
// Boundary policy (ADR-14): a type error is a lenient `null`, but `evaluate_strict`
150
// surfaces it as a thrown exception instead of letting it pass silently as `null`.
151
const threw = (fn) => {
152
  try {
153
    fn();
154
    return false;
155
  } catch {
156
    return true;
157
  }
158
};
159
160
const strictCases = [
161
  ["1 + true", {}, null, true], // lenient: null; strict: throws
162
  ["null", {}, null, false], // a genuine value-null is fine even in strict
163
];
164
for (const [expr, ctx, expectedLenient, expectStrictThrow] of strictCases) {
165
  const lenient = evaluate(expr, ctx);
166
  const strictThrew = threw(() => evaluate_strict(expr, ctx));
167
  console.log(`${expr} => lenient ${JSON.stringify(lenient)} | strict throws: ${strictThrew}`);
168
  if (!eq(lenient, expectedLenient) || strictThrew !== expectStrictThrow) {
169
    console.error(`FAIL: ${expr} lenient/strict mismatch`);
170
    ok = false;
171
  }
172
}
173
// Compiled path: parse once, evaluate against many contexts (the parse-once /
174
// evaluate-many API). `free()` is the optional explicit-cleanup escape hatch;
175
// otherwise wasm-bindgen's FinalizationRegistry reclaims it on GC.
176
const prog = compile("a + 1");
177
const compiledCases = [
178
  [{ a: 1 }, 2],
179
  [{ a: 41 }, 42],
180
];
181
for (const [ctx, expected] of compiledCases) {
182
  const got = prog.evaluate(ctx);
183
  console.log(`compiled "a + 1" (ctx ${JSON.stringify(ctx)}) => ${JSON.stringify(got)}`);
184
  if (!eq(got, expected)) {
185
    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
186
    ok = false;
187
  }
188
}
189
prog.free();
190
191
// Host callables (ADR-23): a JS function in the context is a FEEL function the
192
// expression can invoke. Positional FEEL args -> positional JS args; named FEEL
193
// args -> a single trailing options object (JS has no keyword arguments).
194
const hostFnCases = [
195
  // positional
196
  ["f(2, 3)", { f: (a, b) => a + b }, 5],
197
  // named -> options object {a, b}
198
  ["f(b: 3, a: 2)", { f: (o) => o.a - o.b }, -1],
199
  // mixed positional + named -> (positional…, {named})
200
  ["f(2, b: 3)", { f: (a, o) => a - o.b }, -1],
201
  // a host default applies (feel-core does no arity check for host callables)
202
  ["f(2)", { f: (a, b = 10) => a + b }, 12],
203
  // a host object argument round-trips by identity into the function
204
  ["grab(o)", { grab: (o) => o.total, o: { total: 99 } }, 99],
205
  // a function-valued binding shadows a built-in of the same name
206
  ["count(2, 3)", { count: (a, b) => a * b }, 6],
207
];
208
for (const [expr, ctx, expected] of hostFnCases) {
209
  const got = evaluate(expr, ctx);
210
  console.log(`${expr} (host fn) => ${JSON.stringify(got)}`);
211
  if (!eq(got, expected)) {
212
    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
213
    ok = false;
214
  }
215
}
216
217
// The ambient function registry (third argument): functions live apart from data.
218
const regResult = evaluate("add(x, 3)", { x: 2 }, { add: (a, b) => a + b });
219
console.log(`add(x, 3) (registry) => ${JSON.stringify(regResult)}`);
220
if (regResult !== 5) {
221
  console.error("FAIL: ambient function registry");
222
  ok = false;
223
}
224
225
// A thrown exception inside a host callable is a lenient null (error-null).
226
const threwResult = evaluate("boom(1)", {
227
  boom: () => {
228
    throw new Error("nope");
229
  },
230
});
231
console.log(`boom(1) (throws) => ${JSON.stringify(threwResult)}`);
232
if (threwResult !== null) {
233
  console.error("FAIL: a host exception should be a lenient null");
234
  ok = false;
235
}
236
237
// A host callable that reaches the result passes back as the same function.
238
const idFn = (a) => a;
239
const idResult = evaluate("f", { f: idFn });
240
console.log(`f passthrough identity => ${idResult === idFn}`);
241
if (idResult !== idFn) {
242
  console.error("FAIL: a returned host function should pass through by identity");
243
  ok = false;
244
}
245
246
if (!ok) process.exit(1);
247
console.error("smoke test passed");