rong_core 0.3.1

Core runtime types for RongJS
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! Error-related public API (stable codes + boundary types).
//!
//! This module exists to provide a single, ergonomic import path:
//! - `rong::error::E_IO`
//! - `rong::error::HostError`

// Stable error codes used at the Rust ↔ JS boundary.
//
// Prefer importing these constants instead of hardcoding `"E_..."` strings, to avoid typos and to
// make refactors easier. Module-specific codes (e.g. `"FS_IO"`) should live in the module crate.
pub const E_ABORT: &str = "E_ABORT";
pub const E_ALREADY_EXISTS: &str = "E_ALREADY_EXISTS";
pub const E_COMPILE: &str = "E_COMPILE";
pub const E_ERROR: &str = "E_ERROR";
pub const E_ILLEGAL_CONSTRUCTOR: &str = "E_ILLEGAL_CONSTRUCTOR";
pub const E_INTERNAL: &str = "E_INTERNAL";
pub const E_INVALID_ARG: &str = "E_INVALID_ARG";
pub const E_INVALID_DATA: &str = "E_INVALID_DATA";
pub const E_INVALID_STATE: &str = "E_INVALID_STATE";
pub const E_IO: &str = "E_IO";
pub const E_JS_THROWN: &str = "E_JS_THROWN";
pub const E_MISSING_PROPERTY: &str = "E_MISSING_PROPERTY";
pub const E_NETWORK: &str = "E_NETWORK";
pub const E_NOT_ARRAY: &str = "E_NOT_ARRAY";
pub const E_NOT_ARRAY_BUFFER: &str = "E_NOT_ARRAY_BUFFER";
pub const E_NOT_EXCEPTION: &str = "E_NOT_EXCEPTION";
pub const E_NOT_FOUND: &str = "E_NOT_FOUND";
pub const E_NOT_FUNCTION: &str = "E_NOT_FUNCTION";
pub const E_NOT_SUPPORTED: &str = "E_NOT_SUPPORTED";
pub const E_NOT_TYPED_ARRAY: &str = "E_NOT_TYPED_ARRAY";
pub const E_OUT_OF_RANGE: &str = "E_OUT_OF_RANGE";
pub const E_PERMISSION_DENIED: &str = "E_PERMISSION_DENIED";
pub const E_STREAM: &str = "E_STREAM";
pub const E_TIMEOUT: &str = "E_TIMEOUT";
pub const E_TYPE: &str = "E_TYPE";

use crate::context::thrown_store::ThrownValueHandle;
use crate::{
    FromJSValue, IntoJSValue, JSArray, JSArrayOps, JSContext, JSContextImpl, JSErrorFactory,
    JSExceptionThrower, JSObject, JSObjectOps, JSValue, JSValueImpl,
};
use std::collections::{BTreeMap, HashMap};
use thiserror::Error;
use tokio::sync::oneshot;

pub type JSResult<T> = Result<T, RongJSError>;

