rust_jsc 0.5.0

High-level bindings to JavaScriptCore
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
use crate::{
    JSClass, JSContext, JSContextGroup, JSObject, JSResult, JSString, JSStringProctected,
    JSValue, PrivateDataWrapper,
};
use rust_jsc_sys::{
    InspectorMessageCallback, InspectorPauseEventCallback, JSAPIModuleLoader,
    JSCheckScriptSyntax, JSContextGetGlobalContext, JSContextGetGlobalObject,
    JSContextGetGroup, JSContextGetSharedData, JSContextGroupCreate, JSContextGroupRef,
    JSContextGroupRelease, JSContextRef, JSContextSetSharedData, JSEvaluateScript,
    JSGarbageCollect, JSGetMemoryUsageStatistics, JSGlobalContextCopyName,
    JSGlobalContextCreate, JSGlobalContextCreateInGroup, JSGlobalContextIsInspectable,
    JSGlobalContextRef, JSGlobalContextRelease, JSGlobalContextSetInspectable,
    JSGlobalContextSetName, JSGlobalContextSetUncaughtExceptionAtEventLoopCallback,
    JSGlobalContextSetUncaughtExceptionHandler,
    JSGlobalContextSetUnhandledRejectionCallback, JSInspectorDisconnect,
    JSInspectorIsConnected, JSInspectorSendMessage, JSInspectorSetCallback,
    JSInspectorSetPauseEventCallback, JSLinkAndEvaluateModule, JSLoadAndEvaluateModule,
    JSLoadAndEvaluateModuleFromSource, JSLoadModule, JSLoadModuleFromSource,
    JSSetAPIModuleLoader, JSSetSyntheticModuleKeys, JSStringRef,
    JSUncaughtExceptionAtEventLoop, JSUncaughtExceptionHandler, JSValueRef,
};
use std::ffi::CString;

impl JSContextGroup {
    pub fn new_context(&self) -> JSContext {
        let ctx = unsafe {
            JSGlobalContextCreateInGroup(self.context_group, std::ptr::null_mut())
        };
        JSContext::from(ctx)
    }

    pub fn new_context_with_class(&self, class: &JSClass) -> JSContext {
        let ctx =
            unsafe { JSGlobalContextCreateInGroup(self.context_group, class.inner) };
        JSContext::from(ctx)
    }

    /// Creates a new `JSContextGroup` object.
    pub fn new() -> Self {
        let context_group = unsafe { JSContextGroupCreate() };
        Self { context_group }
    }
}

impl From<JSContextGroupRef> for JSContextGroup {
    fn from(group: JSContextGroupRef) -> Self {
        Self {
            context_group: group,
        }
    }
}

impl Drop for JSContextGroup {
    fn drop(&mut self) {
        unsafe {
            JSContextGroupRelease(self.context_group);
        }
    }
}

impl std::fmt::Debug for JSContextGroup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JSContextGroup").finish()
    }
}

/// Debugger pause-loop events emitted by JavaScriptCore while debugging.
///
/// - `Paused`: debugger just entered paused state (breakpoint, `debugger;`, etc.)
/// - `Resumed`: debugger just resumed execution
/// - `Tick`: called repeatedly while the debugger is paused (nested run loop)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InspectorPauseEvent {
    Paused,
    Resumed,
    Tick,
}

impl JSContext {
    /// Creates a new `JSContext` object.
    ///
    /// Gets a new global context of a JavaScript execution context.
    ///
    /// # Examples
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ```
    pub fn new() -> Self {
        let ctx = unsafe { JSGlobalContextCreate(std::ptr::null_mut()) };
        Self { inner: ctx }
    }

    pub fn new_with(class: &JSClass) -> Self {
        let ctx = unsafe { JSGlobalContextCreate(class.inner) };
        Self { inner: ctx }
    }

    /// Garbage collects the JavaScript execution context.
    ///
    /// e.g.
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.garbage_collect();
    /// ```
    pub fn garbage_collect(&self) {
        unsafe { JSGarbageCollect(self.inner) }
    }

    /// Gets the memory usage statistics of a JavaScript execution context.
    ///
    /// # Examples
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let memory_usage_statistics = ctx.get_memory_usage();
    /// let heap_size = memory_usage_statistics.get_property("heapSize").unwrap().as_number().unwrap();
    /// let heap_capacity = memory_usage_statistics.get_property("heapCapacity").unwrap().as_number().unwrap();
    /// let extra_memory_size = memory_usage_statistics.get_property("extraMemorySize").unwrap().as_number().unwrap();
    /// let object_count = memory_usage_statistics.get_property("objectCount").unwrap().as_number().unwrap();
    /// let protected_object_count = memory_usage_statistics.get_property("protectedObjectCount").unwrap().as_number().unwrap();
    /// let global_object_count = memory_usage_statistics.get_property("globalObjectCount").unwrap().as_number().unwrap();
    /// let protected_global_object_count = memory_usage_statistics.get_property("protectedGlobalObjectCount").unwrap().as_number().unwrap();
    /// let object_type_counts = memory_usage_statistics.get_property("objectTypeCounts").unwrap().as_object().unwrap();
    ///
    /// println!("Heap size: {}", heap_size);
    /// println!("Heap capacity: {}", heap_capacity);
    /// println!("Extra memory size: {}", extra_memory_size);
    /// println!("Object count: {}", object_count);
    /// println!("Protected object count: {}", protected_object_count);
    /// println!("Global object count: {}", global_object_count);
    /// println!("Protected global object count: {}", protected_global_object_count);
    /// ```
    ///
    /// # Returns
    ///
    /// Returns a `JSObject` object.
    /// The object contains the following properties:
    ///     heapSize - The size of the heap.
    ///     heapCapacity - The total size of the heap.
    ///     extraMemorySize - The size of the extra memory.
    ///     objectCount - The number of objects.
    ///     protectedObjectCount - The number of protected objects.
    ///     globalObjectCount - The number of global objects.
    ///     protectedGlobalObjectCount - The number of protected global objects.
    ///     objectTypeCounts - An object that contains the count of each object type.
    pub fn get_memory_usage(&self) -> JSObject {
        let result = unsafe { JSGetMemoryUsageStatistics(self.inner) };
        JSObject::from_ref(result, self.inner)
    }

