Public repository: timo / feel

Reader

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

feel / crates / feel-wasm / src / lib.rs · 24.4 KB · at 93b43c1c833b · raw

Outline: 51 definitions
1
//! WASM wrapper for `feel-core`, built with wasm-bindgen.
2
//!
3
//! Exposes the one-shot `evaluate(expr, context) -> JsValue` plus a
4
//! `compile(expr) -> CompiledExpr` class for parse-once / evaluate-many: parsing
5
//! is the per-call cost that does not depend on the context, so callers that
6
//! evaluate the same expression against many contexts should compile once and
7
//! reuse. The context is a native JS object and the result a native JS value. The
8
//! boundary mapping lives here (not in `feel-core`), per the project's
9
//! boundary-mapping decision.
10
//!
11
//! Context input is **lazy** (ADR-21): an object is wrapped behind feel-core's
12
//! `ForeignObject` seam, so `order.customer.address` resolves one segment at a time
13
//! via `Reflect.get` (which fires JS accessor getters) instead of the whole graph
14
//! being walked up front. Scalars and `Date` values are converted eagerly; a
15
//! `Foreign` that reaches the result passes the original `JsValue` back untouched.
16
//! A finite expression can only navigate a finite path, so cyclic objects need no
17
//! cycle guard (the previous `js_to_value` guard is gone).
18
19
use std::cell::RefCell;
20
use std::collections::BTreeMap;
21
use std::sync::Arc;
22
23
use feel_core::{
24
    compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
25
    CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
26
    FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value,
27
};
28
use serde::Serialize;
29
use wasm_bindgen::prelude::*;
30
use wasm_bindgen::JsCast;
31
32
/// Evaluate a FEEL expression (lenient boundary policy).
33
///
34
/// `context` is a native JS object (e.g. `{}`); `undefined`/`null` is treated as
35
/// an empty context. The result is returned as a native JS value. Parse and eval
36
/// errors are thrown as JS exceptions. A null arising from a type/domain error is
37
/// returned as plain `null` (the spec-shaped result); see `evaluate_strict` to
38
/// surface such errors as a thrown exception instead.
39
///
40
/// The context **is** the scope for §10.3.1.6 name resolution (ADR-47): a name
41
/// like `a-b` resolves to the context binding `a-b` when one exists, and to
42
/// subtraction otherwise.
43
#[wasm_bindgen]
44
pub fn evaluate(expr: &str, context: JsValue, functions: JsValue) -> Result<JsValue, JsError> {
45
    // Build the context and registry first: together they are the parse-time
46
    // name oracle (ADR-47).
47
    let ctx = context_from_js(&context)?;
48
    let registry = JsFunctionRegistry { funcs: functions };
49
    let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
50
    run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, &registry, false)
51
}
52
53
/// Evaluate a FEEL expression (strict boundary policy): if the result is, or
54
/// contains, a null that arose from a type/domain error, throw instead of letting
55
/// the error pass silently as `null` (ADR-14). A plain (value) null is still
56
/// returned as `null`. Scope-dependent names resolve as in [`evaluate`].
57
#[wasm_bindgen]
58
pub fn evaluate_strict(
59
    expr: &str,
60
    context: JsValue,
61
    functions: JsValue,
62
) -> Result<JsValue, JsError> {
63
    let ctx = context_from_js(&context)?;
64
    let registry = JsFunctionRegistry { funcs: functions };
65
    let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
66
    run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, &registry, true)
