ul-next 0.5.4

Ultralight Rust bindings
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
use core::fmt;
use std::{
    ops::Deref,
    sync::{Arc, OnceLock},
};

use crate::Library;

use super::{AsJSValue, JSContext, JSString, JSValue};

// TODO: major hack, not sure how to get access to the Library
//       from inside the trampoline
static LIBRARY: OnceLock<Arc<Library>> = OnceLock::new();

/// Attributes for JavaScript properties.
///
/// Used in [`JSObject::set_property`] and [`JSObject::set_property_for_key`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct JSPropertyAttributes {
    /// Specifies that a property is read-only.
    pub read_only: bool,
    /// Specifies that a property should not be enumerated by `JSPropertyEnumerators`
    /// and JavaScript `for...in` loops.
    pub dont_enum: bool,
    /// Specifies that the delete operation should fail on a property.
    pub dont_delete: bool,
}

impl JSPropertyAttributes {
    /// Creates empty attributes.
    pub fn new() -> Self {
        Self::default()
    }

    /// Specifies that a property is read-only.
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.read_only = read_only;
        self
    }

    /// Specifies that a property should not be enumerated by `JSPropertyEnumerators`
    /// and JavaScript `for...in` loops.
    pub fn dont_enum(mut self, dont_enum: bool) -> Self {
        self.dont_enum = dont_enum;
        self
    }

    /// Specifies that the delete operation should fail on a property.
    pub fn dont_delete(mut self, dont_delete: bool) -> Self {
        self.dont_delete = dont_delete;
        self
    }

    pub(crate) fn to_raw(self) -> u32 {
        let mut raw = 0;

        if self.read_only {
            raw |= ul_sys::kJSPropertyAttributeReadOnly;
        }

        if self.dont_enum {
            raw |= ul_sys::kJSPropertyAttributeDontEnum;
        }

        if self.dont_delete {
            raw |= ul_sys::kJSPropertyAttributeDontDelete;
        }

        raw
    }
}

/// A JavaScript object.
#[derive(Clone, Debug)]
pub struct JSObject<'a> {
    pub(crate) value: JSValue<'a>,
}

impl<'a> JSObject<'a> {
    pub(crate) fn copy_from_raw(ctx: &'a JSContext, obj: ul_sys::JSObjectRef) -> Self {
        assert!(!obj.is_null());

        // add one
        unsafe { ctx.lib.ultralight().JSValueProtect(ctx.internal, obj) };

        Self {
            value: JSValue::from_raw(ctx, obj),
        }
    }

