fel-core 0.3.0

Formspec Expression Language — parser, evaluator, and dependency analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! Canonical conversion between serde_json::Value and TypeValue.
//!
//! These are the single source of truth for JSON↔FEL value conversion.
//! All crates should use these instead of rolling their own.

use std::collections::HashMap;

use indexmap::IndexMap;
use rust_decimal::Decimal;
use rust_decimal::prelude::*;
use serde_json::Value;

use crate::types::{CurrencyCode, Money as TypeMoney, Value as TypeValue};

/// Largest integer that JavaScript can represent exactly in a `number`.
const JSON_SAFE_INTEGER_MAX: i64 = 9_007_199_254_740_991;
/// Smallest integer that JavaScript can represent exactly in a `number`.
const JSON_SAFE_INTEGER_MIN: i64 = -9_007_199_254_740_991;

/// Returns true when `i` fits exactly in a JavaScript `number`.
fn is_json_safe_integer(i: i64) -> bool {
    (JSON_SAFE_INTEGER_MIN..=JSON_SAFE_INTEGER_MAX).contains(&i)
}

/// JSON object → flat field map for FEL `MapEnvironment` (`{}` / empty → empty map).
pub fn json_object_to_field_map(val: &Value) -> HashMap<String, TypeValue> {
    let mut map = HashMap::new();
    if let Some(obj) = val.as_object() {
        for (k, v) in obj {
            map.insert(k.clone(), json_to_fel(v));
        }
    }
    map
}

/// Parse a JSON object string into a field map (empty or `"{}"` → empty map).
pub fn field_map_from_json_str(fields_json: &str) -> Result<HashMap<String, TypeValue>, String> {
    if fields_json.is_empty() || fields_json == "{}" {
        return Ok(HashMap::new());
    }
    let json_val: Value =
        serde_json::from_str(fields_json).map_err(|e| format!("invalid fields JSON: {e}"))?;
    Ok(json_object_to_field_map(&json_val))
}

/// Convert a `serde_json::Value` to a `TypeValue`.
///
/// Conversion rules:
/// - `Null` → `TypeValue::Null`
/// - `Bool(b)` → `TypeValue::Boolean(b)`
/// - `Number(n)` → `TypeValue::Number` (tries i64, then u64, then f64)
/// - `String(s)` → `TypeValue::String(s)` — no silent date coercion
/// - `Array(arr)` → `TypeValue::Array` (recursive)
/// - `Object` with `"$type": "money"` + `"amount"` + `"currency"` → `TypeValue::Money`
/// - `Object` otherwise → `TypeValue::Object` (recursive)
///
/// Money detection requires an explicit `"$type": "money"` marker. Objects that
/// happen to have `amount` and `currency` fields but lack the marker are treated
/// as regular objects — no heuristic guessing.
///
/// The `amount` field accepts either a JSON number or a JSON string that parses
/// as a Decimal.
pub fn json_to_fel(val: &Value) -> TypeValue {
    match val {
        Value::Null => TypeValue::Null,
        Value::Bool(b) => TypeValue::Boolean(*b),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                TypeValue::Number(Decimal::from(i))
            } else if let Some(u) = n.as_u64() {
                TypeValue::Number(Decimal::from(u))
            } else if let Some(f) = n.as_f64() {
                Decimal::from_f64(f)
                    .map(TypeValue::Number)
                    .unwrap_or(TypeValue::Null)
            } else {
                TypeValue::Null
            }
        }
        Value::String(s) => TypeValue::String(s.clone()),
        Value::Array(arr) => TypeValue::Array(arr.iter().map(json_to_fel).collect()),
        Value::Object(map) => {
            if let Some(value_type) = map.get("$type").and_then(|v| v.as_str()) {
                if value_type == "number" {
                    if let Some(raw) = map.get("value") {
                        return match raw {
                            Value::Number(n) => n
                                .as_i64()
                                .map(Decimal::from)
                                .or_else(|| n.as_u64().map(Decimal::from))
                                .or_else(|| n.as_f64().and_then(Decimal::from_f64))
                                .map(TypeValue::Number)
                                .unwrap_or(TypeValue::Null),
                            Value::String(s) => Decimal::from_str_exact(s)
                                .map(TypeValue::Number)
                                .unwrap_or(TypeValue::Null),
                            _ => TypeValue::Null,
                        };
                    }
                }
                if value_type == "date" {
                    if let Some(s) = map.get("value").and_then(|v| v.as_str()) {
                        if let Some(d) = crate::types::parse_datetime_literal(&format!("@{s}")) {
                            return TypeValue::Date(d);
                        }
                        if let Some(d) = crate::types::parse_date_literal(&format!("@{s}")) {
                            return TypeValue::Date(d);
                        }
                    }
                    return TypeValue::Null;
                }
                if value_type == "money"
                    && let Some(currency) = map.get("currency").and_then(|v| v.as_str())
                    && let Some(amount) = map.get("amount")
                {
                    let maybe_decimal = match amount {
                        Value::Number(n) => n
                            .as_i64()
                            .map(Decimal::from)
                            .or_else(|| n.as_u64().map(Decimal::from))
                            .or_else(|| n.as_f64().and_then(Decimal::from_f64)),
                        Value::String(s) => Decimal::from_str_exact(s).ok(),
                        _ => None,
                    };
                    if let Some(amount_decimal) = maybe_decimal {
                        if let Some(cc) = CurrencyCode::parse(currency) {
                            return TypeValue::Money(TypeMoney {
                                amount: amount_decimal,
                                currency: cc,
                            });
                        }
                    }
                }
            }
            TypeValue::Object(
                map.iter()
                    .map(|(k, v)| (k.clone(), json_to_fel(v)))
                    .collect::<IndexMap<_, _>>(),
            )
        }
    }
}