pub fn illegal_constructor<T>(message: impl Into<String>) -> JSResult<T> {
    Err(HostError::type_error(E_ILLEGAL_CONSTRUCTOR, message).into())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorNumber {
    I64(i64),
    U64(u64),
    F64(u64),
}

impl ErrorNumber {
    pub fn from_f64(n: f64) -> Self {
        Self::F64(n.to_bits())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorData {
    Null,
    Bool(bool),
    Number(ErrorNumber),
    String(String),
    Array(Vec<ErrorData>),
    Object(BTreeMap<String, ErrorData>),
}

impl ErrorData {
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(s) => Some(s.as_str()),
            _ => None,
        }
    }
}

impl From<bool> for ErrorData {
    fn from(v: bool) -> Self {
        Self::Bool(v)
    }
}

impl From<String> for ErrorData {
    fn from(v: String) -> Self {
        Self::String(v)
    }
}

impl From<&str> for ErrorData {
    fn from(v: &str) -> Self {
        Self::String(v.to_string())
    }
}

impl From<f64> for ErrorData {
    fn from(v: f64) -> Self {
        Self::Number(ErrorNumber::from_f64(v))
    }
}

impl From<f32> for ErrorData {
    fn from(v: f32) -> Self {
        Self::from(v as f64)
    }
}

impl From<i64> for ErrorData {
    fn from(v: i64) -> Self {
        Self::Number(ErrorNumber::I64(v))
    }
}

impl From<i32> for ErrorData {
    fn from(v: i32) -> Self {
        Self::from(v as i64)
    }
}

impl From<i16> for ErrorData {
    fn from(v: i16) -> Self {
        Self::from(v as i64)
    }
}

impl From<i8> for ErrorData {
    fn from(v: i8) -> Self {
        Self::from(v as i64)
    }
}

impl From<isize> for ErrorData {
    fn from(v: isize) -> Self {
        Self::from(v as i64)
    }
}

impl From<u64> for ErrorData {
    fn from(v: u64) -> Self {
        Self::Number(ErrorNumber::U64(v))
    }
}

impl From<u32> for ErrorData {
    fn from(v: u32) -> Self {
        Self::from(v as u64)
    }
}

impl From<u16> for ErrorData {
    fn from(v: u16) -> Self {
        Self::from(v as u64)
    }
}

impl From<u8> for ErrorData {
    fn from(v: u8) -> Self {
        Self::from(v as u64)
    }
}

impl From<usize> for ErrorData {
    fn from(v: usize) -> Self {
        Self::from(v as u64)
    }
}

impl<T> From<Option<T>> for ErrorData
where
    T: Into<ErrorData>,
{
    fn from(v: Option<T>) -> Self {
        match v {
            Some(value) => value.into(),
            None => Self::Null,
        }
    }
}

impl<T> From<Vec<T>> for ErrorData
where
    T: Into<ErrorData>,
{
    fn from(v: Vec<T>) -> Self {
        Self::Array(v.into_iter().map(Into::into).collect())
    }
}

impl<T, const N: usize> From<[T; N]> for ErrorData
where
    T: Into<ErrorData>,
{
    fn from(v: [T; N]) -> Self {
        Self::Array(v.into_iter().map(Into::into).collect())
    }
}

impl<T> From<BTreeMap<String, T>> for ErrorData
where
    T: Into<ErrorData>,
{
    fn from(v: BTreeMap<String, T>) -> Self {
        Self::Object(v.into_iter().map(|(k, value)| (k, value.into())).collect())
    }
}

impl<T> From<HashMap<String, T>> for ErrorData
where
    T: Into<ErrorData>,
{
    fn from(v: HashMap<String, T>) -> Self {
        Self::Object(v.into_iter().map(|(k, value)| (k, value.into())).collect())
    }
}

#[macro_export]
macro_rules! err_data {
    (null) => {
        $crate::error::ErrorData::Null
    };
    (true) => {
        $crate::error::ErrorData::Bool(true)
    };
    (false) => {
        $crate::error::ErrorData::Bool(false)
    };

    ([$($tt:tt)*]) => {{
        let mut vec = ::std::vec::Vec::<$crate::error::ErrorData>::new();
        $crate::err_data!(@array vec $($tt)*);
        $crate::error::ErrorData::Array(vec)
    }};

    ({$($tt:tt)*}) => {{
        let mut map = ::std::collections::BTreeMap::<::std::string::String, $crate::error::ErrorData>::new();
        $crate::err_data!(@object map $($tt)*);
        $crate::error::ErrorData::Object(map)
    }};

    (@array $vec:ident) => {};
    (@array $vec:ident , $($rest:tt)*) => {
        $crate::err_data!(@array $vec $($rest)*);
    };
    (@array $vec:ident $value:tt , $($rest:tt)*) => {{
        $vec.push($crate::err_data!($value));
        $crate::err_data!(@array $vec $($rest)*);
    }};
    (@array $vec:ident $value:tt) => {{
        $vec.push($crate::err_data!($value));
    }};

    (@object $map:ident) => {};
    (@object $map:ident , $($rest:tt)*) => {
        $crate::err_data!(@object $map $($rest)*);
    };
    (@object $map:ident $key:tt : $value:tt , $($rest:tt)*) => {{
        $map.insert($crate::err_data!(@key $key), $crate::err_data!($value));
        $crate::err_data!(@object $map $($rest)*);
    }};
    (@object $map:ident $key:tt : $value:tt) => {{
        $map.insert($crate::err_data!(@key $key), $crate::err_data!($value));
    }};

    (@key $key:ident) => {
        ::std::string::ToString::to_string(stringify!($key))
    };
    (@key $key:literal) => {
        ::std::string::ToString::to_string($key)
    };

    ($other:expr) => {
        $crate::error::ErrorData::from($other)
    };
}

#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error("{code}: {message}")]
pub struct HostError {
    pub name: &'static str,
    pub code: &'static str,
    pub message: String,
    pub data: Option<ErrorData>,
    pub(crate) thrown: Option<ThrownValueHandle>,
}

impl HostError {
    pub fn new(code: &'static str, message: impl Into<String>) -> Self {
        Self {
            name: "Error",
            code,
            message: message.into(),
            data: None,
            thrown: None,
        }
    }

    pub(crate) fn type_error(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(code, message).with_name("TypeError")
    }

    pub(crate) fn range_error(code: &'static str, message: impl Into<String>) -> Self {
        Self::new(code, message).with_name("RangeError")
    }

    pub fn invalid_arg_count(expected: u32, got: u32) -> Self {
        Self::type_error(
            E_INVALID_ARG,
            format!("{expected} arguments required, but {got} found"),
        )
        .with_data(crate::err_data!({ expected: expected, got: got }))
    }

    pub(crate) fn not_array() -> Self {
        Self::type_error(E_NOT_ARRAY, "Not JS Array")
    }

    pub(crate) fn not_array_buffer() -> Self {
        Self::type_error(E_NOT_ARRAY_BUFFER, "Not JS ArrayBuffer")
    }

    pub(crate) fn not_exception() -> Self {
        Self::type_error(E_NOT_EXCEPTION, "Not JS Exception")
    }

    pub(crate) fn not_function() -> Self {
        Self::type_error(E_NOT_FUNCTION, "Not JS Function")
    }

    pub(crate) fn not_object() -> Self {
        Self::type_error(E_TYPE, "Not JS Object")
    }

    pub(crate) fn not_symbol() -> Self {
        Self::type_error(E_TYPE, "Not JS Symbol")
    }

    pub(crate) fn not_proxy() -> Self {
        Self::type_error(E_TYPE, "Not JS Proxy")
    }

    pub(crate) fn not_typed_array() -> Self {
        Self::type_error(E_NOT_TYPED_ARRAY, "Not JS TypedArray")
    }

    pub(crate) fn property_not_found(name: impl std::fmt::Display) -> Self {
        Self::new(E_MISSING_PROPERTY, format!("Property '{name}' Not Found"))
            .with_name("ReferenceError")
    }

    pub(crate) fn once_fn_called() -> Self {
        Self::new(E_INVALID_STATE, "OnceFn had been called")
    }

    pub(crate) fn typed_array_kind_mismatch(
        expected: impl std::fmt::Debug,
        actual: impl std::fmt::Debug,
    ) -> Self {
        Self::type_error(
            E_TYPE,
            format!(
                "TypedArray kind mismatch: expected {:?}, got {:?}",
                expected, actual
            ),
        )
    }

    pub(crate) fn typed_array_alignment_error() -> Self {
        Self::range_error(
            E_OUT_OF_RANGE,
            "Invalid TypedArray alignment: byte_offset must be a multiple of element size",
        )
    }

    pub(crate) fn typed_array_range_error() -> Self {
        Self::range_error(
            E_OUT_OF_RANGE,
            "Invalid TypedArray range: offset or length exceeds buffer size",
        )
    }

    pub fn with_name(mut self, name: &'static str) -> Self {
        self.name = name;
        self
    }

    pub fn with_data<D>(mut self, data: D) -> Self
    where
        D: Into<ErrorData>,
    {
        self.data = Some(data.into());
        self
    }

    pub fn aborted(reason: Option<String>) -> Self {
        let mut err = Self::new(E_ABORT, "Operation aborted").with_name("AbortError");
        if let Some(reason) = reason {
            err.data = Some(crate::err_data!({ reason: reason }));
        }
        err
    }
}

/// Opaque handle to a JS-thrown/rejected payload captured inside a specific `JSContext`.
///
/// The payload can be any JS value (including primitives). You cannot construct this type directly;
/// use `RongJSError::from_thrown_value`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct ThrownValue {
    handle: ThrownValueHandle,
}