    /// Create a new default javascript object.
    pub fn new(ctx: &'a JSContext) -> Self {
        let obj = unsafe {
            ctx.lib.ultralight().JSObjectMake(
                ctx.internal,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };

        Self {
            value: JSValue::from_raw(ctx, obj),
        }
    }

    /// Create a JavaScript function with a given callback as its implementation.
    ///
    /// Results in a JSObject that is a function. The object's prototype will be the default function prototype.
    ///
    /// This can be used to execute Rust code from JavaScript.
    pub fn new_function_with_callback<F>(ctx: &'a JSContext, callback: F) -> Self
    where
        for<'c> F:
            FnMut(&'c JSContext, &JSObject<'c>, &[JSValue<'c>]) -> Result<JSValue<'c>, JSValue<'c>>,
    {
        LIBRARY.get_or_init(|| ctx.lib.clone());

        unsafe extern "C" fn finalize<Env>(function: ul_sys::JSObjectRef)
        where
            for<'c> Env: FnMut(
                &'c JSContext,
                &JSObject<'c>,
                &[JSValue<'c>],
            ) -> Result<JSValue<'c>, JSValue<'c>>,
        {
            let _guard = scopeguard::guard_on_unwind((), |()| {
                ::std::process::abort();
            });

            let lib = ffi_unwrap!(LIBRARY.get(), "library undefined ptr",);

            let private_data = lib.ultralight().JSObjectGetPrivate(function) as *mut Box<Env>;

            let _ = Box::from_raw(private_data);
        }

        unsafe extern "C" fn trampoline<Env>(
            ctx: ul_sys::JSContextRef,
            function: ul_sys::JSObjectRef,
            this_object: ul_sys::JSObjectRef,
            argument_count: usize,
            arguments: *const ul_sys::JSValueRef,
            exception: *mut ul_sys::JSValueRef,
        ) -> ul_sys::JSValueRef
        where
            for<'c> Env: FnMut(
                &'c JSContext,
                &JSObject<'c>,
                &[JSValue<'c>],
            ) -> Result<JSValue<'c>, JSValue<'c>>,
        {
            let _guard = scopeguard::guard_on_unwind((), |()| {
                ::std::process::abort();
            });

            let lib = ffi_unwrap!(LIBRARY.get(), "library undefined ptr",);

            let private_data = lib.ultralight().JSObjectGetPrivate(function) as *mut Box<Env>;
            let callback: &mut Box<Env> = ffi_unwrap!(private_data.as_mut(), "null ptr",);

            let ctx = JSContext::copy_from_raw(lib.clone(), ctx);
            let this = JSObject::copy_from_raw(&ctx, this_object);
            let args = std::slice::from_raw_parts(arguments, argument_count)
                .iter()
                .map(|v| JSValue::copy_from_raw(&ctx, *v))
                .collect::<Vec<_>>();

            let ret = callback(&ctx, &this, &args);
            match ret {
                Ok(value) => value.into_raw(),
                Err(value) => {
                    if !exception.is_null() {
                        *exception = value.into_raw();
                    }
                    std::ptr::null_mut()
                }
            }
        }

        let c_callback: ul_sys::JSObjectCallAsFunctionCallback = Some(trampoline::<F>);
        let callback_data: *mut Box<F> = Box::into_raw(Box::new(Box::new(callback)));

        let class_def = ul_sys::JSClassDefinition {
            finalize: Some(finalize::<F>),
            callAsFunction: c_callback,
            ..super::class::EMPTY_CLASS_DEF
        };

        let obj = unsafe {
            let class = ctx.lib.ultralight().JSClassCreate(&class_def);

            let obj = ctx
                .lib
                .ultralight()
                .JSObjectMake(ctx.internal, class, callback_data as _);

            ctx.lib.ultralight().JSClassRelease(class);

            obj
        };

        Self {
            value: JSValue::from_raw(ctx, obj),
        }
    }

    /// Creates a function with a given script as its body.
    ///
    /// Use this method when you want to execute a script repeatedly,
    /// to avoid the cost of re-parsing the script before each execution.
    ///
    /// Can return [`Err`] if there was an exception when creating the function or
    /// if the script or parameters contain syntax errors.
    pub fn new_function(
        ctx: &'a JSContext,
        name: Option<&str>,
        param_names: &[&str],
        body: &str,
        source_url: Option<&str>,
        starting_line_number: i32,
    ) -> Result<Self, JSValue<'a>> {
        let mut exception = std::ptr::null();
        let name = name.map(|n| JSString::new(ctx.lib.clone(), n));

        let param_names: Vec<_> = param_names
            .iter()
            .map(|n| JSString::new(ctx.lib.clone(), n))
            .collect();
        let params_ptrs: Vec<_> = param_names.iter().map(|n| n.internal).collect();

        let body = JSString::new(ctx.lib.clone(), body);
        let source_url = source_url.map(|s| JSString::new(ctx.lib.clone(), s));

        let obj = unsafe {
            ctx.lib.ultralight().JSObjectMakeFunction(
                ctx.internal,
                name.map_or(std::ptr::null_mut(), |n| n.internal),
                param_names.len() as _,
                if param_names.is_empty() {
                    std::ptr::null()
                } else {
                    params_ptrs.as_ptr()
                },
                body.internal,
                source_url.map_or(std::ptr::null_mut(), |s| s.internal),
                starting_line_number,
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(ctx, exception))
        } else if obj.is_null() {
            Err(JSValue::new_string(ctx, "Failed to create function"))
        } else {
            Ok(Self {
                value: JSValue::from_raw(ctx, obj),
            })
        }
    }

    /// Creates a JavaScript Array object.
    pub fn new_array(ctx: &'a JSContext, items: &[JSValue]) -> Result<Self, JSValue<'a>> {
        let items_ptrs: Vec<_> = items.iter().map(|v| v.internal).collect();

        let mut exception = std::ptr::null();

        let result = unsafe {
            ctx.lib.ultralight().JSObjectMakeArray(
                ctx.internal,
                items.len() as _,
                items_ptrs.as_ptr(),
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(ctx, exception))
        } else if result.is_null() {
            Err(JSValue::new_string(ctx, "Failed to create array"))
        } else {
            Ok(Self {
                value: JSValue::from_raw(ctx, result),
            })
        }
    }

    /// Tests whether an object can be called as a function.
    pub fn is_function(&self) -> bool {
        unsafe {
            self.value
                .ctx
                .lib
                .ultralight()
                .JSObjectIsFunction(self.value.ctx.internal, self.value.internal as _)
        }
    }

    /// Tests whether an object can be called as a constructor.
    pub fn is_constructor(&self) -> bool {
        unsafe {
            self.value
                .ctx
                .lib
                .ultralight()
                .JSObjectIsConstructor(self.value.ctx.internal, self.value.internal as _)
        }
    }

    /// Calls an object as a function.
    ///
    /// Return the [`JSValue`] that results from calling object as a function,
    /// or [`Err`] if an exception is thrown or object is not a function.
    pub fn call_as_function(
        &self,
        this: Option<&JSObject>,
        args: &[JSValue],
    ) -> Result<JSValue, JSValue> {
        let mut exception = std::ptr::null();

        let args: Vec<_> = args.iter().map(|v| v.internal).collect();

        let result_raw = unsafe {
            self.value.ctx.lib.ultralight().JSObjectCallAsFunction(
                self.value.ctx.internal,
                self.value.internal as _,
                this.map_or(std::ptr::null_mut(), |v| v.internal as _),
                args.len(),
                args.as_ptr(),
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(self.value.ctx, exception))
        } else if result_raw.is_null() {
            Err(JSValue::new_string(
                self.value.ctx,
                "Failed to call function",
            ))
        } else {
            Ok(JSValue::from_raw(self.value.ctx, result_raw))
        }
    }

    /// Calls an object as a constructor.
    ///
    /// Return the [`JSObject`] that results from calling object as a constructor,
    /// or [`Err`] if an exception is thrown or object is not a constructor.
    pub fn call_as_constructor(&self, args: &[JSValue]) -> Result<JSObject, JSValue> {
        let mut exception = std::ptr::null();

        let args: Vec<_> = args.iter().map(|v| v.internal).collect();

        let result_raw = unsafe {
            self.value.ctx.lib.ultralight().JSObjectCallAsConstructor(
                self.value.ctx.internal,
                self.value.internal as _,
                args.len(),
                args.as_ptr(),
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(self.value.ctx, exception))
        } else if result_raw.is_null() {
            Err(JSValue::new_string(
                self.value.ctx,
                "Failed to call constructor",
            ))
        } else {
            Ok(JSObject::copy_from_raw(self.value.ctx, result_raw))
        }
    }
}

impl JSObject<'_> {
    /// Gets a property from an object by name.
    ///
    /// Returns the property's value if object has the property, otherwise the undefined value,
    /// or [`Err`] if an exception is thrown.
    pub fn get_property(&self, name: &str) -> Result<JSValue, JSValue> {
        let name = JSString::new(self.ctx.lib.clone(), name);
        let mut exception = std::ptr::null();

        let result_raw = unsafe {
            self.ctx.lib.ultralight().JSObjectGetProperty(
                self.ctx.internal,
                self.internal as _,
                name.internal,
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else if result_raw.is_null() {
            Err(JSValue::new_string(self.ctx, "Failed to get property"))
        } else {
            Ok(JSValue::from_raw(self.ctx, result_raw))
        }
    }

    /// Gets a property from an object by numeric index.
    ///
    /// Returns the property's value if object has the property, otherwise the undefined value,
    /// or [`Err`] if an exception is thrown.
    ///
    /// Calling [`JSObject::get_property_at_index`] is equivalent to calling [`JSObject::get_property`]
    /// with a string containing `index`, but [`JSObject::get_property_at_index`] provides optimized
    /// access to numeric properties.
    pub fn get_property_at_index(&self, index: u32) -> Result<JSValue, JSValue> {
        let mut exception = std::ptr::null();

        let result_raw = unsafe {
            self.ctx.lib.ultralight().JSObjectGetPropertyAtIndex(
                self.ctx.internal,
                self.internal as _,
                index,
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else if result_raw.is_null() {
            Err(JSValue::new_string(self.ctx, "Failed to get property"))
        } else {
            Ok(JSValue::from_raw(self.ctx, result_raw))
        }
    }

    /// Sets a property on an object by name.
    ///
    /// Returns [`Err`] if an exception is thrown.
    pub fn set_property(
        &self,
        name: &str,
        value: &JSValue,
        attributes: JSPropertyAttributes,
    ) -> Result<(), JSValue> {
        let name = JSString::new(self.ctx.lib.clone(), name);
        let mut exception = std::ptr::null();

        unsafe {
            self.ctx.lib.ultralight().JSObjectSetProperty(
                self.ctx.internal,
                self.internal as _,
                name.internal,
                value.internal,
                attributes.to_raw(),
                &mut exception,
            );
        }

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else {
            Ok(())
        }
    }

    /// Sets a property on an object by numeric index.
    ///
    /// Returns [`Err`] if an exception is thrown.
    ///
    /// Calling [`JSObject::set_property_at_index`] is equivalent to calling
    /// [`JSObject::set_property`] with a string containing `index`,
    /// but [`JSObject::set_property_at_index`] provides optimized access to numeric properties.
    pub fn set_property_at_index(&self, index: u32, value: &JSValue) -> Result<(), JSValue> {
        let mut exception = std::ptr::null();

        unsafe {
            self.ctx.lib.ultralight().JSObjectSetPropertyAtIndex(
                self.ctx.internal,
                self.internal as _,
                index,
                value.internal,
                &mut exception,
            );
        }

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else {
            Ok(())
        }
    }

    /// Gets the names of an object's enumerable properties.
    pub fn get_property_names(&self) -> JSPropertyNameArray {
        let names = unsafe {
            self.ctx
                .lib
                .ultralight()
                .JSObjectCopyPropertyNames(self.ctx.internal, self.internal as _)
        };

        JSPropertyNameArray::from_raw(self.ctx, names)
    }

    /// Tests whether an object has a property.
    pub fn has_property(&self, name: &str) -> bool {
        let name = JSString::new(self.ctx.lib.clone(), name);

        unsafe {
            self.ctx.lib.ultralight().JSObjectHasProperty(
                self.ctx.internal,
                self.internal as _,
                name.internal,
            )
        }
    }

    /// Deletes a property from an object by name.
    ///
    /// Returns `true` if the property was deleted, `false` if the property was not present,
    /// or it had [`JSPropertyAttributes::dont_delete`] set, or [`Err`] if an exception is thrown.
    pub fn delete_property(&self, name: &str) -> Result<bool, JSValue> {
        let name = JSString::new(self.ctx.lib.clone(), name);
        let mut exception = std::ptr::null();

        let result = unsafe {
            self.ctx.lib.ultralight().JSObjectDeleteProperty(
                self.ctx.internal,
                self.internal as _,
                name.internal,
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else {
            Ok(result)
        }
    }

    /// Gets a property from an object using a [`JSValue`] as the property key.
    ///
    /// Returns the property's value if object has the property, otherwise the undefined value,
    /// or [`Err`] if an exception is thrown.
    ///
    /// This function is the same as performing `object[propertyKey](propertyKey)` from JavaScript.
    pub fn get_property_for_key(&self, key: &JSValue) -> Result<JSValue, JSValue> {
        let mut exception = std::ptr::null();

        let result_raw = unsafe {
            self.ctx.lib.ultralight().JSObjectGetPropertyForKey(
                self.ctx.internal,
                self.internal as _,
                key.internal,
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else if result_raw.is_null() {
            Err(JSValue::new_string(self.ctx, "Failed to get property"))
        } else {
            Ok(JSValue::from_raw(self.ctx, result_raw))
        }
    }

    /// Sets a property on an object using a [`JSValue`] as the property key.
    ///
    /// Returns [`Err`] if an exception is thrown.
    ///
    /// This function is the same as performing `object[propertyKey](propertyKey) = value` from JavaScript.
    pub fn set_property_for_key(
        &self,
        key: &JSValue,
        value: &JSValue,
        attributes: JSPropertyAttributes,
    ) -> Result<(), JSValue> {
        let mut exception = std::ptr::null();

        unsafe {
            self.ctx.lib.ultralight().JSObjectSetPropertyForKey(
                self.ctx.internal,
                self.internal as _,
                key.internal,
                value.internal,
                attributes.to_raw(),
                &mut exception,
            );
        }

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else {
            Ok(())
        }
    }

    /// Tests whether an object has a given property using a [`JSValue`] as the property key.
    ///
    /// This function is the same as performing `propertyKey in object` from JavaScript.
    pub fn has_property_for_key(&self, key: &JSValue) -> Result<bool, JSValue> {
        let mut exception = std::ptr::null();

        let result = unsafe {
            self.ctx.lib.ultralight().JSObjectHasPropertyForKey(
                self.ctx.internal,
                self.internal as _,
                key.internal,
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else {
            Ok(result)
        }
    }

    /// Deletes a property from an object using a [`JSValue`] as the property key.
    ///
    /// Returns `true` if the property was deleted, `false` if the property was not present,
    /// or it had [`JSPropertyAttributes::dont_delete`] set, or [`Err`] if an exception is thrown.
    ///
    /// This function is the same as performing `delete object[propertyKey](propertyKey)` from JavaScript.
    pub fn delete_property_for_key(&self, key: &JSValue) -> Result<bool, JSValue> {
        let mut exception = std::ptr::null();

        let result = unsafe {
            self.ctx.lib.ultralight().JSObjectDeletePropertyForKey(
                self.ctx.internal,
                self.internal as _,
                key.internal,
                &mut exception,
            )
        };

        if !exception.is_null() {
            Err(JSValue::from_raw(self.ctx, exception))
        } else {
            Ok(result)
        }
    }
}

impl<'a> AsRef<JSValue<'a>> for JSObject<'a> {
    fn as_ref(&self) -> &JSValue<'a> {
        &self.value
    }
}

impl<'a> Deref for JSObject<'a> {
    type Target = JSValue<'a>;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<'a> AsJSValue<'a> for JSObject<'a> {
    fn into_value(self) -> JSValue<'a> {
        self.value
    }

    fn as_value(&self) -> &JSValue<'a> {
        &self.value
    }
}

/// A reference to an array of property names.
///
/// This is created by [`JSObject::get_property_names`].
pub struct JSPropertyNameArray<'a> {
    internal: ul_sys::JSPropertyNameArrayRef,
    ctx: &'a JSContext,
}

impl<'a> JSPropertyNameArray<'a> {
    pub(crate) fn from_raw(ctx: &'a JSContext, array: ul_sys::JSPropertyNameArrayRef) -> Self {
        assert!(!array.is_null());

        Self {
            internal: array,
            ctx,
        }
    }

    /// Returns `true` if the array is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the number of property names in the array.
    pub fn len(&self) -> usize {
        unsafe {
            self.ctx
                .lib
                .ultralight()
                .JSPropertyNameArrayGetCount(self.internal)
        }
    }

    /// Gets a property name at a given index.
    pub fn get(&self, index: usize) -> Option<JSString> {
        let name = unsafe {
            self.ctx
                .lib
                .ultralight()
                .JSPropertyNameArrayGetNameAtIndex(self.internal, index)
        };

        if name.is_null() {
            None
        } else {
            Some(JSString::copy_from_raw(self.ctx.lib.clone(), name))
        }
    }

    /// Converts the array into a [`Vec`] of property names.
    pub fn into_vec(self) -> Vec<String> {
        self.into()
    }
}

impl From<JSPropertyNameArray<'_>> for Vec<String> {
    fn from(array: JSPropertyNameArray) -> Self {
        let mut names = Vec::with_capacity(array.len());

        for i in 0..array.len() {
            let name = array
                .get(i)
                .expect("Array should still have elements")
                .to_string();
            names.push(name);
        }

        names
    }
}

impl Clone for JSPropertyNameArray<'_> {
    fn clone(&self) -> Self {
        let array = unsafe {
            self.ctx
                .lib
                .ultralight()
                .JSPropertyNameArrayRetain(self.internal)
        };

        Self {
            internal: array,
            ctx: self.ctx,
        }
    }
}

impl fmt::Debug for JSPropertyNameArray<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.clone().into_vec().fmt(f)
    }
}

impl Drop for JSPropertyNameArray<'_> {
    fn drop(&mut self) {
        unsafe {
            self.ctx
                .lib
                .ultralight()
                .JSPropertyNameArrayRelease(self.internal);
        }
    }
}