    /// Sets a callback function that is called when a promise is rejected and no handler is provided.
    /// The callback is called with the rejected promise and the reason for the rejection.
    ///
    /// # Arguments
    /// - `function`: A JavaScript function.
    ///
    /// # Examples
    /// ```
    /// use rust_jsc::{JSContext, JSObject};
    ///
    /// let ctx = JSContext::new();
    /// let script = "function handleRejection(reason) { console.log('Unhandled rejection:', reason); }; handleRejection";
    /// let function = ctx.evaluate_script(script, None).unwrap();
    /// assert!(function.is_object());
    /// assert!(function.as_object().unwrap().is_function());
    /// let result = ctx.set_unhandled_rejection_callback(function.as_object().unwrap());
    /// ```
    ///
    pub fn set_unhandled_rejection_callback(&self, function: JSObject) -> JSResult<()> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        unsafe {
            JSGlobalContextSetUnhandledRejectionCallback(
                self.inner,
                function.inner,
                &mut exception,
            );
        };

        if !exception.is_null() {
            let value = JSValue::new(exception, self.inner);
            return Err(value.into());
        }

        Ok(())
    }

    /// Sets a callback function that is called when an exception is not caught.
    /// The callback is called with the exception value.
    /// The callback is called on the context thread.
    ///
    /// # Arguments
    /// - `handler`: A native function
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// #[uncaught_exception]
    /// fn uncaught_exception_handler(ctx: JSContext, filename: JSString, exception: JSValue) {
    ///    println!("Uncaught exception: {:?}", exception.as_json_string(1));
    /// }
    ///
    /// fn main() {
    ///     let ctx = JSContext::new();
    ///     ctx.set_uncaught_exception_handler(uncaught_exception_handler);
    /// }
    /// ```
    pub fn set_uncaught_exception_handler(&self, handler: JSUncaughtExceptionHandler) {
        unsafe {
            JSGlobalContextSetUncaughtExceptionHandler(self.inner, handler);
        };
    }

    /// Sets a callback function that is called when an exception is not caught at the event loop.
    /// The callback is called with the exception value.
    /// The callback is called on the event loop thread.
    ///
    /// # Arguments
    /// - `callback`: A native function
    ///
    /// # Examples
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// #[uncaught_exception_event_loop]
    /// fn uncaught_exception_event_loop(ctx: JSContext, exception: JSValue) {
    ///   println!("Uncaught exception: {:?}", exception.as_json_string(1));
    /// }
    ///
    /// fn main() {
    ///     let ctx = JSContext::new();
    ///     ctx.set_uncaught_exception_at_event_loop_callback(uncaught_exception_event_loop);
    /// }
    /// ```
    pub fn set_uncaught_exception_at_event_loop_callback(
        &self,
        callback: JSUncaughtExceptionAtEventLoop,
    ) {
        unsafe {
            JSGlobalContextSetUncaughtExceptionAtEventLoopCallback(self.inner, callback);
        };
    }

    /// Checks the syntax of a JavaScript script.
    ///
    /// # Arguments
    /// - `script`: A JavaScript script.
    /// - `starting_line_number`: The line number to start parsing the script.
    ///
    /// # Examples
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let result = ctx.check_syntax("console.log('Hello, world!');", 0);
    /// assert!(result.is_ok());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a `JSError` if the script has a syntax error.
    /// the error type is a SyntaxError.
    pub fn check_syntax(
        &self,
        script: &str,
        starting_line_number: i32,
    ) -> JSResult<bool> {
        let script: JSString = script.into();
        let source_url = std::ptr::null_mut();
        let mut exception: JSValueRef = std::ptr::null_mut();
        let result = unsafe {
            JSCheckScriptSyntax(
                self.inner,
                script.inner,
                source_url,
                starting_line_number,
                &mut exception,
            )
        };

        if !exception.is_null() {
            let value = JSValue::new(exception, self.inner);
            return Err(value.into());
        }

        Ok(result)
    }

    pub fn group(&self) -> JSContextGroup {
        let group = unsafe { JSContextGetGroup(self.inner) };
        JSContextGroup::from(group)
    }

    /// Gets the global object of the JavaScript execution context.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let global_object = ctx.global_object();
    /// assert_eq!(format!("{:?}", global_object), "JSObject");
    /// ```
    ///
    /// # Returns
    /// Returns a `JSObject` object.
    pub fn global_object(&self) -> JSObject {
        JSObject::from_ref(unsafe { JSContextGetGlobalObject(self.inner) }, self.inner)
    }

    /// Evaluates a JavaScript module.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use rust_jsc::JSContext;
    ///
    /// let filename = "/path/filename.js";
    /// let ctx = JSContext::new();
    /// let result = ctx.evaluate_module(filename);
    /// assert!(result.is_ok());
    /// ```
    ///
    /// It will use a file system module loader to load the module.
    ///
    pub fn evaluate_module(&self, filename: &str) -> JSResult<()> {
        let filename: JSString = filename.into();
        let mut exception: JSValueRef = std::ptr::null_mut();
        unsafe { JSLoadAndEvaluateModule(self.inner, filename.inner, &mut exception) };

        if !exception.is_null() {
            let value = JSValue::new(exception, self.inner);
            return Err(value.into());
        }

        Ok(())
    }

    /// Loads a module.
    /// The module is loaded using the module loader set for the context.
    /// LoadModule:
    ///     - Fetches the module source text.
    ///     - Parses the module source text.
    ///     - Requests dependencies.
    ///
    /// a new entry will be added to the registry with all dependencies satisfied.
    ///
    /// # Arguments
    /// - `key`: The key of the module.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let result = ctx.load_module("test");
    /// assert!(result.is_ok());
    /// ```
    pub fn load_module(&self, key: &str) -> JSResult<()> {
        let module_key: JSString = key.into();
        let mut exception: JSValueRef = std::ptr::null_mut();
        unsafe { JSLoadModule(self.inner, module_key.inner, &mut exception) };

        if !exception.is_null() {
            let value = JSValue::new(exception, self.inner);
            return Err(value.into());
        }

        Ok(())
    }

    /// Links and evaluates a module.
    /// https://262.ecma-international.org/6.0/#sec-moduledeclarationinstantiation
    /// The module is linked and evaluated using the module loader set for the context.
    ///
    /// LinkAndEvaluateModule:
    ///     - Initialize a new module environment.
    ///     - Ensure all the indirect exports are correctly resolved to unique bindings.
    ///     - Instantiate namespace objects and initialize the bindings with them if required.
    ///     - Initialize heap allocated function declarations.
    ///     - Initialize heap allocated variable declarations.
    ///     - link namespace objects to the module environment.
    ///     - set the module environment to the global environment.
    ///     - Evaluate the module.
    ///
    /// # Arguments
    /// - `key`: The key of the module.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let result = ctx.link_and_evaluate_module("test");
    /// assert!(result.is_undefined());
    /// ```
    pub fn link_and_evaluate_module(&self, key: &str) -> JSValue {
        let module_key: JSString = key.into();
        let result = unsafe { JSLinkAndEvaluateModule(self.inner, module_key.inner) };

        JSValue::new(result, self.inner)
    }

    /// Loads a module from source.
    /// The module is loaded using the module loader set for the context.
    ///
    /// # Arguments
    /// - `source`: The source of the module.
    /// - `source_url`: The URL of the source.
    /// - `starting_line_number`: The line number to start parsing the source.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let result = ctx.load_module_from_source("console.log('Hello, World!')", "test.js", 0);
    /// assert!(result.is_ok());
    /// ```
    pub fn load_module_from_source(
        &self,
        source: &str,
        source_url: &str,
        starting_line_number: i32,
    ) -> JSResult<()> {
        let source: JSString = source.into();
        let source_url: JSString = source_url.into();
        let mut exception: JSValueRef = std::ptr::null_mut();
        unsafe {
            JSLoadModuleFromSource(
                self.inner,
                source.inner,
                source_url.inner,
                starting_line_number,
                &mut exception,
            )
        };

        if !exception.is_null() {
            let value = JSValue::new(exception, self.inner);
            return Err(value.into());
        }

        Ok(())
    }

    /// Evaluates a module from source.
    /// The module is evaluated using the module loader set for the context.
    ///
    /// # Arguments
    /// - `source`: The source of the module.
    /// - `source_url`: The URL of the source.
    /// - `starting_line_number`: The line number to start parsing the source.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let result = ctx.evaluate_module_from_source("console.log('Hello, World!')", "test.js", None);
    /// assert!(result.is_ok());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a `JSError` if the module has a syntax error.
    pub fn evaluate_module_from_source(
        &self,
        source: &str,
        source_url: &str,
        starting_line_number: Option<i32>,
    ) -> JSResult<()> {
        let source: JSString = source.into();
        let source_url: JSString = source_url.into();
        let mut exception: JSValueRef = std::ptr::null_mut();

        unsafe {
            JSLoadAndEvaluateModuleFromSource(
                self.inner,
                source.inner,
                source_url.inner,
                starting_line_number.unwrap_or(1),
                &mut exception,
            )
        };

        if !exception.is_null() {
            let value = JSValue::new(exception, self.inner);
            return Err(value.into());
        }

        Ok(())
    }

    /// Sets the module loader for a context.
    /// The module loader is used to load modules when evaluating a module.
    /// The module loader is called with the module key and the context.
    /// All fn pointers must be provided. so that the module loader can be used.
    ///
    /// # Arguments
    /// - `module_loader`: A module loader.
    pub fn set_module_loader(&self, module_loader: JSAPIModuleLoader) {
        unsafe { JSSetAPIModuleLoader(self.inner, module_loader) };
    }

    /// Sets the keys for all virtual modules.
    /// The keys are used to identify virtual modules when loading modules.
    ///
    /// # Arguments
    /// - `keys`: An array of keys.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_jsc::{JSContext, JSStringProctected};
    ///
    /// let ctx = JSContext::new();
    /// let keys = &[
    ///    JSStringProctected::from("@rust-jsc"),
    /// ];
    /// ctx.set_virtual_module_keys(keys);
    /// ```
    pub fn set_virtual_module_keys(&self, keys: &[JSStringProctected]) {
        let keys: Vec<JSStringRef> = keys.iter().map(|key| key.0).collect();
        unsafe {
            JSSetSyntheticModuleKeys(self.inner, keys.len(), keys.as_ptr());
        };
    }

    /// Evaluates a JavaScript script.
    ///
    /// # Arguments
    /// - `script`: A JavaScript script.
    /// - `starting_line_number`: The line number to start parsing the script.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let result = ctx.evaluate_script("console.log('Hello, world!'); 'kedojs'", Some(0));
    /// assert!(result.is_ok());
    /// ```
    ///
    /// # Errors
    /// Returns a `JSError` if the script has a syntax error.
    pub fn evaluate_script(
        &self,
        script: &str,
        starting_line_number: Option<i32>,
    ) -> JSResult<JSValue> {
        let script: JSString = script.into();
        let this_object = std::ptr::null_mut();
        let source_url = std::ptr::null_mut();
        let mut exception: JSValueRef = std::ptr::null_mut();
        let result = unsafe {
            JSEvaluateScript(
                self.inner,
                script.inner,
                this_object,
                source_url,
                starting_line_number.unwrap_or(0),
                &mut exception,
            )
        };

        if !exception.is_null() {
            let value = JSValue::new(exception, self.inner);
            return Err(value.into());
        }

        Ok(JSValue::new(result, self.inner))
    }

    /// Sets the callback function for inspector messages.
    /// This creates a new rust frontend.
    ///
    /// # Arguments
    /// * `callback` - The callback function to be set.
    ///
    /// # Example
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    ///
    /// #[inspector_callback]
    /// fn inspector_callback(message: &str) {
    ///    println!("Inspector message macro: {}", message);
    /// }
    ///
    /// ctx.set_inspector_callback(inspector_callback);
    /// ```
    pub fn set_inspector_callback(&self, callback: InspectorMessageCallback) {
        unsafe {
            JSInspectorSetCallback(self.inner, callback);
        }
    }

    /// Sends a message to the inspector.
    ///
    /// # Arguments
    /// * `message` - The message to be sent.
    ///
    /// # Example
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    ///
    /// ctx.inspector_send_message("{ method: \"Runtime.evaluate\", params: { expression: \"1 + 1\" } }");
    /// ```
    pub fn inspector_send_message(&self, message: &str) {
        let class_name = CString::new(message).unwrap();
        unsafe {
            JSInspectorSendMessage(self.inner, class_name.as_ptr());
        }
    }

    /// Disconnects the inspector frontend from this context.
    /// This should be called before dropping a context that has an active inspector connection.
    /// After calling this function, no more inspector callbacks will be received for this context.
    ///
    /// # Example
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// // ... set up inspector callback and use it ...
    /// ctx.inspector_disconnect(); // Clean up before context is dropped
    /// ```
    pub fn inspector_disconnect(&self) {
        unsafe {
            JSInspectorDisconnect(self.inner);
        }
    }

    /// Checks if the inspector is currently connected for this context.
    ///
    /// # Returns
    /// `true` if an inspector frontend is connected, `false` otherwise.
    ///
    /// # Example
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// assert_eq!(ctx.inspector_is_connected(), false);
    /// ```
    pub fn inspector_is_connected(&self) -> bool {
        unsafe { JSInspectorIsConnected(self.inner) }
    }

    /// Registers a pause-event callback.
    ///
    /// # Arguments
    /// - `callback`: A callback function.
    pub fn set_inspector_pause_event_callback(
        &self,
        callback: InspectorPauseEventCallback,
    ) {
        unsafe {
            JSInspectorSetPauseEventCallback(self.inner, callback);
        }
    }

    /// Releases the context.
    ///
    /// # Example
    /// ```ignore
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    ///
    /// ctx.release();
    /// ```
    pub fn release(self) {
        unsafe {
            JSGlobalContextRelease(self.inner);
        }
    }

    /// Checks if a context is inspectable.
    ///
    /// # Examples
    ///
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let is_inspectable = ctx.is_inspectable();
    /// assert_eq!(is_inspectable, true);
    /// ```
    ///
    /// # Returns
    /// a boolean value. `true` if the context is inspectable, `false` otherwise.
    pub fn is_inspectable(&self) -> bool {
        unsafe { JSGlobalContextIsInspectable(self.inner) }
    }

    /// Sets whether a context is inspectable.
    ///
    /// # Examples
    /// ```no_run
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_inspectable(true);
    /// assert_eq!(ctx.is_inspectable(), true);
    /// ```
    pub fn set_inspectable(&self, inspectable: bool) {
        unsafe { JSGlobalContextSetInspectable(self.inner, inspectable) };
    }

    /// Sets the name exposed when inspecting a context.
    ///
    /// # Examples
    /// ```no_run
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_name("KedoJS");
    /// assert_eq!(ctx.get_name().to_string(), "KedoJS");
    /// ```
    pub fn set_name(&self, name: &str) {
        let name: JSString = name.into();
        unsafe { JSGlobalContextSetName(self.inner, name.inner) }
    }

    /// Gets a copy of the name of a context.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// let name = ctx.get_name();
    /// ```
    ///
    /// # Returns
    ///
    /// Returns a `JSString` object.
    pub fn get_name(&self) -> JSString {
        let name = unsafe { JSGlobalContextCopyName(self.inner) };
        name.into()
    }

    /// Sets shared data for a context.
    ///
    /// The data is wrapped in a type-safe container that tracks the original type,
    /// preventing type confusion when retrieved with [`get_shared_data`].
    ///
    /// # Arguments
    /// - `data`: The data to store. Accepts any `'static` type.
    ///
    /// # Examples
    /// ```no_run
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_shared_data(10i32);
    /// ```
    ///
    /// # Note
    /// If shared data was previously set, call [`take_shared_data`] first to
    /// reclaim it. Otherwise the old data will be leaked.
    pub fn set_shared_data<T: 'static>(&self, data: T) {
        let ptr = PrivateDataWrapper::into_raw(data);
        unsafe { JSContextSetSharedData(self.inner, ptr) }
    }

    /// Gets shared data for a context as an immutable reference.
    ///
    /// Returns `None` if no data is set or if `T` does not match the type
    /// that was originally stored with [`set_shared_data`].
    ///
    /// # Examples
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_shared_data(10i32);
    /// let shared_data = ctx.get_shared_data::<i32>().unwrap();
    /// assert_eq!(*shared_data, 10);
    /// ```
    ///
    /// # Type Safety
    /// Unlike raw pointer casts, this method uses `TypeId`-based checking.
    /// Requesting the wrong type returns `None` instead of causing UB:
    /// ```
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_shared_data(String::from("hello"));
    /// assert!(ctx.get_shared_data::<u64>().is_none()); // wrong type → None
    /// assert!(ctx.get_shared_data::<String>().is_some()); // correct type → Some
    /// ```
    pub fn get_shared_data<T: 'static>(&self) -> Option<&T> {
        let data_ptr = unsafe { JSContextGetSharedData(self.inner) };
        unsafe { PrivateDataWrapper::downcast_ref(data_ptr) }
    }

    /// Gets shared data for a context as a mutable reference.
    ///
    /// Returns `None` if no data is set or if `T` does not match the type
    /// that was originally stored with [`set_shared_data`].
    ///
    /// # Safety
    ///
    /// The caller **must** guarantee that:
    ///
    /// 1. No other `&T` or `&mut T` references obtained from [`get_shared_data`]
    ///    or this method are alive at the time of the call.
    /// 2. The returned `&mut T` is not held simultaneously with any other
    ///    reference to the same data.
    ///
    /// Violating these rules creates **aliased mutable references**, which is
    /// instant undefined behavior — the compiler may reorder reads/writes,
    /// cache stale values, or miscompile the program.
    ///
    /// # Recommended alternative
    ///
    /// For safe interior mutability, store a [`std::cell::RefCell<T>`] and use
    /// [`get_shared_data`] instead:
    ///
    /// ```no_run
    /// use rust_jsc::JSContext;
    /// use std::cell::RefCell;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_shared_data(RefCell::new(10i32));
    ///
    /// // Safe runtime borrow checking — panics on double mutable borrow
    /// let cell = ctx.get_shared_data::<RefCell<i32>>().unwrap();
    /// *cell.borrow_mut() = 20;
    /// assert_eq!(*cell.borrow(), 20);
    /// ```
    ///
    /// # Examples
    /// ```no_run
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_shared_data(10i32);
    /// // SAFETY: no other references to the shared data exist.
    /// if let Some(data) = unsafe { ctx.get_shared_data_mut::<i32>() } {
    ///     *data = 20;
    /// }
    /// assert_eq!(*ctx.get_shared_data::<i32>().unwrap(), 20);
    /// ```
    pub unsafe fn get_shared_data_mut<T: 'static>(&self) -> Option<&mut T> {
        let data_ptr = unsafe { JSContextGetSharedData(self.inner) };
        unsafe { PrivateDataWrapper::downcast_mut(data_ptr) }
    }

    /// Takes ownership of the shared data, removing it from the context.
    ///
    /// Returns `None` if no data is set or if `T` does not match the stored type.
    /// if T does not match, the data remains in place and is not freed,
    /// so it can still be retrieved with the correct type.
    ///
    /// # Safety
    /// This function is unsafe because `JSContext` is a handle that can be cloned.
    /// If other references to the shared data exist (e.g. obtained via `get_shared_data`
    /// from a cloned handle), calling this method will free the memory they point to,
    /// causing Undefined Behavior (Use-After-Free).
    ///
    /// # Examples
    /// ```no_run
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_shared_data(42i32);
    /// let data: i32 = unsafe { ctx.take_shared_data::<i32>() }.unwrap();
    /// assert_eq!(data, 42);
    /// assert!(ctx.get_shared_data::<i32>().is_none()); // data has been removed
    /// ```
    ///
    /// # Safety Note
    /// The caller must ensure that the type `T` matches the type of the data currently
    /// stored in the context. If the type does not match, this method will return `None`
    /// and leave the data in place.
    pub unsafe fn take_shared_data<T: 'static>(&self) -> Option<T> {
        let data_ptr = unsafe { JSContextGetSharedData(self.inner) };
        if data_ptr.is_null() {
            return None;
        }
        // Only take ownership (and clear the JSC pointer) if the type matches.
        // On type mismatch the data stays in place — nothing is freed or lost.
        let result = unsafe { PrivateDataWrapper::take(data_ptr) };
        if result.is_some() {
            unsafe { JSContextSetSharedData(self.inner, std::ptr::null_mut()) };
        }
        result
    }

    /// Drops the shared data without reclaiming ownership.
    /// This is useful for cleaning up data when the context is being dropped, without needing to take ownership of it.
    /// After this call, the context's shared data pointer is cleared.
    ///
    /// # Examples
    /// ```no_run
    /// use rust_jsc::JSContext;
    ///
    /// let ctx = JSContext::new();
    /// ctx.set_shared_data(String::from("temporary data"));
    /// unsafe { ctx.drop_shared_data::<String>() }; // Clean up without taking ownership
    /// assert!(ctx.get_shared_data::<String>().is_none()); // data has been removed
    /// ```
    /// # Safety Note
    /// The caller must ensure that the type `T` matches the type of the data currently
    /// stored in the context. If the type does not match, this method will not drop the data,
    /// and set the shared data pointer to null, which could lead to memory leaks. Use with caution.
    pub unsafe fn drop_shared_data<T: 'static>(&self) {
        let data_ptr = unsafe { JSContextGetSharedData(self.inner) };
        if !data_ptr.is_null() {
            unsafe { PrivateDataWrapper::drop_raw::<T>(data_ptr) };
            unsafe { JSContextSetSharedData(self.inner, std::ptr::null_mut()) };
        }
    }
}