#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[error(transparent)]
pub struct RongJSError(pub(crate) RongJSErrorKind);

#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub(crate) enum RongJSErrorKind {
    /// Host-originated failure that must be surfaced to JS as an `Error` object.
    #[error("{0}")]
    Host(HostError),

    /// Thrown/rejected JS payload (can be any JS value, including primitives).
    #[error("JavaScript threw a value")]
    Thrown(ThrownValue),
}

impl RongJSError {
    fn error_data_to_js_value<V>(ctx: &JSContext<V::Context>, data: &ErrorData) -> JSValue<V>
    where
        V: JSValueImpl + JSObjectOps + JSArrayOps,
    {
        const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;

        match data {
            ErrorData::Null => JSValue::null(ctx),
            ErrorData::Bool(b) => JSValue::from_rust(ctx, *b),
            ErrorData::String(s) => JSValue::from_rust(ctx, s.as_str()),
            ErrorData::Number(n) => match *n {
                ErrorNumber::I64(v) => {
                    let abs = v.unsigned_abs();
                    if abs <= MAX_SAFE_INTEGER {
                        JSValue::from_rust(ctx, v as f64)
                    } else {
                        JSValue::from_rust(ctx, v.to_string())
                    }
                }
                ErrorNumber::U64(v) => {
                    if v <= MAX_SAFE_INTEGER {
                        JSValue::from_rust(ctx, v as f64)
                    } else {
                        JSValue::from_rust(ctx, v.to_string())
                    }
                }
                ErrorNumber::F64(bits) => JSValue::from_rust(ctx, f64::from_bits(bits)),
            },
            ErrorData::Array(items) => {
                let Ok(array) = JSArray::<V>::new(ctx) else {
                    return JSValue::undefined(ctx);
                };
                for (i, item) in items.iter().enumerate() {
                    let _ = array.set(i as u32, Self::error_data_to_js_value::<V>(ctx, item));
                }
                JSValue::from_rust(ctx, array)
            }
            ErrorData::Object(map) => {
                let obj = JSObject::<V>::new(ctx);
                for (k, v) in map.iter() {
                    let _ = obj.set(k.as_str(), Self::error_data_to_js_value::<V>(ctx, v));
                }
                JSValue::from_rust(ctx, obj)
            }
        }
    }

