feat(wrappers): temporal boundary mapping + injected clocks (ADR-18)
public
feat(wrappers): temporal boundary mapping + injected clocks (ADR-18) Expose `feel_core::temporal::to_iso` and map temporal values across both target boundaries: - feel-pg: temporal results serialise as canonical ISO-8601 jsonb strings, so a plain SQL cast yields native date/timestamptz/interval (ADR-5's interval mapping, error path staying in SQL). `now()`/`today()` read GetCurrentTransactionStartTimestamp(), so they are transaction-stable; added #[pg_test]s for the ISO form, the interval cast, and stability. - feel-wasm: date/date-and-time results return native JS `Date` objects (falling back to ISO strings when Date can't represent them), time and durations as ISO strings; the context input accepts JS `Date` objects anywhere via a recursive JsValue->Value walk. `now()` reads Date.now(). Smoke test extended; bundle ~272 KB -> ~738 KB (the bundled IANA tzdb). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
| Changeset | 79b7ecf3abc7715c47ba954f44fc53db879931a0 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 908423f3d221 |
| Children | |
| Pushlog | by timo via ssh |
modified Cargo.lock +3 −0
| @@ -627,6 +627,7 @@ | ||
| 627 | 627 | version = "0.1.0" |
| 628 | 628 | dependencies = [ |
| 629 | 629 | "feel-core", |
| 630 | + "jiff", | |
| 630 | 631 | "pgrx", |
| 631 | 632 | "pgrx-tests", |
| 632 | 633 | "serde_json", |
| @@ -637,6 +638,8 @@ | ||
| 637 | 638 | version = "0.1.0" |
| 638 | 639 | dependencies = [ |
| 639 | 640 | "feel-core", |
| 641 | + "jiff", | |
| 642 | + "js-sys", | |
| 640 | 643 | "serde", |
| 641 | 644 | "serde-wasm-bindgen", |
| 642 | 645 | "serde_json", |
modified crates/feel-core/src/temporal.rs +1 −1
| @@ -265,7 +265,7 @@ | ||
| 265 | 265 | |
| 266 | 266 | /// Canonical XSD/FEEL lexical form for a temporal value, or `None` if `v` is not |
| 267 | 267 | /// temporal. Used by the wrappers' boundary, the fixture loop, and `string(x)`. |
| 268 | -pub(crate) fn to_iso(v: &Value) -> Option<String> { | |
| 268 | +pub fn to_iso(v: &Value) -> Option<String> { | |
| 269 | 269 | Some(match v { |
| 270 | 270 | Value::Date(d) => fmt_date(*d), |
| 271 | 271 | Value::Time(t) => format!("{}{}", fmt_time(t.time), fmt_zone(&t.zone)), |
modified crates/feel-pg/Cargo.toml +3 −0
| @@ -23,6 +23,9 @@ | ||
| 23 | 23 | pgrx = "=0.18.1" |
| 24 | 24 | serde_json.workspace = true |
| 25 | 25 | feel-core = { path = "../feel-core" } |
| 26 | +# Used only to build the `EvalEnv` instant from the transaction start timestamp | |
| 27 | +# (ADR-18); the temporal value logic itself lives in feel-core. | |
| 28 | +jiff.workspace = true | |
| 26 | 29 | |
| 27 | 30 | [dev-dependencies] |
| 28 | 31 | pgrx-tests = "=0.18.1" |
modified crates/feel-pg/src/lib.rs +75 −2
| @@ -15,11 +15,24 @@ | ||
| 15 | 15 | //! engine (e.g. `DirectFunctionCall` to `textregexreplace` / |
| 16 | 16 | //! `regexp_split_to_array`) and be passed via `CompiledExpr::evaluate_with`, so |
| 17 | 17 | //! the *host* dialect applies server-side too — deferred, not done here. |
| 18 | +//! | |
| 19 | +//! Temporal values (ADR-18) cross the boundary as canonical ISO-8601 jsonb | |
| 20 | +//! strings, so converting to a native PostgreSQL type is a plain cast — and the | |
| 21 | +//! cast's error path stays in SQL, never `ereport`-ing through Rust frames: | |
| 22 | +//! | |
| 23 | +//! ```sql | |
| 24 | +//! (feel_eval('date(2017, 8, 3)') #>> '{}')::date -- 2017-08-03 | |
| 25 | +//! (feel_eval('date and time("2017-08-10T...")') #>> '{}')::timestamptz | |
| 26 | +//! (feel_eval('duration("P1Y2M")') #>> '{}')::interval -- 1 year 2 mons | |
| 27 | +//! ``` | |
| 28 | +//! | |
| 29 | +//! `now()`/`today()` read the transaction start timestamp, so they are constant | |
| 30 | +//! across rows of a query and agree with PostgreSQL's own `now()`. | |
| 18 | 31 | |
| 19 | 32 | use pgrx::prelude::*; |
| 20 | 33 | use pgrx::{pg_func_extra, JsonB, PgBox}; |
| 21 | 34 | |
| 22 | -use feel_core::{compile, CompiledExpr, Context, Value}; | |
| 35 | +use feel_core::{compile, CompiledExpr, Context, EvalEnv, RustRegex, Value}; | |
| 23 | 36 | |
| 24 | 37 | ::pgrx::pg_module_magic!(); |
| 25 | 38 | |
| @@ -65,13 +78,31 @@ | ||
| 65 | 78 | |
| 66 | 79 | let ctx = context_from_json(&context.0) |
| 67 | 80 | .unwrap_or_else(|e| error!("invalid feel context: {e}")); |
| 68 | - match compiled.evaluate(&ctx) { | |
| 81 | + // `now()`/`today()` read the transaction start (ADR-18) — constant per query, | |
| 82 | + // matching PostgreSQL's own `now()`/`transaction_timestamp()`. | |
| 83 | + let env = EvalEnv::new(&RustRegex, transaction_start()); | |
| 84 | + match compiled.evaluate_with_env(&ctx, &env) { | |
| 69 | 85 | Ok(value) if strict && value.contains_error() => { |
| 70 | 86 | error!("feel_eval: result is null from a type or domain error (strict mode)") |
| 71 | 87 | } |
| 72 | 88 | Ok(value) => JsonB(value_to_json(&value)), |
| 73 | 89 | Err(e) => error!("feel_eval failed: {e}"), |
| 74 | 90 | } |
| 91 | +} | |
| 92 | + | |
| 93 | +/// The current transaction's start time as a `jiff::Zoned` (UTC), for `now()`/ | |
| 94 | +/// `today()`. PostgreSQL's `TimestampTz` is microseconds since 2000-01-01 UTC. | |
| 95 | +fn transaction_start() -> jiff::Zoned { | |
| 96 | + // SAFETY: a plain read of the transaction timestamp; never `ereport`s. | |
| 97 | + let pg_micros = unsafe { pg_sys::GetCurrentTransactionStartTimestamp() }; | |
| 98 | + const PG_EPOCH_UNIX_SECS: i64 = 946_684_800; // 2000-01-01 minus 1970-01-01 | |
| 99 | + let unix_micros = pg_micros + PG_EPOCH_UNIX_SECS * 1_000_000; | |
| 100 | + // A fixed-offset (not named) UTC zone, so `now()` serialises as `…+00:00`, | |
| 101 | + // which casts straight to `timestamptz` (a named `@UTC` would not). | |
| 102 | + let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC); | |
| 103 | + jiff::Timestamp::from_microsecond(unix_micros) | |
| 104 | + .map(|ts| ts.to_zoned(utc)) | |
| 105 | + .unwrap_or_else(|_| jiff::Zoned::now()) | |
| 75 | 106 | } |
| 76 | 107 | |
| 77 | 108 | /// Map a `feel-core` [`Value`] to a JSON value for the jsonb boundary. |
| @@ -87,6 +118,15 @@ | ||
| 87 | 118 | Value::Context(map) => serde_json::Value::Object( |
| 88 | 119 | map.iter().map(|(k, v)| (k.clone(), value_to_json(v))).collect(), |
| 89 | 120 | ), |
| 121 | + // Temporal values cross as canonical ISO-8601 strings so they cast to | |
| 122 | + // native PostgreSQL date/timestamptz/interval in SQL (ADR-18 / ADR-5). | |
| 123 | + Value::Date(_) | |
| 124 | + | Value::Time(_) | |
| 125 | + | Value::DateTime(_) | |
| 126 | + | Value::YearsMonthsDuration(_) | |
| 127 | + | Value::DaysTimeDuration(_) => feel_core::temporal::to_iso(value) | |
| 128 | + .map(serde_json::Value::String) | |
| 129 | + .unwrap_or(serde_json::Value::Null), | |
| 90 | 130 | // Lenient: an error-null serialises like a plain null. Strict callers |
| 91 | 131 | // check `Value::contains_error` before reaching here. |
| 92 | 132 | Value::Null | Value::Error => serde_json::Value::Null, |
| @@ -241,6 +281,39 @@ | ||
| 241 | 281 | .expect("SPI query failed"); |
| 242 | 282 | assert_eq!(matched, Some(true)); |
| 243 | 283 | } |
| 284 | + | |
| 285 | + #[pg_test] | |
| 286 | + fn temporal_date_is_iso_string() { | |
| 287 | + // A temporal result crosses as a canonical ISO-8601 jsonb string (ADR-18). | |
| 288 | + let matched = | |
| 289 | + Spi::get_one::<bool>(r#"SELECT feel_eval('date(2017, 8, 3)') = '"2017-08-03"'::jsonb"#) | |
| 290 | + .expect("SPI query failed"); | |
| 291 | + assert_eq!(matched, Some(true)); | |
| 292 | + } | |
| 293 | + | |
| 294 | + #[pg_test] | |
| 295 | + fn temporal_duration_casts_to_interval() { | |
| 296 | + // ISO-8601 means converting to a native PostgreSQL type is a plain cast, | |
| 297 | + // satisfying ADR-5's interval mapping (the cast errors stay in SQL). | |
| 298 | + let matched = Spi::get_one::<bool>( | |
| 299 | + r#"SELECT (feel_eval('duration("P1Y2M")') #>> '{}')::interval | |
| 300 | + = interval '1 year 2 months'"#, | |
| 301 | + ) | |
| 302 | + .expect("SPI query failed"); | |
| 303 | + assert_eq!(matched, Some(true)); | |
| 304 | + } | |
| 305 | + | |
| 306 | + #[pg_test] | |
| 307 | + fn now_is_transaction_stable() { | |
| 308 | + // now() reads the transaction start, so it is constant across rows and | |
| 309 | + // equals PostgreSQL's own transaction_timestamp() (ADR-18). | |
| 310 | + let matched = Spi::get_one::<bool>( | |
| 311 | + r#"SELECT bool_and((feel_eval('now()') #>> '{}')::timestamptz = transaction_timestamp()) | |
| 312 | + FROM generate_series(1, 5)"#, | |
| 313 | + ) | |
| 314 | + .expect("SPI query failed"); | |
| 315 | + assert_eq!(matched, Some(true)); | |
| 316 | + } | |
| 244 | 317 | } |
| 245 | 318 | |
| 246 | 319 | /// Required pgrx test harness hooks. |
modified crates/feel-wasm/Cargo.toml +6 −0
| @@ -13,6 +13,12 @@ | ||
| 13 | 13 | serde-wasm-bindgen = "0.6" |
| 14 | 14 | serde = { version = "1", features = ["derive"] } |
| 15 | 15 | serde_json.workspace = true |
| 16 | +# JS `Date` interop (ADR-18): detect `Date` in the context input and return | |
| 17 | +# date/date-and-time results as `Date` objects; also the `now()` clock source. | |
| 18 | +js-sys = "0.3" | |
| 19 | +# Build the `EvalEnv` instant from `Date.now()` and parse the boundary form; the | |
| 20 | +# temporal value logic itself lives in feel-core. | |
| 21 | +jiff.workspace = true | |
| 16 | 22 | # default-features = false drops feel-core's `rust-regex` provider (and the whole |
| 17 | 23 | # regex-automata stack) from the bundle; the regex builtins use the host JS |
| 18 | 24 | # `RegExp` engine instead (ADR-16). |
modified crates/feel-wasm/smoke.mjs +21 −0
| @@ -47,6 +47,27 @@ | ||
| 47 | 47 | } |
| 48 | 48 | } |
| 49 | 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 | + | |
| 50 | 71 | // Boundary policy (ADR-14): a type error is a lenient `null`, but `evaluate_strict` |
| 51 | 72 | // surfaces it as a thrown exception instead of letting it pass silently as `null`. |
| 52 | 73 | const threw = (fn) => { |
modified crates/feel-wasm/src/lib.rs +123 −41
| @@ -9,9 +9,12 @@ | ||
| 9 | 9 | //! boundary-mapping decision: `JsValue` is bridged to `serde_json::Value` with |
| 10 | 10 | //! `serde-wasm-bindgen`, then to `feel-core`'s [`Value`] by the helpers below. |
| 11 | 11 | |
| 12 | -use feel_core::{compile as core_compile, CompiledExpr as CoreCompiled, Context, Value}; | |
| 12 | +use std::collections::BTreeMap; | |
| 13 | + | |
| 14 | +use feel_core::{compile as core_compile, CompiledExpr as CoreCompiled, Context, EvalEnv, Value}; | |
| 13 | 15 | use serde::Serialize; |
| 14 | 16 | use wasm_bindgen::prelude::*; |
| 17 | +use wasm_bindgen::JsCast; | |
| 15 | 18 | |
| 16 | 19 | /// Evaluate a FEEL expression (lenient boundary policy). |
| 17 | 20 | /// |
| @@ -73,22 +76,76 @@ | ||
| 73 | 76 | core_compile(expr).map_err(|e| JsError::new(&e.to_string())) |
| 74 | 77 | } |
| 75 | 78 | |
| 76 | -/// Shared per-call boundary: map the JS context in, evaluate the compiled | |
| 77 | -/// program against the host regex provider, optionally surface error-nulls | |
| 78 | -/// strictly, map the result back out. | |
| 79 | +/// Shared per-call boundary: map the JS context in (accepting native `Date` | |
| 80 | +/// objects), evaluate the compiled program against the host regex provider and | |
| 81 | +/// the `Date.now()` instant, optionally surface error-nulls strictly, map the | |
| 82 | +/// result back out (date/date-and-time as native `Date` objects). | |
| 79 | 83 | fn run(compiled: &CoreCompiled, context: JsValue, strict: bool) -> Result<JsValue, JsError> { |
| 80 | - let parsed: serde_json::Value = serde_wasm_bindgen::from_value(context) | |
| 81 | - .map_err(|e| JsError::new(&format!("invalid context: {e}")))?; | |
| 82 | - let ctx = context_from_json(&parsed).map_err(|m| JsError::new(&m))?; | |
| 84 | + let ctx = context_from_js(&context)?; | |
| 85 | + let env = EvalEnv::new(®EX, now_zoned()); | |
| 83 | 86 | let value = compiled |
| 84 | - .evaluate_with(&ctx, ®EX) | |
| 87 | + .evaluate_with_env(&ctx, &env) | |
| 85 | 88 | .map_err(|e| JsError::new(&e.to_string()))?; |
| 86 | 89 | if strict && value.contains_error() { |
| 87 | 90 | return Err(JsError::new( |
| 88 | 91 | "evaluation produced a null from a type or domain error", |
| 89 | 92 | )); |
| 90 | 93 | } |
| 91 | - to_js(&value_to_json(&value)) | |
| 94 | + value_to_js(&value) | |
| 95 | +} | |
| 96 | + | |
| 97 | +/// The evaluation instant for `now()`/`today()`: `Date.now()` as a UTC `Zoned` | |
| 98 | +/// (a fixed offset, so `now()` serialises as `…+00:00`). | |
| 99 | +fn now_zoned() -> jiff::Zoned { | |
| 100 | + let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC); | |
| 101 | + jiff::Timestamp::from_millisecond(js_sys::Date::now() as i64) | |
| 102 | + .unwrap_or(jiff::Timestamp::UNIX_EPOCH) | |
| 103 | + .to_zoned(utc) | |
| 104 | +} | |
| 105 | + | |
| 106 | +// --------------------------------------------------------------------------- // | |
| 107 | +// Result mapping (feel-core Value -> native JsValue) | |
| 108 | +// --------------------------------------------------------------------------- // | |
| 109 | + | |
| 110 | +/// Map a `feel-core` [`Value`] to a native `JsValue`. Date and date-and-time | |
| 111 | +/// values become native JS `Date` objects (ADR-18; falling back to the ISO string | |
| 112 | +/// if `Date` cannot represent them); `time` and durations stay ISO-8601 strings. | |
| 113 | +/// Lists/contexts are mapped recursively so nested temporal values are preserved. | |
| 114 | +fn value_to_js(value: &Value) -> Result<JsValue, JsError> { | |
| 115 | + match value { | |
| 116 | + Value::Date(_) | Value::DateTime(_) => { | |
| 117 | + let iso = feel_core::temporal::to_iso(value).unwrap_or_default(); | |
| 118 | + let date = js_sys::Date::new(&JsValue::from_str(&iso)); | |
| 119 | + // An unrepresentable date (e.g. sub-millisecond precision JS drops, or | |
| 120 | + // a parse gap) yields `Invalid Date`; fall back to the ISO string. | |
| 121 | + if date.get_time().is_nan() { | |
| 122 | + Ok(JsValue::from_str(&iso)) | |
| 123 | + } else { | |
| 124 | + Ok(date.into()) | |
| 125 | + } | |
| 126 | + } | |
| 127 | + Value::Time(_) | Value::YearsMonthsDuration(_) | Value::DaysTimeDuration(_) => { | |
| 128 | + Ok(JsValue::from_str(&feel_core::temporal::to_iso(value).unwrap_or_default())) | |
| 129 | + } | |
| 130 | + Value::List(items) => { | |
| 131 | + let arr = js_sys::Array::new(); | |
| 132 | + for item in items { | |
| 133 | + arr.push(&value_to_js(item)?); | |
| 134 | + } | |
| 135 | + Ok(arr.into()) | |
| 136 | + } | |
| 137 | + Value::Context(map) => { | |
| 138 | + let obj = js_sys::Object::new(); | |
| 139 | + for (k, v) in map { | |
| 140 | + js_sys::Reflect::set(&obj, &JsValue::from_str(k), &value_to_js(v)?) | |
| 141 | + .map_err(|_| JsError::new("failed to build result object"))?; | |
| 142 | + } | |
| 143 | + Ok(obj.into()) | |
| 144 | + } | |
| 145 | + // Scalars (number/bool/string/null) go through the JSON-compatible path so | |
| 146 | + // integral numbers stay JS numbers (`1 + 1` -> `2`, not `2.0`). | |
| 147 | + _ => to_js(&value_to_json(value)), | |
| 148 | + } | |
| 92 | 149 | } |
| 93 | 150 | |
| 94 | 151 | /// Serialize a JSON value to a native `JsValue`. The `json_compatible` serializer |
| @@ -100,22 +157,17 @@ | ||
| 100 | 157 | .map_err(|e| JsError::new(&e.to_string())) |
| 101 | 158 | } |
| 102 | 159 | |
| 103 | -/// Map a `feel-core` [`Value`] to a JSON value for the string boundary. | |
| 104 | -/// | |
| 105 | -/// Integral numbers are emitted as JSON integers so that e.g. `1 + 1` yields | |
| 106 | -/// `2` rather than `2.0`. | |
| 160 | +/// Map a scalar `feel-core` [`Value`] to JSON. Only the non-temporal scalars reach | |
| 161 | +/// here ([`value_to_js`] handles temporal, lists and contexts). Integral numbers | |
| 162 | +/// are emitted as JSON integers so e.g. `1 + 1` yields `2` rather than `2.0`. | |
| 107 | 163 | fn value_to_json(value: &Value) -> serde_json::Value { |
| 108 | 164 | match value { |
| 109 | 165 | Value::Number(n) => number_to_json(*n), |
| 110 | 166 | Value::Boolean(b) => serde_json::Value::Bool(*b), |
| 111 | 167 | Value::String(s) => serde_json::Value::String(s.clone()), |
| 112 | - Value::List(items) => serde_json::Value::Array(items.iter().map(value_to_json).collect()), | |
| 113 | - Value::Context(map) => serde_json::Value::Object( | |
| 114 | - map.iter().map(|(k, v)| (k.clone(), value_to_json(v))).collect(), | |
| 115 | - ), | |
| 116 | 168 | // Lenient: an error-null serialises like a plain null. Strict callers |
| 117 | 169 | // check `Value::contains_error` before reaching here. |
| 118 | - Value::Null | Value::Error => serde_json::Value::Null, | |
| 170 | + _ => serde_json::Value::Null, | |
| 119 | 171 | } |
| 120 | 172 | } |
| 121 | 173 | |
| @@ -129,33 +181,63 @@ | ||
| 129 | 181 | } |
| 130 | 182 | } |
| 131 | 183 | |
| 132 | -fn context_from_json(json: &serde_json::Value) -> Result<Context, String> { | |
| 133 | - let mut ctx = Context::new(); | |
| 134 | - match json { | |
| 135 | - serde_json::Value::Object(map) => { | |
| 184 | +// --------------------------------------------------------------------------- // | |
| 185 | +// Context mapping (native JsValue -> feel-core Value) | |
| 186 | +// --------------------------------------------------------------------------- // | |
| 187 | + | |
| 188 | +/// Build a [`Context`] from a native JS object. `undefined`/`null` is the empty | |
| 189 | +/// context; any other top-level value is an error. | |
| 190 | +fn context_from_js(value: &JsValue) -> Result<Context, JsError> { | |
| 191 | + if value.is_null() || value.is_undefined() { | |
| 192 | + return Ok(Context::new()); | |
| 193 | + } | |
| 194 | + match js_to_value(value) { | |
| 195 | + Value::Context(map) => { | |
| 196 | + let mut ctx = Context::new(); | |
| 136 | 197 | for (key, val) in map { |
| 137 | - ctx.insert(key.clone(), json_to_value(val)); | |
| 198 | + ctx.insert(key, val); | |
| 138 | 199 | } |
| 139 | 200 | Ok(ctx) |
| 140 | 201 | } |
| 141 | - serde_json::Value::Null => Ok(ctx), | |
| 142 | - other => Err(format!("expected a JSON object, got {other}")), | |
| 143 | - } | |
| 144 | -} | |
| 145 | - | |
| 146 | -/// Map a JSON value to a `feel-core` [`Value`]. Numbers, booleans, strings, | |
| 147 | -/// arrays (-> list), objects (-> context) and null are supported. | |
| 148 | -fn json_to_value(json: &serde_json::Value) -> Value { | |
| 149 | - match json { | |
| 150 | - serde_json::Value::Number(num) => num.as_f64().map(Value::Number).unwrap_or(Value::Null), | |
| 151 | - serde_json::Value::Bool(b) => Value::Boolean(*b), | |
| 152 | - serde_json::Value::String(s) => Value::String(s.clone()), | |
| 153 | - serde_json::Value::Array(arr) => Value::List(arr.iter().map(json_to_value).collect()), | |
| 154 | - serde_json::Value::Object(map) => Value::Context( | |
| 155 | - map.iter().map(|(k, v)| (k.clone(), json_to_value(v))).collect(), | |
| 156 | - ), | |
| 157 | - serde_json::Value::Null => Value::Null, | |
| 158 | - } | |
| 202 | + _ => Err(JsError::new("expected an object context")), | |
| 203 | + } | |
| 204 | +} | |
| 205 | + | |
| 206 | +/// Map a native `JsValue` to a `feel-core` [`Value`], accepting a JS `Date` | |
| 207 | +/// anywhere as a FEEL date and time (ADR-18). Numbers, booleans, strings, arrays | |
| 208 | +/// (-> list), plain objects (-> context) and null/undefined are supported. | |
| 209 | +fn js_to_value(value: &JsValue) -> Value { | |
| 210 | + if value.is_null() || value.is_undefined() { | |
| 211 | + return Value::Null; | |
| 212 | + } | |
| 213 | + if let Some(b) = value.as_bool() { | |
| 214 | + return Value::Boolean(b); | |
| 215 | + } | |
| 216 | + if let Some(n) = value.as_f64() { | |
| 217 | + return Value::Number(n); | |
| 218 | + } | |
| 219 | + if let Some(s) = value.as_string() { | |
| 220 | + return Value::String(s); | |
| 221 | + } | |
| 222 | + if value.is_instance_of::<js_sys::Date>() { | |
| 223 | + let date: &js_sys::Date = value.unchecked_ref(); | |
| 224 | + let iso = date.to_iso_string().as_string().unwrap_or_default(); | |
| 225 | + return feel_core::temporal_from_iso("date and time", &iso).unwrap_or(Value::Null); | |
| 226 | + } | |
| 227 | + if js_sys::Array::is_array(value) { | |
| 228 | + let arr: &js_sys::Array = value.unchecked_ref(); | |
| 229 | + return Value::List(arr.iter().map(|x| js_to_value(&x)).collect()); | |
| 230 | + } | |
| 231 | + if value.is_object() { | |
| 232 | + let obj: &js_sys::Object = value.unchecked_ref(); | |
| 233 | + let mut map = BTreeMap::new(); | |
| 234 | + for key in js_sys::Object::keys(obj).iter() { | |
| 235 | + let val = js_sys::Reflect::get(value, &key).unwrap_or(JsValue::NULL); | |
| 236 | + map.insert(key.as_string().unwrap_or_default(), js_to_value(&val)); | |
| 237 | + } | |
| 238 | + return Value::Context(map); | |
| 239 | + } | |
| 240 | + Value::Null | |
| 159 | 241 | } |
| 160 | 242 | |
| 161 | 243 | // --------------------------------------------------------------------------- // |