67
}
68
69
/// A parsed FEEL expression, reusable across many evaluations.
70
///
71
/// Build one with [`compile`], then call [`CompiledExpr::evaluate`] repeatedly —
72
/// parsing happens once, each call only maps the context across the boundary.
73
/// wasm-bindgen exposes a `free()` method and registers instances with a
74
/// `FinalizationRegistry`, so the WASM-side memory is reclaimed on GC; calling
75
/// `free()` explicitly is an optional escape hatch, not required.
76
///
77
/// Parsed **probe-free** (ADR-47): special-character name runs (`a-b`) are
78
/// arithmetic on this path, whatever the later contexts bind — a compiled
79
/// program must not pin one scope. Use the one-shot [`evaluate`] for
80
/// scope-dependent name resolution (§10.3.1.6).
81
#[wasm_bindgen]
82
pub struct CompiledExpr {
83
    inner: CoreCompiled,
84
}
85
86
/// Parse a FEEL expression into a reusable [`CompiledExpr`] (throws on a parse
87
/// error). Does not evaluate. Probe-free — see [`CompiledExpr`].
88
#[wasm_bindgen]
89
pub fn compile(expr: &str) -> Result<CompiledExpr, JsError> {
90
    Ok(CompiledExpr {
91
        inner: compile_core(expr)?,
92
    })
93
}
94
95
#[wasm_bindgen]
96
impl CompiledExpr {
97
    /// Evaluate this compiled expression against a context (lenient policy).
98
    pub fn evaluate(&self, context: JsValue, functions: JsValue) -> Result<JsValue, JsError> {
99
        run(&self.inner, context, functions, false)
100
    }
101
102
    /// Evaluate this compiled expression against a context (strict policy; see
103
    /// the free `evaluate_strict`).
104
    pub fn evaluate_strict(
105
        &self,
106
        context: JsValue,
107
        functions: JsValue,
108
    ) -> Result<JsValue, JsError> {
109
        run(&self.inner, context, functions, true)
110
    }
111
}
112
113
fn compile_core(expr: &str) -> Result<CoreCompiled, JsError> {
114
    core_compile(expr).map_err(|e| JsError::new(&e.to_string()))
115
}
116
117
/// Parse with the call's scope (context + function registry) as the §10.3.1.6
118
/// name oracle (ADR-47): special-character name runs (`a-b`) fuse into names
119
/// exactly when that scope binds them.
120
fn compile_with_probe_core(expr: &str, probe: &dyn ScopeProbe) -> Result<CoreCompiled, JsError> {
121
    core_compile_with_probe(expr, probe)
122
        .map_err(|e| JsError::new(&e.to_string()))
123
}
124
125
/// Shared per-call boundary: map the JS context in (accepting native `Date`
126
/// objects), evaluate the compiled program against the host regex provider and
127
/// the `Date.now()` instant, optionally surface error-nulls strictly, map the
128
/// result back out (date/date-and-time as native `Date` objects).
129
fn run(compiled: &CoreCompiled, context: JsValue, functions: JsValue, strict: bool) -> Result<JsValue, JsError> {
130
    // Ambient host functions (ADR-23): a JS object of `name -> function`, consulted
131
    // after context bindings and built-ins. `undefined`/`null` -> no-op registry.
132
    let registry = JsFunctionRegistry { funcs: functions };
133
    run_with_ctx(compiled, &context_from_js(&context)?, &registry, strict)
134
}
135
136
/// [`run`] with the context and registry already built — the one-shot entry
137
/// points have them in hand first, because together they are the parse-time
138
/// scope probe.
139
fn run_with_ctx(
140
    compiled: &CoreCompiled,
141
    ctx: &Context,
142
    registry: &JsFunctionRegistry,
143
    strict: bool,
144
) -> Result<JsValue, JsError> {
145
    let env = EvalEnv::with_functions(&REGEX, now_zoned(), registry);
146
    let value = compiled
147
        .evaluate_with_env(ctx, &env)
148
        .map_err(|e| JsError::new(&e.to_string()))?;
149
    if strict && value.contains_error() {
150
        return Err(JsError::new(
151
            "evaluation produced a null from a type or domain error",
152
        ));
153
    }
154
    value_to_js(&value)
155
}
156
157
/// The evaluation instant for `now()`/`today()`: `Date.now()` as a UTC `Zoned`
158
/// (a fixed offset, so `now()` serialises as `…+00:00`).
159
fn now_zoned() -> jiff::Zoned {
160
    let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC);
161
    jiff::Timestamp::from_millisecond(js_sys::Date::now() as i64)
162
        .unwrap_or(jiff::Timestamp::UNIX_EPOCH)