/// Convert a `TypeValue` to a `serde_json::Value`.
///
/// Conversion rules:
/// - `Null` → `Value::Null`
/// - `Boolean(b)` → `Value::Bool(b)`
/// - `Number(n)` → `{"$type": "number", "value": <number|string>}`. The `value`
///   member is a JSON integer only when whole and within JavaScript's safe integer range;
///   otherwise it is a normalized decimal string.
/// - `String(s)` → `Value::String(s)`
/// - `Date(d)` → `{"$type": "date", "value": <iso-string>}`
/// - `Money { amount, currency }` → `{"$type": "money", "amount": <decimal-string>, "currency": <string>}`
/// - `Array(arr)` → `Value::Array` (recursive)
/// - `Object(entries)` → `Value::Object` (recursive)
pub fn fel_to_wire_json(val: &TypeValue) -> Value {
    match val {
        TypeValue::Null => Value::Null,
        TypeValue::Boolean(b) => Value::Bool(*b),
        TypeValue::Number(n) => {
            let mut map = serde_json::Map::new();
            map.insert("$type".to_string(), Value::String("number".to_string()));
            map.insert("value".to_string(), decimal_to_wire_number_value(n));
            Value::Object(map)
        }
        TypeValue::String(s) => Value::String(s.clone()),
        TypeValue::Date(d) => {
            let mut map = serde_json::Map::new();
            map.insert("$type".to_string(), Value::String("date".to_string()));
            map.insert("value".to_string(), Value::String(d.format_iso()));
            Value::Object(map)
        }
        TypeValue::Array(arr) => Value::Array(arr.iter().map(fel_to_wire_json).collect()),
        TypeValue::Object(entries) => {
            let map: serde_json::Map<String, Value> = entries
                .iter()
                .map(|(k, v)| (k.clone(), fel_to_wire_json(v)))
                .collect();
            Value::Object(map)
        }
        TypeValue::Money(m) => {
            let mut map = serde_json::Map::new();
            map.insert("$type".to_string(), Value::String("money".to_string()));
            map.insert(
                "amount".to_string(),
                Value::String(m.amount.normalize().to_string()),
            );
            map.insert(
                "currency".to_string(),
                Value::String(m.currency.to_string()),
            );
            Value::Object(map)
        }
    }
}