    fn host_error_object<V>(host: &HostError, ctx: &JSContext<V::Context>) -> JSObject<V>
    where
        V: JSValueImpl + JSObjectOps + JSArrayOps,
        V::Context: JSErrorFactory,
    {
        let raw = ctx
            .as_ref()
            .new_error(host.name, &host.message, Some(host.code));
        let obj = JSObject::from_js_value(ctx, JSValue::from_raw(ctx, raw)).unwrap();

        if host.code == E_JS_THROWN {
            let data_obj = host
                .data
                .as_ref()
                .and_then(|data| Self::error_data_to_js_value::<V>(ctx, data).into_object())
                .unwrap_or_else(|| JSObject::new(ctx));

            if let Some(handle) = host.thrown
                && let Some(thrown) = ctx.resolve_thrown(handle)
            {
                let _ = data_obj.set("thrown", thrown.clone());
                if thrown.is_error() {
                    let _ = obj.set("cause", thrown);
                }
            }

            let _ = obj.set("data", data_obj);
        } else if let Some(data) = host.data.as_ref() {
            let _ = obj.set("data", Self::error_data_to_js_value::<V>(ctx, data));
        }

        obj
    }

    pub fn into_host_in<C>(self, ctx: &JSContext<C>) -> Self
    where
        C: JSContextImpl,
        C::Value: JSObjectOps,
    {
        match self.0 {
            RongJSErrorKind::Host(host) => Self(RongJSErrorKind::Host(host)),
            RongJSErrorKind::Thrown(thrown) => {
                let handle = thrown.handle;
                let thrown = ctx.resolve_thrown(handle);

                let mut data = BTreeMap::<String, ErrorData>::new();
                if let Some(thrown) = &thrown {
                    if let Ok(s) = String::from_js_value(ctx, thrown.clone()) {
                        data.insert("thrown".to_string(), ErrorData::from(s));
                    }
                    data.insert("is_error".to_string(), ErrorData::from(thrown.is_error()));
                } else {
                    data.insert("thrown".to_string(), ErrorData::from("<unavailable>"));
                }

                let message = thrown
                    .clone()
                    .and_then(|v| {
                        v.into_object()
                            .and_then(|o| o.get::<_, String>("message").ok())
                    })
                    .or_else(|| thrown.and_then(|v| String::from_js_value(ctx, v).ok()))
                    .unwrap_or_else(|| "JavaScript threw a value".to_string());

                Self(RongJSErrorKind::Host(HostError {
                    name: "Error",
                    code: E_JS_THROWN,
                    message,
                    data: Some(ErrorData::Object(data)),
                    thrown: Some(handle),
                }))
            }
        }
    }