163
        .to_zoned(utc)
164
}
165
166
// --------------------------------------------------------------------------- //
167
// Result mapping (feel-core Value -> native JsValue)
168
// --------------------------------------------------------------------------- //
169
170
/// Map a `feel-core` [`Value`] to a native `JsValue`. Date and date-and-time
171
/// values become native JS `Date` objects (ADR-18; falling back to the ISO string
172
/// if `Date` cannot represent them); `time` and durations stay ISO-8601 strings.
173
/// Lists/contexts are mapped recursively so nested temporal values are preserved.
174
fn value_to_js(value: &Value) -> Result<JsValue, JsError> {
175
    match value {
176
        Value::Date(_) | Value::DateTime(_) => {
177
            let iso = feel_core::temporal::to_iso(value).unwrap_or_default();
178
            let date = js_sys::Date::new(&JsValue::from_str(&iso));
179
            // An unrepresentable date (e.g. sub-millisecond precision JS drops, or
180
            // a parse gap) yields `Invalid Date`; fall back to the ISO string.
181
            if date.get_time().is_nan() {
182
                Ok(JsValue::from_str(&iso))
183
            } else {
184
                Ok(date.into())
185
            }
186
        }
187
        Value::Time(_) | Value::YearsMonthsDuration(_) | Value::DaysTimeDuration(_) => {
188
            Ok(JsValue::from_str(&feel_core::temporal::to_iso(value).unwrap_or_default()))
189
        }
190
        Value::List(items) => {
191
            let arr = js_sys::Array::new();
192
            for item in items {
193
                arr.push(&value_to_js(item)?);
194
            }
195
            Ok(arr.into())
196
        }
197
        Value::Context(map) => {
198
            let obj = js_sys::Object::new();
199
            for (k, v) in map {
200
                js_sys::Reflect::set(&obj, &JsValue::from_str(k), &value_to_js(v)?)
201
                    .map_err(|_| JsError::new("failed to build result object"))?;
202
            }
203
            Ok(obj.into())
204
        }
205
        // Identity pass-through (ADR-21): a lazy host value that reached the result
206
        // is handed back as the *original* `JsValue`, untouched. The downcast cannot
207
        // miss (`JsForeign` is the only impl); fall back to forcing if it ever does.
208
        Value::Foreign(f) => match f.0.as_any().downcast_ref::<JsForeign>() {
209
            Some(jf) => Ok(jf.obj.clone()),
210
            None => value_to_js(&f.0.force()),
211
        },
212
        // A function value (ADR-23): a host callable is handed back as the original
213
        // JS function (identity pass-through); a native FEEL closure has no JS
214
        // representation and crosses out as `null`.
215
        Value::Function(f) => match &**f {
216
            Func::Foreign(host_fn) => match host_fn.as_any().downcast_ref::<JsForeignFn>() {
217
                Some(jf) => Ok(jf.obj.clone()),
218
                None => Ok(JsValue::NULL),
219
            },
220
            Func::Closure(_) | Func::Builtin(_) => Ok(JsValue::NULL),
221
        },
222
        // Scalars (number/bool/string/null) go through the JSON-compatible path so
223
        // integral numbers stay JS numbers (`1 + 1` -> `2`, not `2.0`).
224
        _ => to_js(&value_to_json(value)),
225
    }
226
}
227
228
/// Serialize a JSON value to a native `JsValue`. The `json_compatible` serializer
229
/// maps objects to plain JS objects (not `Map`); integral numbers stay JS numbers.
230
fn to_js(value: &serde_json::Value) -> Result<JsValue, JsError> {
231
    let serializer = serde_wasm_bindgen::Serializer::json_compatible();
232
    value
233
        .serialize(&serializer)
234
        .map_err(|e| JsError::new(&e.to_string()))
235
}
236
237
/// Map a scalar `feel-core` [`Value`] to JSON. Only the non-temporal scalars reach
238
/// here ([`value_to_js`] handles temporal, lists and contexts). Integral numbers
239
/// are emitted as JSON integers so e.g. `1 + 1` yields `2` rather than `2.0`.
240
fn value_to_json(value: &Value) -> serde_json::Value {
241
    match value {
242
        Value::Number(n) => number_to_json(*n),
243
        Value::Boolean(b) => serde_json::Value::Bool(*b),
244
        Value::String(s) => serde_json::Value::String(s.clone()),
245
        // Lenient: an error-null serialises like a plain null. Strict callers
246
        // check `Value::contains_error` before reaching here.
247
        _ => serde_json::Value::Null,
248
    }
249
}
250
251
fn number_to_json(n: f64) -> serde_json::Value {
252
    if n.is_finite() && n.fract() == 0.0 && n.abs() < 9.007_199_254_740_992e15 {
253
        serde_json::Value::Number((n as i64).into())
254
    } else {
255
        serde_json::Number::from_f64(n)
256
            .map(serde_json::Value::Number)
257
            .unwrap_or(serde_json::Value::Null)
258
    }
259
}
260
261
// --------------------------------------------------------------------------- //
262
// Context mapping (native JsValue -> feel-core Value)
263
// --------------------------------------------------------------------------- //
264
265
/// Build a [`Context`] from a native JS object. `undefined`/`null` is the empty
266
/// context; a plain object maps to a context (its top-level members
267
/// shallow-converted, so nested objects become lazy `Foreign`s); any other
268
/// top-level value is an error.
269
fn context_from_js(value: &JsValue) -> Result<Context, JsError> {
270
    if value.is_null() || value.is_undefined() {
271
        return Ok(Context::new());
272
    }
273
    match js_force(value) {
274
        Value::Context(map) => {
275
            let mut ctx = Context::new();
276
            for (key, val) in map {
277
                ctx.insert(key, val);
278
            }
279
            Ok(ctx)
280
        }
281
        _ => Err(JsError::new("expected an object context")),
282
    }
283
}
284
285
/// Convert a single `JsValue` to a [`Value`] **shallowly** (ADR-21): numbers,
286
/// booleans, strings and `Date` eagerly; an array to a `Value::List` whose elements
287
/// are themselves shallow (an object element becomes a lazy `Foreign`); any other
288
/// object to a `Value::Foreign` resolved on demand. Nothing is walked beyond this
289
/// one level, so cyclic graphs are harmless here.
290
fn shallow_convert_js(value: &JsValue) -> Value {
291
    if value.is_null() || value.is_undefined() {
292
        return Value::Null;
293
    }
294
    if let Some(b) = value.as_bool() {
295
        return Value::Boolean(b);
296
    }
297
    if let Some(n) = value.as_f64() {
298
        return Value::Number(n);
299
    }
300
    if let Some(s) = value.as_string() {
301
        return Value::String(s);
302
    }
303
    if value.is_instance_of::<js_sys::Date>() {
304
        let date: &js_sys::Date = value.unchecked_ref();
305
        let iso = date.to_iso_string().as_string().unwrap_or_default();
306
        return feel_core::temporal_from_iso("date and time", &iso).unwrap_or(Value::Null);
307
    }
308
    // Array before object (an array *is* an object): build the spine, elements stay
309
    // shallow so an object element becomes a lazy `Foreign`.
310
    if js_sys::Array::is_array(value) {
311
        let arr: &js_sys::Array = value.unchecked_ref();
312
        return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect());
313
    }
