Skip to main content

strata_js/
lib.rs

1//! Strata JS: Porting modern JavaScript frontend paradigms, dynamic typing, and Web APIs into safe Rust.
2//!
3//! # Examples
4//!
5//! ```rust
6//! use strata_js::json::{parse_json, stringify_json};
7//! use strata_js::JsValue;
8//!
9//! let val = parse_json("{\"name\": \"Strata\"}").unwrap();
10//! assert_eq!(val["name"], JsValue::String("Strata".to_string()));
11//! ```
12
13use std::cell::RefCell;
14use std::collections::BTreeMap;
15use std::ops::Index;
16use std::rc::Rc;
17
18pub mod bigint;
19pub mod engine;
20pub mod json;
21pub mod promise;
22pub mod web;
23
24pub use bigint::JsBigInt;
25pub use engine::{
26    Document, DomMutationRecord, DomMutationType, DomNode, DomNodeType, Expr, JsEngine, JsParser,
27    MutationListener, MutationSink, Stmt,
28};
29
30/// Reference handle to an executable JavaScript closure.
31#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub struct ClosureHandle {
33    pub id: u64,
34    pub name: Option<String>,
35}
36
37impl ClosureHandle {
38    pub const fn new(id: u64, name: Option<String>) -> Self {
39        Self { id, name }
40    }
41}
42
43/// Unique ECMAScript Symbol identifier.
44#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
45pub struct SymbolId {
46    pub id: u64,
47    pub description: Option<String>,
48}
49
50impl SymbolId {
51    pub const ITERATOR: u64 = 1;
52    pub const TO_STRING_TAG: u64 = 2;
53    pub const HAS_INSTANCE: u64 = 3;
54    pub const TO_PRIMITIVE: u64 = 4;
55
56    pub const fn new(id: u64, description: Option<String>) -> Self {
57        Self { id, description }
58    }
59
60    pub fn iterator() -> Self {
61        Self {
62            id: Self::ITERATOR,
63            description: Some("Symbol.iterator".to_string()),
64        }
65    }
66
67    pub fn to_string_tag() -> Self {
68        Self {
69            id: Self::TO_STRING_TAG,
70            description: Some("Symbol.toStringTag".to_string()),
71        }
72    }
73
74    pub fn has_instance() -> Self {
75        Self {
76            id: Self::HAS_INSTANCE,
77            description: Some("Symbol.hasInstance".to_string()),
78        }
79    }
80
81    pub fn to_primitive() -> Self {
82        Self {
83            id: Self::TO_PRIMITIVE,
84            description: Some("Symbol.toPrimitive".to_string()),
85        }
86    }
87}
88
89/// Tagged union representing dynamic JavaScript values with authentic ECMAScript reference semantics.
90#[derive(Debug, Clone)]
91pub enum JsValue {
92    Undefined,
93    Null,
94    Bool(bool),
95    Number(f64),
96    String(String),
97    BigInt(JsBigInt),
98    Array(Rc<RefCell<Vec<JsValue>>>),
99    Object(Rc<RefCell<BTreeMap<String, JsValue>>>),
100    Function(ClosureHandle),
101    Symbol(SymbolId),
102    Promise(crate::promise::JsPromise<JsValue>),
103}
104
105impl PartialEq for JsValue {
106    fn eq(&self, other: &Self) -> bool {
107        match (self, other) {
108            (Self::Undefined, Self::Undefined) => true,
109            (Self::Null, Self::Null) => true,
110            (Self::Bool(a), Self::Bool(b)) => a == b,
111            (Self::Number(a), Self::Number(b)) => {
112                if a.is_nan() && b.is_nan() {
113                    true
114                } else {
115                    a == b
116                }
117            }
118            (Self::String(a), Self::String(b)) => a == b,
119            (Self::BigInt(a), Self::BigInt(b)) => a == b,
120            (Self::Function(a), Self::Function(b)) => a.id == b.id,
121            (Self::Symbol(a), Self::Symbol(b)) => a.id == b.id,
122            (Self::Promise(a), Self::Promise(b)) => a == b,
123            (Self::Array(a), Self::Array(b)) => {
124                if Rc::ptr_eq(a, b) {
125                    true
126                } else {
127                    *a.borrow() == *b.borrow()
128                }
129            }
130            (Self::Object(a), Self::Object(b)) => {
131                if Rc::ptr_eq(a, b) {
132                    true
133                } else {
134                    *a.borrow() == *b.borrow()
135                }
136            }
137            _ => false,
138        }
139    }
140}
141
142impl JsValue {
143    /// Parses a JSON string into a `JsValue`.
144    pub fn from_json_str(s: &str) -> Result<Self, String> {
145        json::parse_json(s)
146    }
147
148    /// Serializes this `JsValue` into a standard JSON string.
149    pub fn to_json_string(&self) -> String {
150        json::stringify_json(self).unwrap_or_else(|_| "null".to_string())
151    }
152
153    /// Serializes this `JsValue` into a standard JSON string, returning an error if a cycle is detected.
154    pub fn try_to_json_string(&self) -> Result<String, String> {
155        json::stringify_json(self)
156    }
157
158    /// Returns JavaScript `typeof` string for this value.
159    pub fn js_typeof(&self) -> &'static str {
160        match self {
161            Self::Undefined => "undefined",
162            Self::Null => "object", // Canonical JS specification quirk
163            Self::Bool(_) => "boolean",
164            Self::Number(_) => "number",
165            Self::String(_) => "string",
166            Self::BigInt(_) => "bigint",
167            Self::Array(_) => "object",
168            Self::Function(_) => "function",
169            Self::Symbol(_) => "symbol",
170            Self::Promise(_) => "object",
171            Self::Object(cell) => {
172                let map = cell.borrow();
173                if map.contains_key("__fn__") || map.contains_key("__is_class__") {
174                    "function"
175                } else {
176                    "object"
177                }
178            }
179        }
180    }
181
182    /// Strict equality comparison (`===`) adhering to ECMAScript standard.
183    pub fn strict_eq(&self, other: &Self) -> bool {
184        match (self, other) {
185            (Self::Undefined, Self::Undefined) => true,
186            (Self::Null, Self::Null) => true,
187            (Self::Bool(a), Self::Bool(b)) => a == b,
188            (Self::Number(a), Self::Number(b)) => {
189                if a.is_nan() || b.is_nan() {
190                    false
191                } else {
192                    a == b
193                }
194            }
195            (Self::String(a), Self::String(b)) => a == b,
196            (Self::BigInt(a), Self::BigInt(b)) => a == b,
197            (Self::Function(a), Self::Function(b)) => a.id == b.id,
198            (Self::Symbol(a), Self::Symbol(b)) => a.id == b.id,
199            (Self::Promise(a), Self::Promise(b)) => a == b,
200            (Self::Array(a), Self::Array(b)) => Rc::ptr_eq(a, b),
201            (Self::Object(a), Self::Object(b)) => Rc::ptr_eq(a, b),
202            _ => false,
203        }
204    }
205
206    /// Abstract loose equality comparison (`==`) adhering to ECMAScript standard.
207    pub fn loose_eq(&self, other: &Self) -> bool {
208        match (self, other) {
209            // Same type: delegates to strict equality
210            (Self::Undefined, Self::Undefined)
211            | (Self::Null, Self::Null)
212            | (Self::Bool(_), Self::Bool(_))
213            | (Self::Number(_), Self::Number(_))
214            | (Self::String(_), Self::String(_))
215            | (Self::BigInt(_), Self::BigInt(_))
216            | (Self::Array(_), Self::Array(_))
217            | (Self::Object(_), Self::Object(_))
218            | (Self::Function(_), Self::Function(_))
219            | (Self::Symbol(_), Self::Symbol(_))
220            | (Self::Promise(_), Self::Promise(_)) => self.strict_eq(other),
221
222            // null == undefined -> true
223            (Self::Null, Self::Undefined) | (Self::Undefined, Self::Null) => true,
224
225            // Number == String: convert string to number
226            (Self::Number(n), Self::String(s)) => match s.trim().parse::<f64>() {
227                Ok(parsed) => !n.is_nan() && !parsed.is_nan() && n == &parsed,
228                Err(_) => false,
229            },
230            (Self::String(s), Self::Number(n)) => match s.trim().parse::<f64>() {
231                Ok(parsed) => !n.is_nan() && !parsed.is_nan() && &parsed == n,
232                Err(_) => false,
233            },
234
235            // BigInt == String
236            (Self::BigInt(bi), Self::String(s)) | (Self::String(s), Self::BigInt(bi)) => {
237                if let Ok(parsed) = JsBigInt::parse(s) {
238                    &parsed == bi
239                } else {
240                    false
241                }
242            }
243
244            // BigInt == Number
245            (Self::BigInt(bi), Self::Number(n)) | (Self::Number(n), Self::BigInt(bi)) => {
246                if n.fract() == 0.0 && !n.is_nan() && !n.is_infinite() {
247                    bi.to_decimal_string() == format!("{n}")
248                } else {
249                    false
250                }
251            }
252
253            // Boolean == Any: convert boolean to 1.0 or 0.0
254            (Self::Bool(b), other) => {
255                let num = if *b { 1.0 } else { 0.0 };
256                JsValue::Number(num).loose_eq(other)
257            }
258            (this, Self::Bool(b)) => {
259                let num = if *b { 1.0 } else { 0.0 };
260                this.loose_eq(&JsValue::Number(num))
261            }
262
263            // String/Number == Array: unwrap single-element or join
264            (Self::String(_), Self::Array(arr)) | (Self::Number(_), Self::Array(arr)) => {
265                let joined = arr
266                    .borrow()
267                    .iter()
268                    .map(|v| match v {
269                        JsValue::String(s) => s.clone(),
270                        JsValue::Number(n) => format!("{}", n),
271                        JsValue::Bool(b) => format!("{}", b),
272                        JsValue::BigInt(bi) => bi.to_decimal_string(),
273                        _ => String::new(),
274                    })
275                    .collect::<Vec<_>>()
276                    .join(",");
277                self.loose_eq(&JsValue::String(joined))
278            }
279            (Self::Array(arr), Self::String(_)) | (Self::Array(arr), Self::Number(_)) => {
280                let joined = arr
281                    .borrow()
282                    .iter()
283                    .map(|v| match v {
284                        JsValue::String(s) => s.clone(),
285                        JsValue::Number(n) => format!("{}", n),
286                        JsValue::Bool(b) => format!("{}", b),
287                        JsValue::BigInt(bi) => bi.to_decimal_string(),
288                        _ => String::new(),
289                    })
290                    .collect::<Vec<_>>()
291                    .join(",");
292                JsValue::String(joined).loose_eq(other)
293            }
294
295            _ => false,
296        }
297    }
298
299    pub fn is_null(&self) -> bool {
300        matches!(self, Self::Null)
301    }
302
303    pub fn is_undefined(&self) -> bool {
304        matches!(self, Self::Undefined)
305    }
306
307    pub fn is_truthy(&self) -> bool {
308        match self {
309            Self::Undefined | Self::Null => false,
310            Self::Bool(b) => *b,
311            Self::Number(n) => *n != 0.0 && !n.is_nan(),
312            Self::String(s) => !s.is_empty(),
313            Self::BigInt(bi) => !bi.is_zero(),
314            Self::Array(_)
315            | Self::Object(_)
316            | Self::Function(_)
317            | Self::Symbol(_)
318            | Self::Promise(_) => true,
319        }
320    }
321
322    pub fn is_function(&self) -> bool {
323        matches!(self, Self::Function(_))
324    }
325
326    pub fn is_symbol(&self) -> bool {
327        matches!(self, Self::Symbol(_))
328    }
329
330    pub fn is_promise(&self) -> bool {
331        matches!(self, Self::Promise(_))
332    }
333
334    pub fn as_promise(&self) -> Option<&crate::promise::JsPromise<JsValue>> {
335        match self {
336            Self::Promise(p) => Some(p),
337            _ => None,
338        }
339    }
340
341    pub fn new_promise(p: crate::promise::JsPromise<JsValue>) -> Self {
342        Self::Promise(p)
343    }
344
345    pub fn new_object(map: BTreeMap<String, JsValue>) -> Self {
346        Self::Object(Rc::new(RefCell::new(map)))
347    }
348
349    pub fn new_array(items: Vec<JsValue>) -> Self {
350        Self::Array(Rc::new(RefCell::new(items)))
351    }
352
353    pub fn empty_object() -> Self {
354        Self::Object(Rc::new(RefCell::new(BTreeMap::new())))
355    }
356
357    pub fn empty_array() -> Self {
358        Self::Array(Rc::new(RefCell::new(Vec::new())))
359    }
360
361    pub fn has_prop(&self, key: &str) -> bool {
362        match self {
363            Self::Object(c) => c.borrow().contains_key(key),
364            Self::Array(arr) => {
365                if key == "length" {
366                    return true;
367                }
368                if let Ok(idx) = key.parse::<usize>() {
369                    idx < arr.borrow().len()
370                } else {
371                    false
372                }
373            }
374            _ => false,
375        }
376    }
377
378    pub fn get_prop(&self, key: &str) -> Option<JsValue> {
379        match self {
380            Self::Object(c) => c.borrow().get(key).cloned(),
381            Self::Array(arr) => {
382                if key == "length" {
383                    return Some(JsValue::Number(arr.borrow().len() as f64));
384                }
385                if let Ok(idx) = key.parse::<usize>() {
386                    arr.borrow().get(idx).cloned()
387                } else {
388                    None
389                }
390            }
391            _ => None,
392        }
393    }
394
395    pub fn set_prop(&self, key: impl Into<String>, val: impl Into<JsValue>) -> bool {
396        let k = key.into();
397        let v = val.into();
398        match self {
399            Self::Object(c) => {
400                c.borrow_mut().insert(k, v);
401                true
402            }
403            Self::Array(arr) => {
404                if let Ok(idx) = k.parse::<usize>() {
405                    let mut b = arr.borrow_mut();
406                    if idx >= b.len() {
407                        b.resize(idx + 1, JsValue::Undefined);
408                    }
409                    b[idx] = v;
410                    true
411                } else {
412                    false
413                }
414            }
415            _ => false,
416        }
417    }
418
419    pub fn get_property(&self, key: &str) -> Option<JsValue> {
420        self.get_prop(key)
421    }
422
423    pub fn set_property(&self, key: impl Into<String>, val: impl Into<JsValue>) -> bool {
424        self.set_prop(key, val)
425    }
426
427    pub fn as_closure_handle(&self) -> Option<&ClosureHandle> {
428        match self {
429            Self::Function(h) => Some(h),
430            _ => None,
431        }
432    }
433
434    pub fn as_symbol(&self) -> Option<&SymbolId> {
435        match self {
436            Self::Symbol(s) => Some(s),
437            _ => None,
438        }
439    }
440
441    pub fn as_f64(&self) -> Option<f64> {
442        match self {
443            Self::Number(n) => Some(*n),
444            _ => None,
445        }
446    }
447
448    pub fn as_str(&self) -> Option<&str> {
449        match self {
450            Self::String(s) => Some(s.as_str()),
451            _ => None,
452        }
453    }
454
455    pub fn as_bool(&self) -> Option<bool> {
456        match self {
457            Self::Bool(b) => Some(*b),
458            _ => None,
459        }
460    }
461
462    pub fn as_bigint(&self) -> Option<&JsBigInt> {
463        match self {
464            Self::BigInt(b) => Some(b),
465            _ => None,
466        }
467    }
468
469    pub fn remove_property(&mut self, key: &str) -> Option<JsValue> {
470        match self {
471            Self::Object(cell) => cell.borrow_mut().remove(key),
472            _ => None,
473        }
474    }
475
476    pub fn get_index(&self, index: usize) -> Option<JsValue> {
477        match self {
478            Self::Array(cell) => cell.borrow().get(index).cloned(),
479            _ => None,
480        }
481    }
482
483    pub fn set_index(&mut self, index: usize, val: impl Into<JsValue>) {
484        if let Self::Array(cell) = self {
485            let mut arr = cell.borrow_mut();
486            if index >= arr.len() {
487                arr.resize(index + 1, JsValue::Undefined);
488            }
489            arr[index] = val.into();
490        }
491    }
492
493    pub fn len(&self) -> usize {
494        match self {
495            Self::Array(cell) => cell.borrow().len(),
496            Self::String(s) => s.len(),
497            Self::Object(cell) => cell.borrow().len(),
498            _ => 0,
499        }
500    }
501
502    pub fn is_empty(&self) -> bool {
503        self.len() == 0
504    }
505
506    // ==========================================
507    // JavaScript Array Prototype Methods
508    // ==========================================
509
510    pub fn map<F>(&self, mut f: F) -> Self
511    where
512        F: FnMut(&JsValue) -> JsValue,
513    {
514        match self {
515            Self::Array(cell) => Self::new_array(cell.borrow().iter().map(&mut f).collect()),
516            _ => Self::empty_array(),
517        }
518    }
519
520    pub fn filter<F>(&self, mut f: F) -> Self
521    where
522        F: FnMut(&JsValue) -> bool,
523    {
524        match self {
525            Self::Array(cell) => Self::new_array(
526                cell.borrow()
527                    .iter()
528                    .filter(|item| f(item))
529                    .cloned()
530                    .collect(),
531            ),
532            _ => Self::empty_array(),
533        }
534    }
535
536    pub fn reduce<F>(&self, f: F, initial: JsValue) -> JsValue
537    where
538        F: FnMut(JsValue, &JsValue) -> JsValue,
539    {
540        match self {
541            Self::Array(cell) => cell.borrow().iter().fold(initial, f),
542            _ => initial,
543        }
544    }
545
546    pub fn find<F>(&self, f: F) -> Option<JsValue>
547    where
548        F: Fn(&JsValue) -> bool,
549    {
550        match self {
551            Self::Array(cell) => cell.borrow().iter().find(|item| f(item)).cloned(),
552            _ => None,
553        }
554    }
555
556    pub fn find_index<F>(&self, f: F) -> Option<usize>
557    where
558        F: Fn(&JsValue) -> bool,
559    {
560        match self {
561            Self::Array(cell) => cell.borrow().iter().position(f),
562            _ => None,
563        }
564    }
565
566    pub fn some<F>(&self, f: F) -> bool
567    where
568        F: Fn(&JsValue) -> bool,
569    {
570        match self {
571            Self::Array(cell) => cell.borrow().iter().any(f),
572            _ => false,
573        }
574    }
575
576    pub fn every<F>(&self, f: F) -> bool
577    where
578        F: Fn(&JsValue) -> bool,
579    {
580        match self {
581            Self::Array(cell) => cell.borrow().iter().all(f),
582            _ => false,
583        }
584    }
585
586    pub fn includes(&self, item: &JsValue) -> bool {
587        match self {
588            Self::Array(cell) => cell.borrow().iter().any(|x| x.strict_eq(item)),
589            _ => false,
590        }
591    }
592
593    pub fn slice(&self, start: isize, end: Option<isize>) -> Self {
594        match self {
595            Self::Array(cell) => {
596                let arr = cell.borrow();
597                let len = arr.len() as isize;
598                let actual_start = if start < 0 {
599                    (len + start).max(0) as usize
600                } else {
601                    start.min(len) as usize
602                };
603
604                let actual_end = match end {
605                    Some(e) => {
606                        if e < 0 {
607                            (len + e).max(0) as usize
608                        } else {
609                            e.min(len) as usize
610                        }
611                    }
612                    None => len as usize,
613                };
614
615                if actual_start >= actual_end {
616                    Self::empty_array()
617                } else {
618                    Self::new_array(arr[actual_start..actual_end].to_vec())
619                }
620            }
621            _ => Self::empty_array(),
622        }
623    }
624
625    pub fn join(&self, separator: &str) -> String {
626        match self {
627            Self::Array(cell) => cell
628                .borrow()
629                .iter()
630                .map(|item| match item {
631                    JsValue::String(s) => s.clone(),
632                    JsValue::Number(n) => format!("{}", n),
633                    JsValue::Bool(b) => format!("{}", b),
634                    JsValue::BigInt(bi) => bi.to_decimal_string(),
635                    JsValue::Null | JsValue::Undefined => String::new(),
636                    other => json::stringify_json(other)
637                        .unwrap_or_else(|_| "[object Object]".to_string()),
638                })
639                .collect::<Vec<_>>()
640                .join(separator),
641            _ => String::new(),
642        }
643    }
644
645    pub fn push(&mut self, val: impl Into<JsValue>) {
646        if !matches!(self, Self::Array(_)) {
647            *self = Self::empty_array();
648        }
649        if let Self::Array(cell) = self {
650            cell.borrow_mut().push(val.into());
651        }
652    }
653
654    pub fn pop(&mut self) -> Option<JsValue> {
655        match self {
656            Self::Array(cell) => cell.borrow_mut().pop(),
657            _ => None,
658        }
659    }
660
661    pub fn concat(&self, other: &JsValue) -> Self {
662        let mut result = match self {
663            Self::Array(cell) => cell.borrow().clone(),
664            other_self => vec![other_self.clone()],
665        };
666
667        match other {
668            Self::Array(other_cell) => result.extend(other_cell.borrow().iter().cloned()),
669            other_val => result.push(other_val.clone()),
670        }
671
672        Self::new_array(result)
673    }
674
675    pub fn reverse(&mut self) {
676        if let Self::Array(cell) = self {
677            cell.borrow_mut().reverse();
678        }
679    }
680
681    pub fn sort_by<F>(&mut self, f: F)
682    where
683        F: FnMut(&JsValue, &JsValue) -> std::cmp::Ordering,
684    {
685        if let Self::Array(cell) = self {
686            cell.borrow_mut().sort_by(f);
687        }
688    }
689
690    pub fn flat(&self, depth: usize) -> Self {
691        match self {
692            Self::Array(cell) => {
693                let mut out = Vec::new();
694                flatten_recursive(&cell.borrow(), depth, &mut out);
695                Self::new_array(out)
696            }
697            _ => self.clone(),
698        }
699    }
700}
701
702fn flatten_recursive(arr: &[JsValue], depth: usize, out: &mut Vec<JsValue>) {
703    for item in arr {
704        if depth > 0 {
705            if let JsValue::Array(inner) = item {
706                flatten_recursive(&inner.borrow(), depth - 1, out);
707                continue;
708            }
709        }
710        out.push(item.clone());
711    }
712}
713
714/// Static JavaScript `Object` utility functions.
715pub struct JsObject;
716
717impl JsObject {
718    pub fn keys(val: &JsValue) -> Vec<String> {
719        match val {
720            JsValue::Object(cell) => cell.borrow().keys().cloned().collect(),
721            JsValue::Array(cell) => (0..cell.borrow().len()).map(|i| i.to_string()).collect(),
722            _ => Vec::new(),
723        }
724    }
725
726    pub fn values(val: &JsValue) -> Vec<JsValue> {
727        match val {
728            JsValue::Object(cell) => cell.borrow().values().cloned().collect(),
729            JsValue::Array(cell) => cell.borrow().clone(),
730            _ => Vec::new(),
731        }
732    }
733
734    pub fn entries(val: &JsValue) -> Vec<(String, JsValue)> {
735        match val {
736            JsValue::Object(cell) => cell
737                .borrow()
738                .iter()
739                .map(|(k, v)| (k.clone(), v.clone()))
740                .collect(),
741            JsValue::Array(cell) => cell
742                .borrow()
743                .iter()
744                .enumerate()
745                .map(|(i, v)| (i.to_string(), v.clone()))
746                .collect(),
747            _ => Vec::new(),
748        }
749    }
750
751    pub fn assign(target: &mut JsValue, source: &JsValue) {
752        if !matches!(target, JsValue::Object(_)) {
753            *target = JsValue::empty_object();
754        }
755
756        if let (JsValue::Object(target_cell), JsValue::Object(source_cell)) = (target, source) {
757            let src = source_cell.borrow().clone();
758            let mut tgt = target_cell.borrow_mut();
759            for (k, v) in src {
760                tgt.insert(k, v);
761            }
762        }
763    }
764}
765
766struct SyncJsValue(JsValue);
767unsafe impl Sync for SyncJsValue {}
768static UNDEFINED: SyncJsValue = SyncJsValue(JsValue::Undefined);
769
770impl Index<&str> for JsValue {
771    type Output = JsValue;
772
773    fn index(&self, key: &str) -> &Self::Output {
774        match self {
775            Self::Object(cell) => {
776                let ptr = cell.as_ptr();
777                unsafe { (&*ptr).get(key).unwrap_or(&UNDEFINED.0) }
778            }
779            _ => &UNDEFINED.0,
780        }
781    }
782}
783
784impl Index<usize> for JsValue {
785    type Output = JsValue;
786
787    fn index(&self, index: usize) -> &Self::Output {
788        match self {
789            Self::Array(cell) => {
790                let ptr = cell.as_ptr();
791                unsafe { (&*ptr).get(index).unwrap_or(&UNDEFINED.0) }
792            }
793            _ => &UNDEFINED.0,
794        }
795    }
796}
797
798impl From<bool> for JsValue {
799    fn from(v: bool) -> Self {
800        Self::Bool(v)
801    }
802}
803
804impl From<f64> for JsValue {
805    fn from(v: f64) -> Self {
806        Self::Number(v)
807    }
808}
809
810impl From<f32> for JsValue {
811    fn from(v: f32) -> Self {
812        Self::Number(v as f64)
813    }
814}
815
816impl From<i32> for JsValue {
817    fn from(v: i32) -> Self {
818        Self::Number(v as f64)
819    }
820}
821
822impl From<u32> for JsValue {
823    fn from(v: u32) -> Self {
824        Self::Number(v as f64)
825    }
826}
827
828impl From<i64> for JsValue {
829    fn from(v: i64) -> Self {
830        Self::Number(v as f64)
831    }
832}
833
834impl From<u64> for JsValue {
835    fn from(v: u64) -> Self {
836        Self::Number(v as f64)
837    }
838}
839
840impl From<usize> for JsValue {
841    fn from(v: usize) -> Self {
842        Self::Number(v as f64)
843    }
844}
845
846impl From<isize> for JsValue {
847    fn from(v: isize) -> Self {
848        Self::Number(v as f64)
849    }
850}
851
852impl From<&str> for JsValue {
853    fn from(v: &str) -> Self {
854        Self::String(v.to_string())
855    }
856}
857
858impl From<String> for JsValue {
859    fn from(v: String) -> Self {
860        Self::String(v)
861    }
862}
863
864impl From<&String> for JsValue {
865    fn from(v: &String) -> Self {
866        Self::String(v.clone())
867    }
868}
869
870impl From<Vec<JsValue>> for JsValue {
871    fn from(v: Vec<JsValue>) -> Self {
872        Self::new_array(v)
873    }
874}
875
876impl From<BTreeMap<String, JsValue>> for JsValue {
877    fn from(v: BTreeMap<String, JsValue>) -> Self {
878        Self::new_object(v)
879    }
880}
881
882impl From<JsBigInt> for JsValue {
883    fn from(v: JsBigInt) -> Self {
884        Self::BigInt(v)
885    }
886}
887
888impl<T: Into<JsValue>> From<Option<T>> for JsValue {
889    fn from(opt: Option<T>) -> Self {
890        match opt {
891            Some(val) => val.into(),
892            None => Self::Null,
893        }
894    }
895}
896
897impl std::fmt::Display for JsValue {
898    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
899        match self {
900            Self::Undefined => write!(f, "undefined"),
901            Self::Null => write!(f, "null"),
902            Self::Bool(b) => write!(f, "{b}"),
903            Self::Number(n) => {
904                if n.is_nan() {
905                    write!(f, "NaN")
906                } else if n.is_infinite() {
907                    if *n < 0.0 {
908                        write!(f, "-Infinity")
909                    } else {
910                        write!(f, "Infinity")
911                    }
912                } else if n.fract() == 0.0 && n.abs() <= i64::MAX as f64 {
913                    write!(f, "{}", *n as i64)
914                } else {
915                    write!(f, "{n}")
916                }
917            }
918            Self::String(s) => write!(f, "{s}"),
919            Self::BigInt(b) => write!(f, "{}", b.to_decimal_string()),
920            Self::Array(arr) => {
921                let items: Vec<String> = arr.borrow().iter().map(|item| item.to_string()).collect();
922                write!(f, "{}", items.join(","))
923            }
924            Self::Object(_) => write!(f, "[object Object]"),
925            Self::Function(h) => {
926                let name = h.name.as_deref().unwrap_or("anonymous");
927                write!(f, "function {name}() {{ [native code] }}")
928            }
929            Self::Symbol(s) => {
930                if let Some(ref d) = s.description {
931                    write!(f, "Symbol({d})")
932                } else {
933                    write!(f, "Symbol()")
934                }
935            }
936            Self::Promise(_) => write!(f, "[object Promise]"),
937        }
938    }
939}
940
941impl From<crate::promise::JsPromise<JsValue>> for JsValue {
942    fn from(p: crate::promise::JsPromise<JsValue>) -> Self {
943        Self::Promise(p)
944    }
945}
946
947pub mod prelude {
948    pub use super::bigint::JsBigInt;
949    pub use super::engine::{Document, DomNode, DomNodeType, JsEngine};
950    pub use super::json::{parse_json, stringify_json};
951    pub use super::promise::{
952        drain_microtasks, pending_microtasks_count, queue_microtask, JsPromise, PromiseState,
953    };
954    pub use super::web::*;
955    pub use super::{ClosureHandle, JsObject, JsValue, SymbolId};
956}