    pub fn throw_js_exception<V>(self, ctx: &JSContext<V::Context>) -> V
    where
        V: JSValueImpl + JSObjectOps + JSArrayOps,
        V::Context: JSErrorFactory + JSExceptionThrower,
    {
        match self.0 {
            RongJSErrorKind::Thrown(thrown) => {
                let handle = thrown.handle;
                let Some(value) = ctx.take_thrown(handle) else {
                    let raw = ctx.as_ref().new_error(
                        "Error",
                        "Invalid thrown value handle",
                        Some(E_INTERNAL),
                    );
                    return ctx.as_ref().throw(raw);
                };
                ctx.throw(value).into_value()
            }

            RongJSErrorKind::Host(host) => {
                let obj = Self::host_error_object::<V>(&host, ctx);
                if host.code == E_JS_THROWN
                    && let Some(handle) = host.thrown
                {
                    let _ = ctx.take_thrown(handle);
                }
                ctx.as_ref().throw(obj.into_value())
            }
        }
    }

    /// Converts an error into a JS value suitable as a `catch` payload / Promise reject reason.
    ///
    /// This does **not** enter the exception channel.
    pub fn into_catch_value<V>(self, ctx: &JSContext<V::Context>) -> JSValue<V>
    where
        V: JSValueImpl + JSObjectOps + JSArrayOps,
        V::Context: JSErrorFactory,
    {
        match self.0 {
            RongJSErrorKind::Thrown(thrown) => {
                let handle = thrown.handle;
                let Some(value) = ctx.take_thrown(handle) else {
                    let raw = ctx.as_ref().new_error(
                        "Error",
                        "Invalid thrown value handle",
                        Some(E_INTERNAL),
                    );
                    return JSValue::from_raw(ctx, raw);
                };
                value
            }
            RongJSErrorKind::Host(host) => {
                let obj = Self::host_error_object::<V>(&host, ctx);
                if host.code == E_JS_THROWN
                    && let Some(handle) = host.thrown
                {
                    let _ = ctx.take_thrown(handle);
                }
                obj.into_js_value()
            }
        }
    }