314
    // A JS function becomes a FEEL function value the host can invoke (ADR-23).
315
    // Checked before `is_object` (a function has `typeof === "function"`, not
316
    // `"object"`, but be explicit about ordering).
317
    if value.is_function() {
318
        return Func::Foreign(Arc::new(JsForeignFn { obj: value.clone() })).into_value();
319
    }
320
    if value.is_object() {
321
        return Value::Foreign(Foreign(Arc::new(JsForeign { obj: value.clone() })));
322
    }
323
    Value::Null
324
}
325
326
/// Resolve one member of a JS value by name — the FEEL dot (ADR-21) — via
327
/// `Reflect.get`, which fires JS accessor getters. An absent member (`undefined`)
328
/// is a value-null. The returned value is shallow.
329
fn js_get_member(obj: &JsValue, key: &str) -> Value {
330
    match js_sys::Reflect::get(obj, &JsValue::from_str(key)) {
331
        Ok(v) if v.is_undefined() => Value::Null,
332
        Ok(v) => shallow_convert_js(&v),
333
        Err(_) => Value::Null,
334
    }
335
}
336
337
/// Materialise a `JsValue` *one level* into a concrete [`Value`] (ADR-21): an array
338
/// to a `Value::List`; any other object to a `Value::Context` of its own enumerable
339
/// keys (`Object.keys`); everything else to null. Members are shallow-converted, so
340
/// nested objects stay lazy.
341
fn js_force(value: &JsValue) -> Value {
342
    if js_sys::Array::is_array(value) {
343
        let arr: &js_sys::Array = value.unchecked_ref();
344
        return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect());
345
    }