/// Convert a `TypeValue` into UI-friendly JSON.
///
/// Intended for display surfaces and host APIs that do not feed values back into
/// FEL evaluation. Decimal values are emitted as JSON numbers only when the
/// serialized JSON number text round-trips exactly to the same Decimal.
pub fn fel_to_ui_json(val: &TypeValue) -> Value {
    match val {
        TypeValue::Null => Value::Null,
        TypeValue::Boolean(b) => Value::Bool(*b),
        TypeValue::Number(n) => {
            if let Some(num) = decimal_to_lossless_ui_number(n) {
                return Value::Number(num);
            }
            Value::String(n.normalize().to_string())
        }
        TypeValue::String(s) => Value::String(s.clone()),
        TypeValue::Date(d) => Value::String(d.format_iso()),
        TypeValue::Array(arr) => Value::Array(arr.iter().map(fel_to_ui_json).collect()),
        TypeValue::Object(entries) => {
            let map: serde_json::Map<String, Value> = entries
                .iter()
                .map(|(k, v)| (k.clone(), fel_to_ui_json(v)))
                .collect();
            Value::Object(map)
        }
        TypeValue::Money(m) => {
            let mut map = serde_json::Map::new();
            map.insert(
                "amount".to_string(),
                fel_to_ui_json(&TypeValue::Number(m.amount)),
            );
            map.insert(
                "currency".to_string(),
                Value::String(m.currency.to_string()),
            );
            Value::Object(map)
        }
    }
}

/// Converts a decimal to a JSON number only when the text round-trips exactly.
fn decimal_to_lossless_ui_number(n: &Decimal) -> Option<serde_json::Number> {
    if n.fract().is_zero()
        && let Some(i) = n.to_i64()
        && is_json_safe_integer(i)
    {
        return Some(serde_json::Number::from(i));
    }

    let f = n.to_f64()?;
    if !f.is_finite() {
        return None;
    }
    let num = serde_json::Number::from_f64(f)?;
    let serialized = num.to_string();
    let reparsed = Decimal::from_str_exact(&serialized)
        .or_else(|_| Decimal::from_scientific(&serialized))
        .ok()?;
    (reparsed == *n).then_some(num)
}

/// Encodes a decimal for typed wire JSON.
fn decimal_to_wire_number_value(n: &Decimal) -> Value {
    if n.fract().is_zero()
        && let Some(i) = n.to_i64()
        && is_json_safe_integer(i)
    {
        return Value::Number(serde_json::Number::from(i));
    }
    Value::String(n.normalize().to_string())
}