    /// Creates a `Thrown` error from a JS value that originated from JavaScript
    /// (e.g. exception payload / Promise reject reason / abort reason).
    pub fn from_thrown_value<V: JSValueImpl>(value: JSValue<V>) -> Self {
        let ctx: JSContext<V::Context> =
            JSContext::from_borrowed_raw_ptr(value.as_value().as_raw_context());
        Self(RongJSErrorKind::Thrown(ThrownValue {
            handle: ctx.capture_thrown(value),
        }))
    }

    pub fn thrown_value<C>(&self, ctx: &JSContext<C>) -> Option<JSValue<C::Value>>
    where
        C: JSContextImpl,
    {
        match &self.0 {
            RongJSErrorKind::Thrown(thrown) => ctx.resolve_thrown(thrown.handle),
            _ => None,
        }
    }

    pub fn as_host_error(&self) -> Option<&HostError> {
        match &self.0 {
            RongJSErrorKind::Host(host) => Some(host),
            RongJSErrorKind::Thrown(_) => None,
        }
    }

    pub fn into_host_error(self) -> Option<HostError> {
        match self.0 {
            RongJSErrorKind::Host(host) => Some(host),
            RongJSErrorKind::Thrown(_) => None,
        }
    }

    pub fn is_thrown(&self) -> bool {
        matches!(self.0, RongJSErrorKind::Thrown(_))
    }

    pub fn is_property_not_found(&self) -> bool {
        matches!(self.0, RongJSErrorKind::Host(ref host) if host.code == E_MISSING_PROPERTY)
    }

    pub fn is_not_support_bytecode(&self) -> bool {
        match &self.0 {
            RongJSErrorKind::Host(host) if host.code == E_NOT_SUPPORTED => matches!(
                host.data.as_ref(),
                Some(ErrorData::Object(map))
                    if map.get("feature").and_then(|v| v.as_str()) == Some("bytecode")
            ),
            _ => false,
        }
    }
}

impl<V: JSValueImpl> FromJSValue<V> for RongJSError
where
    V: JSObjectOps,
{
    fn from_js_value(_ctx: &JSContext<V::Context>, value: JSValue<V>) -> JSResult<Self> {
        Ok(RongJSError::from_thrown_value(value))
    }
}

impl<V: JSValueImpl> IntoJSValue<V> for RongJSError
where
    V::Context: JSErrorFactory + JSExceptionThrower,
    V: JSObjectOps + JSArrayOps,
{
    fn into_js_value(self, ctx: &JSContext<V::Context>) -> JSValue<V> {
        JSValue::from_raw(ctx, self.throw_js_exception(ctx))
    }
}

impl From<HostError> for RongJSError {
    fn from(err: HostError) -> Self {
        RongJSError(RongJSErrorKind::Host(err))
    }
}

impl<V, T> IntoJSValue<V> for JSResult<T>
where
    V: JSObjectOps + JSArrayOps,
    V::Context: JSErrorFactory + JSExceptionThrower,
    T: IntoJSValue<V>,
{
    fn into_js_value(self, ctx: &JSContext<V::Context>) -> JSValue<V> {
        match self {
            Ok(value) => <T as IntoJSValue<V>>::into_js_value(value, ctx),
            Err(err) => err.into_js_value(ctx),
        }
    }
}

impl From<oneshot::error::RecvError> for RongJSError {
    fn from(err: oneshot::error::RecvError) -> Self {
        HostError::new(E_INTERNAL, format!("Tokio oneshot error: {}", err)).into()
    }
}

impl From<std::io::Error> for RongJSError {
    fn from(err: std::io::Error) -> Self {
        HostError::new(E_IO, err.to_string()).into()
    }
}