346
    if value.is_object() {
347
        let obj: &js_sys::Object = value.unchecked_ref();
348
        let mut map = BTreeMap::new();
349
        for key in js_sys::Object::keys(obj).iter() {
350
            let val = js_sys::Reflect::get(value, &key).unwrap_or(JsValue::NULL);
351
            map.insert(key.as_string().unwrap_or_default(), shallow_convert_js(&val));
352
        }
353
        return Value::Context(map);
354
    }
355
    Value::Null
356
}
357
358
/// A lazily-resolved JS object behind feel-core's [`ForeignObject`] seam. WASM is
359
/// single-threaded, so the `JsValue` handle is used directly (no GIL/token).
360
#[derive(Debug)]
361
struct JsForeign {
362
    obj: JsValue,
363
}
364
365
impl ForeignObject for JsForeign {
366
    fn get(&self, key: &str) -> Value {
367
        js_get_member(&self.obj, key)
368
    }
369
370
    fn force(&self) -> Value {
371
        js_force(&self.obj)
372
    }
373
374
    fn as_any(&self) -> &dyn std::any::Any {
375
        self
376
    }
377
378
    /// JS object identity for cycle detection in unbounded traversals (the
379
    /// descendant `...` operator). feel-wasm mints a fresh `Arc<JsForeign>` per wrap
380
    /// (`shallow_convert_js` re-runs on every `force`/`get`), and a `JsValue` handle
381
    /// index is NOT object identity across different reads of the same object, so the
382
    /// default (allocation address) guard would miss a cycle. We map each distinct
383
    /// object to a stable integer via a process-wide `WeakMap` ([`js_identity`]).
384
    fn identity(&self) -> usize {
385
        js_identity(&self.obj)
386
    }
387
}
388
389
/// Assign each distinct JS object a stable integer identity via a process-wide
390
/// `WeakMap`. Its keys are weakly referenced, so it neither pins objects nor grows
391
/// unboundedly with live data — entries are GC'd once the object is unreferenced
392
/// elsewhere. This is the JS analogue of feel-py's `id()` / feel-lua's table
393
/// pointer: JS exposes no cheap object address, so a `WeakMap<object, number>` is
394
/// the standard way to derive a hashable, stable identity.
395
fn js_identity(obj: &JsValue) -> usize {
396
    thread_local! {
397
        static IDS: RefCell<(js_sys::WeakMap, u32)> =
398
            RefCell::new((js_sys::WeakMap::new(), 0));
399
    }
400
    IDS.with(|cell| {
401
        let (map, next) = &mut *cell.borrow_mut();
402
        // A Foreign always wraps an object; `unchecked_ref` is the zero-cost view.
403
        let key: &js_sys::Object = obj.unchecked_ref();
404
        if let Some(v) = map.get_checked(key) {
405
            v.as_f64().map(|n| n as usize).unwrap_or(0)
406
        } else {
407
            let n = *next;
408
            *next += 1;
409
            let _ = map.set(key, &JsValue::from(n));
410
            n as usize
411
        }
412
    })
413
}
414
415
// --------------------------------------------------------------------------- //
416
// Host callables (ADR-23): a JS function invoked from FEEL
417
// --------------------------------------------------------------------------- //
418
419
/// A JS function behind feel-core's [`ForeignFunction`] seam. `obj` is the original
420
/// `JsValue` (a function), kept whole for identity pass-through on output.
421
#[derive(Debug)]
422
struct JsForeignFn {
423
    obj: JsValue,
424
}
425
426
impl ForeignFunction for JsForeignFn {
427
    fn call(&self, args: Args) -> Value {
428
        let func: &js_sys::Function = self.obj.unchecked_ref();
429
        match js_call(func, args) {
430
            Ok(v) => shallow_convert_js(&v),
431
            Err(_) => Value::Error, // a thrown JS exception -> error-null (ADR-14)
432
        }
433
    }
434
435
    fn as_any(&self) -> &dyn std::any::Any {
436
        self
437
    }
438
}
439
440
/// Invoke a JS function with FEEL arguments (ADR-23). JS has no keyword arguments,
441
/// so positional FEEL args become positional JS args and — if any named args are
442
/// present — a single trailing options object `{name: value, …}` is appended (the
443
/// idiomatic JS convention). A thrown exception propagates as `Err`.
444
fn js_call(func: &js_sys::Function, args: Args) -> Result<JsValue, JsValue> {
445
    let arr = js_sys::Array::new();
446
    for v in &args.positional {
447
        arr.push(&value_to_js(v).map_err(|_| JsValue::NULL)?);
448
    }
449
    if !args.named.is_empty() {
450
        let opts = js_sys::Object::new();
451
        for (name, v) in &args.named {
452
            js_sys::Reflect::set(
453
                &opts,
454
                &JsValue::from_str(name),
455
                &value_to_js(v).map_err(|_| JsValue::NULL)?,
456
            )?;
457
        }
458
        arr.push(&opts.into());
459
    }
460
    func.apply(&JsValue::NULL, &arr)
461
}
462
463
/// A host function registry backed by a JS object `name -> function` (the third
464
/// `functions` argument; ADR-23). The ambient-function path, beside binding a
465
/// function directly in the context. `undefined`/`null` means no registry.
466
#[derive(Debug)]
467
struct JsFunctionRegistry {
468
    funcs: JsValue,
469
}
470
471
impl FunctionRegistry for JsFunctionRegistry {
472
    fn get(&self, name: &str) -> Option<Arc<dyn ForeignFunction>> {
473
        if self.funcs.is_undefined() || self.funcs.is_null() {
474
            return None;
475
        }
476
        let item = js_sys::Reflect::get(&self.funcs, &JsValue::from_str(name)).ok()?;
477
        if item.is_function() {
478
            Some(Arc::new(JsForeignFn { obj: item }))
479
        } else {
480
            None
481
        }
482
    }
483
}
484
485
// --------------------------------------------------------------------------- //
486
// Host regex provider (ADR-16)
487
// --------------------------------------------------------------------------- //
488
//
489
// The FEEL `matches`/`replace`/`split` builtins run on the **host** regex engine.
490
// In WASM that is the JS `RegExp`, so the ECMAScript dialect applies here — and
491
// the whole Rust regex stack stays out of the bundle. The purist `xpath-regex`
492
// feature instead re-bundles feel-core's `RustRegex` for cross-target identical
493
// results (at the regex stack's size cost).
494
495
/// The provider used for every evaluation. Both candidates are zero-sized.
496
#[cfg(not(feature = "xpath-regex"))]
497
static REGEX: JsRegex = JsRegex;
498
#[cfg(feature = "xpath-regex")]
499
static REGEX: feel_core::RustRegex = feel_core::RustRegex;
500
501
/// JS-`RegExp`-backed [`feel_core::FeelRegex`]. A `null` from the shims means the
502
/// pattern/flags were invalid in the JS dialect, which maps to a FEEL null.
503
#[cfg(not(feature = "xpath-regex"))]
504
struct JsRegex;
505
506
#[cfg(not(feature = "xpath-regex"))]
507
impl feel_core::FeelRegex for JsRegex {
508
    fn is_match(&self, input: &str, pattern: &str, flags: &str) -> Option<bool> {
509
        let (pattern, js_flags) = to_js_pattern(pattern, flags)?;
510
        let r = js_regex_test(input, &pattern, &js_flags);
511
        if r.is_null() {
512
            None
513
        } else {
514
            r.as_bool()
515
        }
516
    }
517
518
    fn replace(
519
        &self,
520
        input: &str,
521
        pattern: &str,
522
        replacement: &str,
523
        flags: &str,
524
    ) -> Option<String> {
525
        let (pattern, js_flags) = to_js_pattern(pattern, flags)?;
526
        let r = js_regex_replace(input, &pattern, &js_flags, replacement);
527
        if r.is_null() {
528
            None
529
        } else {
530
            r.as_string()
531
        }
532
    }
533
534
    fn split(&self, input: &str, delimiter: &str) -> Option<Vec<String>> {
535
        let r = js_regex_split(input, delimiter);
536
        if r.is_null() {
537
            return None;
538
        }
539
        serde_wasm_bindgen::from_value(r).ok()
540
    }
541
}
542
543
/// Map FEEL/XPath flags (`i s m x q`) to (JS pattern, JS RegExp flags). An
544
/// out-of-set flag letter -> `None` (FEEL null), matching the Rust provider's
545
/// validation. `q` escapes the pattern (literal match); `x`
546
/// (whitespace-insensitive) has no JS equivalent and is ignored.
547
#[cfg(not(feature = "xpath-regex"))]
548
fn to_js_pattern(pattern: &str, flags: &str) -> Option<(String, String)> {
549
    if flags.chars().any(|c| !matches!(c, 'i' | 's' | 'm' | 'x' | 'q')) {
550
        return None;
551
    }
552
    let js_flags: String = flags.chars().filter(|c| matches!(c, 'i' | 's' | 'm')).collect();
553
    let pattern = if flags.contains('q') {
554
        js_escape(pattern)
555
    } else {
556
        pattern.to_string()
557
    };
558
    Some((pattern, js_flags))
559
}
560
561
/// Backslash-escape ECMAScript regex metacharacters (for the `q` flag).
562
#[cfg(not(feature = "xpath-regex"))]
563
fn js_escape(pattern: &str) -> String {
564
    const SPECIAL: &str = r"\^$.|?*+()[]{}";
565
    let mut out = String::with_capacity(pattern.len());
566
    for c in pattern.chars() {
567
        if SPECIAL.contains(c) {
568
            out.push('\\');
569
        }
570
        out.push(c);
571
    }
572
    out
573
}
574
575
// `try/catch` shims so an invalid pattern/flags becomes `null` (-> FEEL null)
576
// instead of a thrown JS exception. `replace` adds the `g` flag because XPath
577
// `replace` replaces all matches, whereas JS `String.replace(regex, …)` only
578
// replaces the first without it.
579
#[cfg(not(feature = "xpath-regex"))]
580
#[wasm_bindgen(inline_js = r#"
581
export function feel_regex_test(input, pattern, flags) {
582
  try { return new RegExp(pattern, flags).test(input); } catch (e) { return null; }
583
}
584
export function feel_regex_replace(input, pattern, flags, replacement) {
585
  try { return input.replace(new RegExp(pattern, flags + "g"), replacement); } catch (e) { return null; }
586
}
587
export function feel_regex_split(input, delimiter) {
588
  try { return input.split(new RegExp(delimiter)); } catch (e) { return null; }
589
}
590
"#)]
591
extern "C" {
592
    #[wasm_bindgen(js_name = feel_regex_test)]
593
    fn js_regex_test(input: &str, pattern: &str, flags: &str) -> JsValue;
594
    #[wasm_bindgen(js_name = feel_regex_replace)]
595
    fn js_regex_replace(input: &str, pattern: &str, flags: &str, replacement: &str) -> JsValue;
596
    #[wasm_bindgen(js_name = feel_regex_split)]
597
    fn js_regex_split(input: &str, delimiter: &str) -> JsValue;
598
}