impl std::fmt::Debug for JSContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JSContext").finish()
    }
}

impl Default for JSContext {
    fn default() -> Self {
        JSContext::new()
    }
}

impl From<JSContextRef> for JSContext {
    fn from(context: JSContextRef) -> Self {
        let global_context = unsafe { JSContextGetGlobalContext(context) };
        // Retaining the context here would lead to over-retention and potential memory leaks.
        // unsafe { JSGlobalContextRetain(global_context); }

        Self {
            inner: global_context,
        }
    }
}

// impl Drop for JSContext {
//     fn drop(&mut self) {
//         /*
//         TODO: Set pointer to null
//         unsafe {
//              if JSInspectorIsConnected(self.inner) {
//                  JSInspectorDisconnect(self.inner);
//              }
//             JSContextSetSharedData(self.inner, std::ptr::null_mut());
//         }
//         */
//     }
// }

impl From<JSGlobalContextRef> for JSContext {
    fn from(ctx: JSGlobalContextRef) -> Self {
        Self { inner: ctx }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{self as rust_jsc};

    use rust_jsc_macros::*;

    #[module_resolve]
    fn module_loader_resolve_virtual(
        _ctx: JSContext,
        _key: JSValue,
        _referrer: JSValue,
        _script_fetcher: JSValue,
    ) -> JSStringProctected {
        JSStringProctected::from("@rust-jsc")
    }

    #[module_evaluate]
    fn module_loader_evaluate_virtual(ctx: JSContext, _key: JSValue) -> JSValue {
        let object = JSObject::new(&ctx);
        let value = JSValue::string(&ctx, "John Doe");
        object
            .set_property("name", &value, Default::default())
            .unwrap();

        let default = JSObject::new(&ctx);
        default
            .set_property("name", &value, Default::default())
            .unwrap();

        default
            .set_property("default", &object, Default::default())
            .unwrap();
        default.into()
    }

    #[module_evaluate]
    fn module_loader_evaluate_no_default_virtual(
        ctx: JSContext,
        _key: JSValue,
    ) -> JSValue {
        let object = JSObject::new(&ctx);
        let value = JSValue::string(&ctx, "John Doe");
        object
            .set_property("name", &value, Default::default())
            .unwrap();
        object.into()
    }

    #[uncaught_exception]
    fn uncaught_exception_handler(
        _ctx: JSContext,
        _filename: JSString,
        exception: JSValue,
    ) {
        println!("Uncaught exception: {:?}", exception.as_json_string(1));
    }

    #[uncaught_exception_event_loop]
    fn uncaught_exception_event_loop(_ctx: JSContext, exception: JSValue) {
        println!("Uncaught exception: {:?}", exception.as_json_string(1));
    }

    #[module_resolve]
    fn module_loader_resolve_non_virtual(
        _ctx: JSContext,
        key: JSValue,
        _referrer: JSValue,
        _script_fetcher: JSValue,
    ) -> JSStringProctected {
        let key_value = key.as_string().unwrap();
        // resolve path to file system
        let test_module_dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/modules");
        // module key can start with ./ or ../
        let path = std::path::Path::new(test_module_dir).join(key_value.to_string());
        let module_path = std::fs::canonicalize(path).unwrap();

        JSStringProctected::from(module_path.to_str().unwrap())
    }

    #[module_fetch]
    fn module_loader_fetch(
        _ctx: JSContext,
        _key: JSValue,
        _attributes_value: JSValue,
        _script_fetcher: JSValue,
    ) -> JSStringProctected {
        // read file content
        let path_key = _key.as_string().unwrap().to_string();
        println!("Path key: {:?}", path_key);
        // check if the path is a file
        let file_content = match std::fs::read_to_string(&path_key) {
            Ok(content) => content,
            Err(error) => {
                unreachable!("Error reading file: {:?}", error);
            }
        };

        JSStringProctected::from(file_content)
    }

    #[module_import_meta]
    fn module_loader_create_import_meta_properties(
        ctx: JSContext,
        key: JSValue,
        _script_fetcher: JSValue,
    ) -> JSObject {
        let object = JSObject::new(&ctx);
        object
            .set_property("url", &key, Default::default())
            .unwrap();
        object
    }

    #[test]
    fn test_js_context() {
        let ctx = JSContext::new();
        assert_eq!(format!("{:?}", ctx), "JSContext");
    }

    #[test]
    fn test_js_context_name() {
        let ctx = JSContext::new();
        ctx.set_name("KedoJS");
        assert_eq!(ctx.get_name().to_string(), "KedoJS");
    }

    #[test]
    fn test_js_context_group() {
        let group = JSContextGroup::new();
        assert_eq!(format!("{:?}", group), "JSContextGroup");
    }

    #[test]
    fn test_js_context_with_group() {
        let group = JSContextGroup::new();
        let ctx = group.new_context();
        assert_eq!(format!("{:?}", ctx), "JSContext");
    }

    #[test]
    fn test_js_context_garbage_collect() {
        let ctx = JSContext::new();
        ctx.garbage_collect();
    }

    #[test]
    fn test_js_context_check_syntax() {
        let ctx = JSContext::new();
        let script = "console.log('Hello, world!');";
        let result = ctx.check_syntax(script, 1);
        assert!(result.is_ok());
    }

    #[test]
    fn test_js_context_global_object() {
        let ctx = JSContext::new();
        let global_object = ctx.global_object();
        assert_eq!(format!("{:?}", global_object), "JSObject");
    }

    #[test]
    fn test_js_context_evaluate_module() {
        let filename = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/modules/test.js");
        let ctx = JSContext::new();
        let result = ctx.evaluate_module(filename);
        assert!(result.is_ok());
    }

    #[test]
    fn test_js_context_evaluate_module_fails() {
        let filename =
            concat!(env!("CARGO_MANIFEST_DIR"), "/non_exist/mock_path/wrong.js");
        let ctx = JSContext::new();
        let result = ctx.evaluate_module(filename);
        assert!(result.is_err());
    }

    #[test]
    fn test_js_context_evaluate_script() {
        let ctx = JSContext::new();
        let script = "console.log('Hello, world!'); 'kedojs'";
        let result = ctx.evaluate_script(script, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_js_context_evaluate_module_source() {
        let ctx = JSContext::new();
        let script = "console.log('Hello, world!'); 'kedojs'";
        let result = ctx.evaluate_module_from_source(script, "source.js", None);
        assert!(result.is_ok());
    }

    // =========================================================================
    // Inspector / Debugger Tests
    // =========================================================================

    #[test]
    fn test_inspector_set_inspectable() {
        let ctx = JSContext::new();

        // Initially not inspectable
        ctx.set_inspectable(false);
        assert!(!ctx.is_inspectable());

        // Enable inspectable
        ctx.set_inspectable(true);
        assert!(ctx.is_inspectable());

        // Disable inspectable
        ctx.set_inspectable(false);
        assert!(!ctx.is_inspectable());
    }

    #[test]
    fn test_inspector_connect_disconnect() {
        let ctx = JSContext::new();
        ctx.set_inspectable(true);

        #[inspector_callback]
        fn callback(_message: &str) {}

        // Connect inspector
        ctx.set_inspector_callback(Some(callback));
        assert!(ctx.inspector_is_connected());

        // Disconnect inspector
        ctx.inspector_disconnect();
        assert!(!ctx.inspector_is_connected());
    }

    #[test]
    fn test_inspector_send_message() {
        use std::sync::atomic::{AtomicBool, Ordering};

        static RECEIVED: AtomicBool = AtomicBool::new(false);

        let ctx = JSContext::new();
        ctx.set_inspectable(true);

        #[inspector_callback]
        fn callback(message: &str) {
            // Verify we receive a response
            if message.contains("\"id\":1") {
                RECEIVED.store(true, Ordering::SeqCst);
            }
        }

        ctx.set_inspector_callback(Some(callback));

        // Send a simple Runtime.evaluate command
        ctx.inspector_send_message(
            r#"{"id": 1, "method": "Runtime.evaluate", "params": {"expression": "1+1"}}"#,
        );

        assert!(RECEIVED.load(Ordering::SeqCst), "Should receive response");
        ctx.inspector_disconnect();
    }

    #[test]
    fn test_inspector_debugger_enable_disable() {
        use std::sync::atomic::{AtomicU32, Ordering};

        static RESPONSE_COUNT: AtomicU32 = AtomicU32::new(0);

        let ctx = JSContext::new();
        ctx.set_inspectable(true);

        #[inspector_callback]
        fn callback(message: &str) {
            if message.contains("\"result\"") {
                RESPONSE_COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        ctx.set_inspector_callback(Some(callback));

        // Enable debugger
        ctx.inspector_send_message(
            r#"{"id": 1, "method": "Debugger.enable", "params": {}}"#,
        );

        // Disable debugger
        ctx.inspector_send_message(
            r#"{"id": 2, "method": "Debugger.disable", "params": {}}"#,
        );

        assert!(
            RESPONSE_COUNT.load(Ordering::SeqCst) >= 2,
            "Should receive responses for enable and disable"
        );

        ctx.inspector_disconnect();
    }

    #[test]
    fn test_virtual_module() {
        let ctx = JSContext::new();
        let keys = &[JSStringProctected::from("@rust-jsc")];
        ctx.set_virtual_module_keys(keys);

        let callbacks = JSAPIModuleLoader {
            disableBuiltinFileSystemLoader: false,
            moduleLoaderResolve: Some(module_loader_resolve_virtual),
            moduleLoaderEvaluate: Some(module_loader_evaluate_virtual),
            moduleLoaderFetch: Some(module_loader_fetch),
            moduleLoaderCreateImportMetaProperties: Some(
                module_loader_create_import_meta_properties,
            ),
        };
        ctx.set_module_loader(callbacks);

        // let module_test_dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/modules");
        // let test_dir = format!("{}/virtual_module.js", module_test_dir);
        let result = ctx.evaluate_module_from_source(
            r"
            import lib from '@rust-jsc';
            globalThis.lib = lib;
        ",
            "virtual_module.js",
            None,
        );
        assert!(result.is_ok());

        let result = ctx.evaluate_script("lib.name", None);

        assert!(result.is_ok());
        let result_value = result.unwrap();
        assert_eq!(result_value.as_string().unwrap(), "John Doe");

        let result = ctx.evaluate_module_from_source(
            r"
            import { name } from '@rust-jsc';
            globalThis.name = name;
        ",
            "virtual_module.js",
            None,
        );
        assert!(result.is_ok());

        let result = ctx.evaluate_script("name", None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_string().unwrap(), "John Doe");
    }

    #[test]
    fn test_virtual_module_no_default() {
        let ctx = JSContext::new();
        let keys = &[JSStringProctected::from("@rust-jsc")];
        ctx.set_virtual_module_keys(keys);

        let callbacks = JSAPIModuleLoader {
            disableBuiltinFileSystemLoader: false,
            moduleLoaderResolve: Some(module_loader_resolve_virtual),
            moduleLoaderEvaluate: Some(module_loader_evaluate_no_default_virtual),
            moduleLoaderFetch: Some(module_loader_fetch),
            moduleLoaderCreateImportMetaProperties: Some(
                module_loader_create_import_meta_properties,
            ),
        };
        ctx.set_module_loader(callbacks);

        let result = ctx.evaluate_module_from_source(
            r"
            import { name } from '@rust-jsc';
            globalThis.name = name;
        ",
            "virtual_module.js",
            None,
        );

        assert!(result.is_ok());

        let result = ctx.evaluate_script("name", None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_string().unwrap(), "John Doe");

        let result = ctx.evaluate_module_from_source(
            r"
            import lib from '@rust-jsc';
            globalThis.lib = lib;
        ",
            "virtual_module.js",
            None,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_non_virtual_module() {
        let ctx = JSContext::new();

        let callbacks = JSAPIModuleLoader {
            disableBuiltinFileSystemLoader: true,
            moduleLoaderResolve: Some(module_loader_resolve_non_virtual),
            moduleLoaderEvaluate: Some(module_loader_evaluate_virtual),
            moduleLoaderFetch: Some(module_loader_fetch),
            moduleLoaderCreateImportMetaProperties: Some(
                module_loader_create_import_meta_properties,
            ),
        };
        ctx.set_module_loader(callbacks);

        let module_test_dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/modules");
        let test_dir = format!("{}/test.js", module_test_dir);
        let result = ctx.evaluate_module(&test_dir);
        assert!(result.is_ok());

        let result = ctx.evaluate_script("message", None);
        assert!(result.is_ok());

        let result_value = result.unwrap();
        assert_eq!(result_value.as_string().unwrap(), "Hello World KEDO");
    }

    #[test]
    fn test_set_unhandled_rejection_callback() {
        let ctx = JSContext::new();
        let script = "function handleRejection(reason) { console.log('Unhandled rejection:', reason); }; handleRejection";
        let function = ctx.evaluate_script(script, None).unwrap();

        assert!(function.is_object());
        assert!(function.as_object().unwrap().is_function());
        let result = ctx.set_unhandled_rejection_callback(function.as_object().unwrap());
        assert!(result.is_ok());
    }

    #[test]
    fn test_set_uncaught_exception_handler() {
        let ctx = JSContext::new();
        ctx.set_uncaught_exception_handler(Some(uncaught_exception_handler));

        let script =
            "function throwError() { throw new Error('Error thrown'); }; throwError();";
        let result = ctx.evaluate_module_from_source(
            script,
            "uncaught_exception_handler.js",
            None,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_set_uncaught_exception_at_event_loop_callback() {
        let ctx = JSContext::new();
        ctx.set_uncaught_exception_at_event_loop_callback(Some(
            uncaught_exception_event_loop,
        ));
    }

    #[allow(dead_code)]
    fn memory_usage(ctx: &JSContext) {
        let memory_usage_statistics = ctx.get_memory_usage();
        let heap_size = memory_usage_statistics
            .get_property("heapSize")
            .unwrap()
            .as_number()
            .unwrap();
        let heap_capacity = memory_usage_statistics
            .get_property("heapCapacity")
            .unwrap()
            .as_number()
            .unwrap();
        let extra_memory_size = memory_usage_statistics
            .get_property("extraMemorySize")
            .unwrap()
            .as_number()
            .unwrap();
        let object_count = memory_usage_statistics
            .get_property("objectCount")
            .unwrap()
            .as_number()
            .unwrap();
        let protected_object_count = memory_usage_statistics
            .get_property("protectedObjectCount")
            .unwrap()
            .as_number()
            .unwrap();
        let global_object_count = memory_usage_statistics
            .get_property("globalObjectCount")
            .unwrap()
            .as_number()
            .unwrap();
        let protected_global_object_count = memory_usage_statistics
            .get_property("protectedGlobalObjectCount")
            .unwrap()
            .as_number()
            .unwrap();

        println!("Heap size: {}", heap_size);
        println!("Heap capacity: {}", heap_capacity);
        println!("Extra memory size: {}", extra_memory_size);
        println!("Object count: {}", object_count);
        println!("Protected object count: {}", protected_object_count);
        println!("Global object count: {}", global_object_count);
        println!(
            "Protected global object count: {}",
            protected_global_object_count
        );
    }

    #[test]
    fn test_shared_data_type_safe() {
        let ctx = JSContext::new();
        ctx.set_shared_data(42i32);
        let data = ctx.get_shared_data::<i32>().unwrap();
        assert_eq!(*data, 42);
    }

    #[test]
    fn test_shared_data_wrong_type_returns_none() {
        let ctx = JSContext::new();
        ctx.set_shared_data(String::from("hello"));
        // Requesting the wrong type must return None, not UB
        assert!(ctx.get_shared_data::<u64>().is_none());
        assert!(ctx.get_shared_data::<i32>().is_none());
        assert!(ctx.get_shared_data::<Vec<u8>>().is_none());
        // Correct type works
        assert_eq!(ctx.get_shared_data::<String>().unwrap(), "hello");
    }

    #[test]
    fn test_shared_data_multiple_reads() {
        let ctx = JSContext::new();
        ctx.set_shared_data(100u64);
        // Multiple reads should all succeed (no double-free)
        assert_eq!(*ctx.get_shared_data::<u64>().unwrap(), 100);
        assert_eq!(*ctx.get_shared_data::<u64>().unwrap(), 100);
        assert_eq!(*ctx.get_shared_data::<u64>().unwrap(), 100);
    }

    #[test]
    fn test_shared_data_mut() {
        let ctx = JSContext::new();
        ctx.set_shared_data(10i32);
        if let Some(data) = unsafe { ctx.get_shared_data_mut::<i32>() } {
            *data = 20;
        }
        assert_eq!(*ctx.get_shared_data::<i32>().unwrap(), 20);
    }

    #[test]
    fn test_take_shared_data() {
        let ctx = JSContext::new();
        ctx.set_shared_data(String::from("take me"));
        let taken = unsafe { ctx.take_shared_data::<String>() }.unwrap();
        assert_eq!(taken, "take me");
        // After take, data is gone
        assert!(ctx.get_shared_data::<String>().is_none());
    }

    #[test]
    fn test_shared_data_none_when_empty() {
        let ctx = JSContext::new();
        assert!(ctx.get_shared_data::<i32>().is_none());
        assert!(unsafe { ctx.take_shared_data::<i32>() }.is_none());
    }

    #[test]
    fn test_shared_data_refcell_safe_mutation() {
        use std::cell::RefCell;

        let ctx = JSContext::new();
        ctx.set_shared_data(RefCell::new(String::from("original")));

        // Safe interior mutability via RefCell
        let cell = ctx.get_shared_data::<RefCell<String>>().unwrap();
        *cell.borrow_mut() = String::from("mutated");

        // Re-read through get_shared_data — no unsafe needed
        let cell = ctx.get_shared_data::<RefCell<String>>().unwrap();
        assert_eq!(*cell.borrow(), "mutated");
    }

    #[test]
    fn test_shared_data_struct() {
        #[derive(Debug, PartialEq)]
        struct AppState {
            counter: u32,
            name: String,
        }

        let ctx = JSContext::new();
        ctx.set_shared_data(AppState {
            counter: 0,
            name: "test".to_string(),
        });

        let state = ctx.get_shared_data::<AppState>().unwrap();
        assert_eq!(state.counter, 0);
        assert_eq!(state.name, "test");

        // Wrong type returns None
        assert!(ctx.get_shared_data::<String>().is_none());
    }

    #[test]
    fn test_shared_data_mut_wrong_type_returns_none() {
        let ctx = JSContext::new();
        ctx.set_shared_data(42i32);

        // SAFETY: no other references exist
        let result = unsafe { ctx.get_shared_data_mut::<String>() };
        assert!(result.is_none());

        // Original data is still intact
        assert_eq!(*ctx.get_shared_data::<i32>().unwrap(), 42);
    }

    #[test]
    fn test_take_shared_data_wrong_type_preserves_data() {
        let ctx = JSContext::new();
        ctx.set_shared_data(String::from("preserve me"));

        // Taking with wrong type should return None and NOT destroy the data
        assert!(unsafe { ctx.take_shared_data::<i32>() }.is_none());
        assert!(unsafe { ctx.take_shared_data::<Vec<u8>>() }.is_none());

        // Data should still be accessible with correct type
        assert_eq!(ctx.get_shared_data::<String>().unwrap(), "preserve me");

        // Now take with correct type
        let taken = unsafe { ctx.take_shared_data::<String>() }.unwrap();
        assert_eq!(taken, "preserve me");
        assert!(ctx.get_shared_data::<String>().is_none());
    }

    #[test]
    fn test_drop_shared_data() {
        let ctx = JSContext::new();
        ctx.set_shared_data(String::from("drop me"));

        assert!(ctx.get_shared_data::<String>().is_some());
        unsafe { ctx.drop_shared_data::<String>() };
        assert!(ctx.get_shared_data::<String>().is_none());
    }

    #[test]
    fn test_shared_data_replace() {
        let ctx = JSContext::new();
        ctx.set_shared_data(42i32);
        assert_eq!(*ctx.get_shared_data::<i32>().unwrap(), 42);

        // Take old data, then set new data of a different type
        let old = unsafe { ctx.take_shared_data::<i32>() }.unwrap();
        assert_eq!(old, 42);

        ctx.set_shared_data(String::from("new type"));
        assert_eq!(ctx.get_shared_data::<String>().unwrap(), "new type");
        // Old type is gone
        assert!(ctx.get_shared_data::<i32>().is_none());
    }

    #[test]
    fn test_shared_data_vec() {
        let ctx = JSContext::new();
        ctx.set_shared_data(vec![1u8, 2, 3, 4, 5]);

        let data = ctx.get_shared_data::<Vec<u8>>().unwrap();
        assert_eq!(data, &[1, 2, 3, 4, 5]);

        // Mutate via unsafe
        // SAFETY: no other references exist
        let data = unsafe { ctx.get_shared_data_mut::<Vec<u8>>() }.unwrap();
        data.push(6);

        let data = ctx.get_shared_data::<Vec<u8>>().unwrap();
        assert_eq!(data, &[1, 2, 3, 4, 5, 6]);
    }

    #[test]
    fn test_shared_data_zero_sized_type() {
        let ctx = JSContext::new();
        ctx.set_shared_data(());

        assert!(ctx.get_shared_data::<()>().is_some());
        assert!(ctx.get_shared_data::<i32>().is_none());

        let taken = unsafe { ctx.take_shared_data::<()>() }.unwrap();
        assert_eq!(taken, ());
    }

    #[test]
    fn test_shared_data_read_after_mut() {
        let ctx = JSContext::new();
        ctx.set_shared_data(100i32);

        // Mutate
        // SAFETY: no other references exist
        {
            let data = unsafe { ctx.get_shared_data_mut::<i32>() }.unwrap();
            *data = 200;
        }
        // Reference dropped, now safe to read
        assert_eq!(*ctx.get_shared_data::<i32>().unwrap(), 200);
    }

    #[test]
    fn test_shared_data_uaf_scenario() {
        let ctx = JSContext::new();
        ctx.set_shared_data(String::from("alive"));

        // Create an alias manually since JSContext is not Clone
        // We need to access inner which is pub(crate)
        let ctx_alias = JSContext { inner: ctx.inner };

        // 1. Get reference from first context
        // The reference lifetime is tied to `ctx`
        let data_ref = ctx.get_shared_data::<String>().unwrap();
        assert_eq!(data_ref, "alive");

        // 2. Take ownership from alias (simulating concurrent access or passed handle)
        // This frees the memory while data_ref is still active in Rust's eyes
        // (because the compiler doesn't know ctx and ctx_alias share state)
        let taken = unsafe { ctx_alias.take_shared_data::<String>() };
        assert_eq!(taken.unwrap(), "alive");

        // 3. data_ref is now dangling!
        // Accessing it here would be UAF and likely crash or print garbage.
        // println!("Dangling ref: {}", data_ref); // THIS CAUSES UB/CRASH

        // Verify the data is logically gone from the context
        assert!(ctx.get_shared_data::<String>().is_none());

        // Avoid double-release issues if JSContext implements Drop (currently it doesn't seem to)
        std::mem::forget(ctx_alias);
    }
}