/// Backward-compatible alias for UI-friendly encoding (`fel_to_ui_json`).
pub fn fel_to_json(val: &TypeValue) -> Value {
    fel_to_ui_json(val)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::missing_docs_in_private_items)]
    use super::*;
    use crate::types::CurrencyCode;
    use indexmap::IndexMap;
    use serde_json::json;

    #[test]
    fn null_roundtrip() {
        let val = json_to_fel(&json!(null));
        assert!(matches!(val, TypeValue::Null));
        assert_eq!(fel_to_json(&val), json!(null));
    }

    #[test]
    fn boolean_roundtrip() {
        assert!(matches!(
            json_to_fel(&json!(true)),
            TypeValue::Boolean(true)
        ));
        assert!(matches!(
            json_to_fel(&json!(false)),
            TypeValue::Boolean(false)
        ));
        assert_eq!(fel_to_json(&TypeValue::Boolean(true)), json!(true));
        assert_eq!(fel_to_json(&TypeValue::Boolean(false)), json!(false));
    }

    #[test]
    fn integer_roundtrip() {
        let val = json_to_fel(&json!(42));
        assert_eq!(fel_to_json(&val), json!(42));
    }

    #[test]
    #[allow(clippy::approx_constant)]
    fn float_roundtrip() {
        let val = json_to_fel(&json!(3.14));
        let back = fel_to_json(&val);
        assert!(
            back.as_f64().is_some() && (back.as_f64().unwrap() - 3.14_f64).abs() < 1e-9,
            "expected JSON number near 3.14, got {back:?}"
        );
    }

    #[test]
    fn string_roundtrip() {
        let val = json_to_fel(&json!("hello"));
        assert!(matches!(val, TypeValue::String(ref s) if s == "hello"));
        assert_eq!(fel_to_json(&val), json!("hello"));
    }

    #[test]
    fn string_no_date_coercion() {
        // ISO date strings must NOT be silently coerced to TypeValue::Date
        let val = json_to_fel(&json!("2024-06-15"));
        assert!(
            matches!(val, TypeValue::String(ref s) if s == "2024-06-15"),
            "expected String, got {val:?}"
        );

        let val = json_to_fel(&json!("2024-06-15T10:30:00"));
        assert!(
            matches!(val, TypeValue::String(ref s) if s == "2024-06-15T10:30:00"),
            "expected String, got {val:?}"
        );
    }

    #[test]
    fn array_roundtrip() {
        let val = json_to_fel(&json!([1, "two", null]));
        let back = fel_to_json(&val);
        assert_eq!(back, json!([1, "two", null]));
    }

    #[test]
    fn object_roundtrip() {
        let val = json_to_fel(&json!({"a": 1, "b": "two"}));
        let back = fel_to_json(&val);
        assert_eq!(back["a"], json!(1));
        assert_eq!(back["b"], json!("two"));
    }

    #[test]
    fn object_serialization_preserves_entry_order() {
        let value = TypeValue::Object(IndexMap::from([
            ("b".to_string(), TypeValue::Number(Decimal::from(1))),
            ("a".to_string(), TypeValue::Number(Decimal::from(2))),
            ("c".to_string(), TypeValue::Number(Decimal::from(3))),
        ]));
        let json = fel_to_json(&value);
        let keys: Vec<String> = json.as_object().expect("object").keys().cloned().collect();
        assert_eq!(keys, vec!["b", "a", "c"]);
    }

    #[test]
    fn money_numeric_amount() {
        let val = json_to_fel(&json!({"$type": "money", "amount": 99.99, "currency": "USD"}));
        match &val {
            TypeValue::Money(m) => {
                assert_eq!(m.currency.as_str(), "USD");
                let f = m.amount.to_f64().unwrap();
                assert!((f - 99.99).abs() < 0.01, "amount: {f}");
            }
            other => panic!("expected Money, got {other:?}"),
        }
    }

    #[test]
    fn money_string_amount() {
        let val = json_to_fel(&json!({"$type": "money", "amount": "99.99", "currency": "USD"}));
        match &val {
            TypeValue::Money(m) => {
                assert_eq!(m.currency.as_str(), "USD");
                // String amount parsed as exact Decimal
                assert_eq!(m.amount, Decimal::from_str_exact("99.99").unwrap());
            }
            other => panic!("expected Money, got {other:?}"),
        }
    }

    #[test]
    fn money_integer_amount() {
        let val = json_to_fel(&json!({"$type": "money", "amount": 100, "currency": "EUR"}));
        match &val {
            TypeValue::Money(m) => {
                assert_eq!(m.currency.as_str(), "EUR");
                assert_eq!(m.amount, Decimal::from(100));
            }
            other => panic!("expected Money, got {other:?}"),
        }
    }

    #[test]
    fn money_without_type_marker_is_object() {
        // Object with "amount" + "currency" but no "$type": "money" must NOT become Money
        let val = json_to_fel(&json!({"amount": 99.99, "currency": "USD"}));
        assert!(
            matches!(val, TypeValue::Object(_)),
            "expected Object, got {val:?}"
        );
    }

    #[test]
    fn money_roundtrip() {
        let money = TypeValue::Money(TypeMoney {
            amount: Decimal::from_str_exact("99.99").unwrap(),
            currency: CurrencyCode::parse("USD").unwrap(),
        });
        let json = fel_to_wire_json(&money);
        assert_eq!(json.get("$type"), Some(&json!("money")));
        assert_eq!(json.get("currency"), Some(&json!("USD")));
        assert_eq!(json.get("amount"), Some(&json!("99.99")));
    }

    #[test]
    fn number_wire_uses_json_integer_for_safe_integer() {
        let json = fel_to_wire_json(&TypeValue::Number(Decimal::from(42)));
        assert_eq!(json.get("$type"), Some(&json!("number")));
        assert_eq!(json.get("value"), Some(&json!(42)));
    }

    #[test]
    fn number_wire_uses_string_for_integer_above_js_safe_range() {
        let dec = Decimal::from(9_223_372_036_854_775_707_i64);
        let json = fel_to_wire_json(&TypeValue::Number(dec));
        assert_eq!(json.get("$type"), Some(&json!("number")));
        assert_eq!(json.get("value"), Some(&json!("9223372036854775707")));
    }

    #[test]
    fn number_wire_uses_string_for_fractional_decimal() {
        let dec = Decimal::from_str_exact("0.1").unwrap();
        let json = fel_to_wire_json(&TypeValue::Number(dec));
        assert_eq!(json.get("$type"), Some(&json!("number")));
        assert_eq!(json.get("value"), Some(&json!("0.1")));
    }

    #[test]
    fn money_missing_currency_becomes_object() {
        // Object with "amount" but no "currency" should NOT become Money
        let val = json_to_fel(&json!({"$type": "money", "amount": 100}));
        assert!(
            matches!(val, TypeValue::Object(_)),
            "expected Object, got {val:?}"
        );
    }

    #[test]
    fn money_non_numeric_amount_becomes_object() {
        // "amount" that isn't numeric or parseable as Decimal → plain Object
        let val = json_to_fel(&json!({"$type": "money", "amount": true, "currency": "USD"}));
        assert!(
            matches!(val, TypeValue::Object(_)),
            "expected Object, got {val:?}"
        );
    }

    #[test]
    fn date_to_json_iso_string() {
        use crate::types::Date;
        let date = TypeValue::Date(Date::Date {
            year: 2025,
            month: 6,
            day: 15,
        });
        assert_eq!(fel_to_json(&date), json!("2025-06-15"));
    }

    #[test]
    fn datetime_to_json_iso_string() {
        use crate::types::Date;
        let dt = TypeValue::Date(Date::DateTime {
            year: 2025,
            month: 6,
            day: 15,
            hour: 10,
            minute: 30,
            second: 0,
        });
        assert_eq!(fel_to_json(&dt), json!("2025-06-15T10:30:00"));
    }

    #[test]
    fn decimal_max_falls_back_to_json_string_when_f64_roundtrip_lossy() {
        let val = TypeValue::Number(Decimal::MAX);
        let json = fel_to_json(&val);
        assert!(
            json.is_string(),
            "Decimal::MAX should produce a JSON string"
        );
    }

    #[test]
    fn non_integer_decimal_keeps_full_precision_as_json_string() {
        let dec = Decimal::from_str_exact("0.1234567890123456789012345678").unwrap();
        let json = fel_to_json(&TypeValue::Number(dec));
        assert_eq!(json, json!("0.1234567890123456789012345678"));
    }

    #[test]
    fn tiny_decimal_that_serializes_inexactly_falls_back_to_string() {
        let dec = Decimal::from_str_exact("0.0000000000000000000000000001").unwrap();
        let json = fel_to_json(&TypeValue::Number(dec));
        assert_eq!(json, json!("0.0000000000000000000000000001"));
    }

    #[test]
    fn integer_above_js_safe_range_falls_back_to_string() {
        let dec = Decimal::from(9_223_372_036_854_775_707_i64);
        let json = fel_to_json(&TypeValue::Number(dec));
        assert_eq!(json, json!("9223372036854775707"));
    }

    #[test]
    fn nested_object_roundtrip() {
        let val = json_to_fel(&json!({"outer": {"inner": 42}}));
        let back = fel_to_json(&val);
        assert_eq!(back["outer"]["inner"], json!(42));
    }

    /// Regression: values stored as `serde_json::Value` between FEL passes (e.g. definition
    /// variables) must re-enter `json_to_fel` as **numbers**, not strings — otherwise arithmetic
    /// and cross-field calculates receive `string` FEL types and yield null.
    #[test]
    fn fel_to_json_scalar_numbers_rehydrate_as_number_not_string_for_typical_decimals() {
        for s in ["0.1", "20", "3.14"] {
            let n = Decimal::from_str_exact(s).expect("decimal");
            let wire = fel_to_json(&TypeValue::Number(n));
            assert!(
                wire.is_number(),
                "{s}: expected JSON number wire, got {wire:?}"
            );
            let back = json_to_fel(&wire);
            assert!(
                matches!(back, TypeValue::Number(_)),
                "{s}: expected TypeValue::Number after json_to_fel, got {back:?}"
            );
        }
    }

    #[test]
    fn u64_large_number() {
        // A number larger than i64::MAX but within u64 range
        let big = (i64::MAX as u64) + 1;
        let val = json_to_fel(&json!(big));
        match &val {
            TypeValue::Number(n) => assert_eq!(*n, Decimal::from(big)),
            other => panic!("expected Number, got {other:?}"),
        }
    }

    /// Plain JSON numbers must not map `from_f64` failure to zero (typed paths use Null).
    #[test]
    fn plain_json_float_non_representable_becomes_null() {
        for f in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let val = json_to_fel(&Value::from(f));
            assert!(
                matches!(val, TypeValue::Null),
                "f={f:?}: expected Null, got {val:?}"
            );
        }
    }

    #[test]
    fn typed_number_non_representable_float_becomes_null() {
        let val = json_to_fel(&json!({
            "$type": "number",
            "value": Value::from(f64::NAN),
        }));
        assert!(matches!(val, TypeValue::Null));
    }

    // ── Boundary tests for json_to_fel `$type:"number"` value match arms ──
    //
    // The two match arms `Value::Number(_)` and `Value::String(_)` inside
    // the `$type == "number"` branch are mutation-survivor magnets: deleting
    // either arm survives unless the test suite exercises BOTH typed-number
    // shapes (numeric value, string-encoded value).

    #[test]
    fn typed_number_with_json_number_value_decodes() {
        // Numeric Value variant — exercises the `Value::Number(n)` arm.
        let val = json_to_fel(&json!({ "$type": "number", "value": 42 }));
        assert_eq!(val, TypeValue::Number(Decimal::from(42)));
    }

    #[test]
    fn typed_number_with_string_value_decodes() {
        // String Value variant (for big-decimals exceeding JS safe-integer
        // range) — exercises the `Value::String(s)` arm. Distinct kill from
        // the json-number path above.
        let val = json_to_fel(&json!({
            "$type": "number",
            "value": "123456789012345678901234567",
        }));
        assert_eq!(
            val,
            TypeValue::Number(Decimal::from_str_exact("123456789012345678901234567").unwrap())
        );
    }

    // ── field_map_from_json_str: shortcut + parse path coverage ──

    #[test]
    fn field_map_from_empty_string_is_empty_map() {
        // Kills `replace fn -> Ok(HashMap::new())` (this asserts the
        // expected result, not just that it's not Err) and the
        // `|| → &&` mutation in the early-return guard.
        let map = field_map_from_json_str("").expect("empty string is valid");
        assert!(map.is_empty());
    }

    #[test]
    fn field_map_from_empty_object_string_is_empty_map() {
        // Kills `replace == with !=` mutation: with `==`, "{}" matches
        // and returns empty; with `!=`, "{}" falls through to JSON parse
        // (which would also produce empty, but via a different code path).
        let map = field_map_from_json_str("{}").expect("'{}' is valid");
        assert!(map.is_empty());
    }

    #[test]
    fn field_map_from_real_json_populates_map() {
        // Kills `replace fn -> Ok(HashMap::new())`: actual non-empty
        // result distinguishes the always-empty mutant.
        let map =
            field_map_from_json_str(r#"{"name": "alice", "age": 30}"#).expect("real JSON is valid");
        assert_eq!(map.len(), 2);
        assert_eq!(
            map.get("name"),
            Some(&TypeValue::String("alice".to_string()))
        );
        assert_eq!(map.get("age"), Some(&TypeValue::Number(Decimal::from(30))));
    }

    #[test]
    fn field_map_from_invalid_json_is_err() {
        // Defensive: the parse-error path is observable.
        let result = field_map_from_json_str("{not valid json");
        assert!(result.is_err());
    }
}