polyplug_js 0.1.1

QuickJS loader for polyplug - loads JavaScript plugins via QuickJS
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
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
//! Integration tests for the QuickJS bundle loader.
//!
//! Covers: runtime initialisation, bundle evaluation (valid / syntax error /
//! runtime error), polyplug_init registration, and thread-safety.

#![allow(clippy::expect_used)]

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;

use polyplug::error::LoaderError;
use polyplug::error::RuntimeError;
use polyplug::loader::BundleLoader;
use polyplug::loader::BundleSource;
use polyplug::loader::manifest::ManifestData;
use polyplug::runtime::Runtime;
use polyplug::runtime::RuntimeBuilder;
use polyplug_abi::AbiError;
use polyplug_abi::AbiErrorCode;
use polyplug_abi::Compatibility;
use polyplug_abi::DispatchType;
use polyplug_abi::GuestContractHandle;
use polyplug_abi::GuestContractInstance;
use polyplug_abi::GuestContractInterface;
use polyplug_abi::RuntimeConfig;
use polyplug_abi::types::LogLevel;
use polyplug_js::JsConfig;
use polyplug_js::JsLoader;
use polyplug_utils::GuestContractId;

// ─── Helpers ──────────────────────────────────────────────────────────────────

/// Build a minimal bundle JS string that defines polyplug_init and registers a plugin.
fn make_bundle_js(contract_id: u64, fn_count: u32, contract_name: &str) -> String {
    let contract_lo: u32 = contract_id as u32;
    let contract_hi: u32 = (contract_id >> 32) as u32;
    format!(
        r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var descriptor = {{
        name: "js-quickjs-plugin",
        contractName: "{contract_name}",
        versionMajor: 0,
        versionMinor: 1,
        versionPatch: 0
    }};
    var iface = {{
        contractLo: {contract_lo},
        contractHi: {contract_hi},
        fnCount: {fn_count},
        contractName: "{contract_name}",
        version: 0x00010000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [
            function(impl, args, out, arena, bridge) {{ return 0; }}
        ]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#
    )
}

/// Write `content` to a temp file and return the path.
/// Also creates a minimal manifest.toml for the bundle.
fn write_temp_bundle(content: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    write_temp_bundle_with_name(content, "test.bundle")
}

/// Write `content` to a temp file with a specific bundle name.
fn write_temp_bundle_with_name(
    content: &str,
    name: &str,
) -> (tempfile::TempDir, std::path::PathBuf) {
    let dir: tempfile::TempDir = tempfile::tempdir().expect("tempdir");
    let path: std::path::PathBuf = dir.path().join("bundle.js");
    std::fs::write(&path, content).expect("write bundle.js");

    let bundle_id: u64 = polyplug_utils::bundle_id(name);
    let manifest: String = format!(
        r#"id = {}
name = "{}"
loader = "js-quickjs"
file = "bundle.js"
"#,
        bundle_id, name
    );
    std::fs::write(dir.path().join("manifest.toml"), &manifest).expect("write manifest.toml");

    (dir, path)
}

/// Create a JsLoader.
fn make_loader() -> JsLoader {
    JsLoader::new(JsConfig {})
}

/// Create a minimal Runtime with the JsLoader registered.
fn make_runtime() -> Arc<Runtime> {
    RuntimeBuilder::new()
        .loader(make_loader())
        .build()
        .expect("runtime build must succeed")
}

/// Create a Runtime with the JsLoader registered and hot-reload enabled.
fn make_runtime_hot_reload() -> Arc<Runtime> {
    RuntimeBuilder::new()
        .loader(make_loader())
        .config(RuntimeConfig {
            compatibility: Compatibility::Strict,
            hot_reload_enabled: true,
            on_reload: None,
            on_reload_user_data: core::ptr::null_mut(),
            ..Default::default()
        })
        .build()
        .expect("runtime build must succeed")
}

/// Create a ManifestData for a JS bundle.
fn make_manifest(path: &std::path::Path, name: &str) -> ManifestData {
    ManifestData {
        id: polyplug_utils::bundle_id(name),
        name: name.to_owned(),
        loader: "js-quickjs".to_owned(),
        file: path
            .file_name()
            .expect("bundle path must have a file name")
            .to_string_lossy()
            .into_owned(),
        path: path
            .parent()
            .expect("bundle path must have a parent directory")
            .to_path_buf(),
        version: String::new(),
        provides: Vec::new(),
        function_count: HashMap::new(),
        dependencies: Vec::new(),
        needs_reinit_on_dep_reload: false,
        bundle_dependencies: Vec::new(),
    }
}

/// Verify a VM-dispatch vtable exposes exactly `expected` functions by probing
/// fn_ids: indices `0..expected` must return `Ok`, and index `expected` must
/// return `FunctionNotAvailable`.
fn assert_vm_function_count(vtable: &GuestContractInterface, expected: u32) {
    use polyplug_abi::AbiError;
    use polyplug_abi::AbiErrorCode;

    assert_eq!(vtable.dispatch_type, DispatchType::VirtualMachine);
    for fn_id in 0..expected {
        let mut result: AbiError = AbiError::ok();
        // SAFETY: dispatch.vm.call is js_dispatch; the noop functions ignore the
        // null args/out pointers.
        unsafe {
            (vtable.dispatch.vm.call)(
                vtable.dispatch.vm.loader_data,
                GuestContractInstance::null(),
                fn_id,
                core::ptr::null::<()>(),
                core::ptr::null_mut::<()>(),
                core::ptr::null_mut(),
                &mut result as *mut AbiError,
            );
        }
        assert_eq!(
            result.code,
            AbiErrorCode::Ok as u32,
            "fn_id {fn_id} must dispatch to Ok"
        );
    }
    let mut missing: AbiError = AbiError::ok();
    // SAFETY: dispatch.vm.call is js_dispatch.
    unsafe {
        (vtable.dispatch.vm.call)(
            vtable.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            expected,
            core::ptr::null::<()>(),
            core::ptr::null_mut::<()>(),
            core::ptr::null_mut(),
            &mut missing as *mut AbiError,
        );
    }
    assert_eq!(
        missing.code,
        AbiErrorCode::FunctionNotAvailable as u32,
        "fn_id {expected} must report FunctionNotAvailable"
    );
}

// ─── Tests ────────────────────────────────────────────────────────────────────

// ── Runtime initialisation ────────────────────────────────────────────────────

#[test]
fn loader_name_is_js_quickjs() {
    let loader: JsLoader = make_loader();
    assert_eq!(loader.loader_name(), "js-quickjs");
}

// ── Valid bundle evaluation + vtable registration ─────────────────────────────

#[test]
fn load_valid_bundle_registers_vtable() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.noop", 1);

    let bundle: String = make_bundle_js(contract_id, 1, "test.noop");
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "load must succeed: {result:?}");

    // Verify the plugin was registered by querying the registry.
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must be registered");
    assert!(!handle.is_null(), "handle must be valid");
}

#[test]
fn load_bundle_with_functions_registers_correct_count() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.math", 1);
    let fn_count: u32 = 3;

    // Bundle with 3 functions
    let bundle: String = format!(
        r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var descriptor = {{
        name: "js-quickjs-plugin",
        contractName: "test.math",
        versionMajor: 0,
        versionMinor: 1,
        versionPatch: 0
    }};
    var iface = {{
        contractLo: {},
        contractHi: {},
        fnCount: {},
        contractName: "test.math",
        version: 0x00010000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [
            function(impl, args, out, arena, bridge) {{ return 0; }},
            function(impl, args, out, arena, bridge) {{ return 0; }},
            function(impl, args, out, arena, bridge) {{ return 0; }}
        ]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#,
        contract_id as u32,
        (contract_id >> 32) as u32,
        fn_count
    );
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "load must succeed: {result:?}");

    // Verify the plugin was registered.
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must be registered");
    assert!(!handle.is_null(), "handle must be valid");

    // Verify function count by probing the VM dispatch.
    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("resolve must succeed");
    // SAFETY: vtable_ptr is a valid pointer returned by resolve.
    let vtable_ref: &GuestContractInterface = unsafe { &*vtable_ptr };
    assert_vm_function_count(vtable_ref, fn_count);
}

// ── Directory path fallback ───────────────────────────────────────────────────

#[test]
fn load_accepts_directory_path() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.dir", 1);

    let bundle: String = make_bundle_js(contract_id, 1, "test.dir");
    let dir: tempfile::TempDir = tempfile::tempdir().expect("tempdir");
    std::fs::write(dir.path().join("bundle.js"), &bundle).expect("write bundle.js");

    let bundle_id: u64 = polyplug_utils::bundle_id("test.dir");
    let manifest_toml: String = format!(
        r#"id = {}
name = "test.dir"
loader = "js-quickjs"
file = "bundle.js"
"#,
        bundle_id
    );
    std::fs::write(dir.path().join("manifest.toml"), &manifest_toml).expect("write manifest.toml");

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = ManifestData {
        id: bundle_id,
        name: "test.dir".to_owned(),
        loader: "js-quickjs".to_owned(),
        file: "bundle.js".to_owned(),
        path: dir.path().to_path_buf(),
        version: String::new(),
        provides: Vec::new(),
        function_count: HashMap::new(),
        dependencies: Vec::new(),
        needs_reinit_on_dep_reload: false,
        bundle_dependencies: Vec::new(),
    };
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(
        result.is_ok(),
        "load from directory path must succeed: {result:?}"
    );

    // Verify the plugin was registered.
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must be registered");
    assert!(!handle.is_null(), "handle must be valid");
}

// ── Syntax error ──────────────────────────────────────────────────────────────

#[test]
fn load_syntax_error_returns_error() {
    let bundle: &str = "this is not valid javascript }{{{";
    let (_dir, path) = write_temp_bundle(bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_err(), "syntax error bundle must return Err");

    // The error must be a JsRuntimePanic mentioning the eval failure.
    let err_str: String = result
        .expect_err("syntax error bundle must return Err")
        .to_string();
    assert!(
        err_str.contains("js-quickjs"),
        "error must mention runtime name: {err_str}"
    );
}

// ── Runtime error ─────────────────────────────────────────────────────────────

#[test]
fn load_runtime_error_returns_error() {
    // Valid JS syntax but throws at runtime.
    let bundle: &str = "throw new Error('intentional runtime error');";
    let (_dir, path) = write_temp_bundle(bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_err(), "runtime error bundle must return Err");

    let err_str: String = result
        .expect_err("runtime error bundle must return Err")
        .to_string();
    assert!(
        err_str.contains("js-quickjs"),
        "error must mention runtime name: {err_str}"
    );
}

// ── Missing polyplug_init function ─────────────────────────────────────────────

#[test]
fn load_bundle_without_polyplug_init_returns_error() {
    // Valid JS that does not define polyplug_init.
    let bundle: &str = "var x = 1 + 2;";
    let (_dir, path) = write_temp_bundle(bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(
        result.is_err(),
        "bundle without polyplug_init must return Err"
    );

    let err_str: String = result
        .expect_err("bundle without polyplug_init must return Err")
        .to_string();
    assert!(
        err_str.contains("init symbol missing"),
        "error must mention init symbol missing: {err_str}"
    );
}

// ── File not found ────────────────────────────────────────────────────────────

#[test]
fn load_nonexistent_file_returns_error() {
    let path: std::path::PathBuf =
        std::path::PathBuf::from("/tmp/polyplug_js_test_nonexistent_bundle_xyz.js");

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = ManifestData {
        id: 0,
        name: "nonexistent".to_owned(),
        loader: "js-quickjs".to_owned(),
        file: "bundle.js".to_owned(),
        path: path
            .parent()
            .expect("bundle path must have a parent directory")
            .to_path_buf(),
        version: String::new(),
        provides: Vec::new(),
        function_count: HashMap::new(),
        dependencies: Vec::new(),
        needs_reinit_on_dep_reload: false,
        bundle_dependencies: Vec::new(),
    };
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_err(), "non-existent file must return Err");
}

// ── BundlePath global injection ───────────────────────────────────────────────

#[test]
fn bundle_path_global_is_injected() {
    // The loader injects `globalThis.bundlePath` before evaluating the bundle.
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.bundlepath", 1);

    // Bundle reads bundlePath; if it is undefined the throw will surface as Err.
    let bundle: String = format!(
        r#"
if (typeof globalThis.bundlePath !== 'string') {{
    throw new Error('bundlePath not injected');
}}
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var descriptor = {{
        name: "js-quickjs-plugin",
        contractName: "test.bundlepath",
        versionMajor: 0,
        versionMinor: 1,
        versionPatch: 0
    }};
    var iface = {{
        contractLo: {},
        contractHi: {},
        fnCount: 1,
        contractName: "test.bundlepath",
        version: 0x00010000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [function(impl, args, out, arena, bridge) {{ return 0; }}]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#,
        contract_id as u32,
        (contract_id >> 32) as u32
    );
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(
        result.is_ok(),
        "bundle reading bundlePath must succeed: {result:?}"
    );
}

// ── polyplug object is accessible in JS ───────────────────────────────────────

#[test]
fn polyplug_object_has_expected_methods() {
    // Verify all expected host methods are present on the bridge object the loader
    // threads into polyplug_init (no `polyplug` global exists — Rule 12), so the
    // check runs INSIDE polyplug_init against the `bridge` argument.
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.methods", 1);

    let bundle: String = format!(
        r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var methods = ['findByContract', 'findByBundle', 'findAllByContract',
                    'resolveGuestContract', 'callHostContract', 'alloc', 'free'];
    for (var i = 0; i < methods.length; i++) {{
        if (typeof bridge[methods[i]] !== 'function') {{
            throw new Error('missing method: ' + methods[i]);
        }}
    }}
    var descriptor = {{
        name: "js-quickjs-plugin",
        contractName: "test.methods",
        versionMajor: 0,
        versionMinor: 1,
        versionPatch: 0
    }};
    var iface = {{
        contractLo: {},
        contractHi: {},
        fnCount: 1,
        contractName: "test.methods",
        version: 0x00010000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [function(impl, args, out, arena, bridge) {{ return 0; }}]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#,
        contract_id as u32,
        (contract_id >> 32) as u32
    );
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(
        result.is_ok(),
        "all polyplug methods must be present: {result:?}"
    );
}

// ── VTable registration — contract_id roundtrip ───────────────────────────────

#[test]
fn vtable_contract_id_roundtrip() {
    // Use a well-known FNV-1a contract — contract_id("image.decode", 1).
    let contract_id: u64 = polyplug_utils::guest_contract_id("image.decode", 1);

    let bundle: String = make_bundle_js(contract_id, 1, "image.decode");
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();
    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    // Verify the plugin was registered with the correct contract_id.
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must be registered");
    assert!(!handle.is_null(), "handle must be valid");
}

// ── VM dispatch verification ──────────────────────────────────────────────────

#[test]
fn vtable_uses_vm_dispatch() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.vm_dispatch", 1);
    let fn_count: u32 = 2;

    let bundle: String = format!(
        r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var descriptor = {{
        name: "js-quickjs-plugin",
        contractName: "test.vm_dispatch",
        versionMajor: 0,
        versionMinor: 1,
        versionPatch: 0
    }};
    var iface = {{
        contractLo: {},
        contractHi: {},
        fnCount: {},
        contractName: "test.vm_dispatch",
        version: 0x00010000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [
            function(impl, args, out, arena, bridge) {{ return 0; }},
            function(impl, args, out, arena, bridge) {{ return 0; }}
        ]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#,
        contract_id as u32,
        (contract_id >> 32) as u32,
        fn_count
    );
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = JsLoader::new(JsConfig {});

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    // Verify the plugin was registered and get its vtable.
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must be registered");
    assert!(!handle.is_null(), "handle must be valid");

    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("resolve must succeed");

    // SAFETY: vtable_ptr is a valid pointer returned by resolve.
    let vtable_ref: &GuestContractInterface = unsafe { &*vtable_ptr };

    assert_vm_function_count(vtable_ref, fn_count);
    assert_eq!(vtable_ref.dispatch_type, DispatchType::VirtualMachine);
    // SAFETY: dispatch_type is VirtualMachine, so accessing .vm is valid.
    // The dispatch function pointer is always non-null (it's js_dispatch).
    assert!(!unsafe { vtable_ref.dispatch.vm.loader_data }.is_null());
}

// ── Memory management helpers ─────────────────────────────────────────────────

#[test]
fn js_alloc_and_free_calls_host_vtable() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.memory", 1);

    // Bundle calls alloc then free.
    // alloc returns [ptr_lo, ptr_hi] tuple; free takes (ptr_lo, ptr_hi, size, align)
    // — the size/align must match the allocation so the host actually frees it.
    let bundle: String = format!(
        r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    // alloc/free run through the threaded bridge (no `polyplug` global — Rule 12).
    var result = bridge.alloc(64);
    var ptr_lo = result[0];
    var ptr_hi = result[1];
    if (ptr_lo !== 0 || ptr_hi !== 0) {{
        bridge.free(ptr_lo, ptr_hi, 64, 1);
    }}
    var descriptor = {{
        name: "js-quickjs-plugin",
        contractName: "test.memory",
        versionMajor: 0,
        versionMinor: 1,
        versionPatch: 0
    }};
    var iface = {{
        contractLo: {},
        contractHi: {},
        fnCount: 1,
        contractName: "test.memory",
        version: 0x00010000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [function(impl, args, out, arena, bridge) {{ return 0; }}]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#,
        contract_id as u32,
        (contract_id >> 32) as u32
    );
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = JsLoader::new(JsConfig {});

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(
        result.is_ok(),
        "bundle with alloc+free must succeed: {result:?}"
    );
}

// ── Thread safety ─────────────────────────────────────────────────────────────

#[test]
fn concurrent_loads_do_not_panic() {
    // Spawn multiple threads each loading a different bundle concurrently.
    // All bundles create _VTABLE globals so load() succeeds.
    // Tests that the shared QJS_RUNTIME and per-Context eval are thread-safe.
    let thread_count: usize = 4;
    let errors: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));

    let handles: Vec<std::thread::JoinHandle<()>> = (0..thread_count)
        .map(|i: usize| {
            let errors_clone: Arc<Mutex<Vec<String>>> = Arc::clone(&errors);
            std::thread::spawn(move || {
                let contract_id: u64 =
                    polyplug_utils::guest_contract_id(&format!("test.concurrent.{i}"), 1);

                let bundle: String =
                    make_bundle_js(contract_id, 1, &format!("test.concurrent.{i}"));
                let (_dir, path) = write_temp_bundle(&bundle);

                let runtime: Arc<Runtime> = RuntimeBuilder::new()
                    .loader(JsLoader::new(JsConfig {}))
                    .build()
                    .expect("runtime build must succeed");
                let loader: JsLoader = JsLoader::new(JsConfig {});

                let manifest: ManifestData = make_manifest(&path, "test.bundle");
                if let Err(e) = loader.load(
                    &manifest,
                    &polyplug::loader::BundleSource::Path(manifest.path.clone()),
                    &runtime,
                ) {
                    let mut guard: std::sync::MutexGuard<'_, Vec<String>> =
                        errors_clone.lock().unwrap_or_else(|e| e.into_inner());
                    guard.push(format!("thread {i}: {e}"));
                }
            })
        })
        .collect();

    for handle in handles {
        handle.join().expect("thread must not panic");
    }

    let errs: std::sync::MutexGuard<'_, Vec<String>> =
        errors.lock().unwrap_or_else(|e| e.into_inner());
    assert!(
        errs.is_empty(),
        "concurrent loads must all succeed: {errs:?}"
    );
}

#[test]
fn multiple_runtimes_on_same_thread_are_isolated() {
    // CRITICAL TEST: Verifies that multiple Runtime instances on the SAME thread
    // have isolated state. This would have FAILED with the old thread-local approach
    // because REGISTRATION_DATA was shared across all Runtime instances on a thread.
    //
    // With the new userdata-based approach, each QuickJS Runtime has its own
    // registration slot stored in its userdata, ensuring complete isolation.

    // Create first runtime and load a plugin with contract_id A
    let contract_id_a: u64 = polyplug_utils::guest_contract_id("test.isolation.a", 1);
    let bundle_a: String = make_bundle_js(contract_id_a, 1, "test.isolation.a");
    let (_dir_a, path_a) = write_temp_bundle(&bundle_a);

    let runtime_a: Arc<Runtime> = RuntimeBuilder::new()
        .loader(JsLoader::new(JsConfig {}))
        .build()
        .expect("runtime_a build must succeed");
    let loader_a: JsLoader = JsLoader::new(JsConfig {});

    let manifest_a: ManifestData = make_manifest(&path_a, "test.bundle.a");
    loader_a
        .load(
            &manifest_a,
            &polyplug::loader::BundleSource::Path(manifest_a.path.clone()),
            &runtime_a,
        )
        .expect("load runtime_a must succeed");

    // Verify plugin A is registered in runtime_a
    let handle_a: GuestContractHandle = runtime_a
        .registry()
        .find(GuestContractId::from_u64(contract_id_a), 0)
        .expect("plugin A must be registered in runtime_a");
    assert!(!handle_a.is_null(), "handle_a must be valid");

    // Create second runtime on the SAME thread and load a plugin with contract_id B
    let contract_id_b: u64 = polyplug_utils::guest_contract_id("test.isolation.b", 1);
    let bundle_b: String = make_bundle_js(contract_id_b, 1, "test.isolation.b");
    let (_dir_b, path_b) = write_temp_bundle(&bundle_b);

    let runtime_b: Arc<Runtime> = RuntimeBuilder::new()
        .loader(JsLoader::new(JsConfig {}))
        .build()
        .expect("runtime_b build must succeed");
    let loader_b: JsLoader = JsLoader::new(JsConfig {});

    let manifest_b: ManifestData = make_manifest(&path_b, "test.bundle.b");
    loader_b
        .load(
            &manifest_b,
            &polyplug::loader::BundleSource::Path(manifest_b.path.clone()),
            &runtime_b,
        )
        .expect("load runtime_b must succeed");

    // Verify plugin B is registered in runtime_b
    let handle_b: GuestContractHandle = runtime_b
        .registry()
        .find(GuestContractId::from_u64(contract_id_b), 0)
        .expect("plugin B must be registered in runtime_b");
    assert!(!handle_b.is_null(), "handle_b must be valid");

    // CRITICAL: Verify that runtime_a still has plugin A (not corrupted by runtime_b)
    // With the old thread-local approach, loading runtime_b would have overwritten
    // the registration data, causing this check to fail.
    let handle_a_still_valid: GuestContractHandle = runtime_a
        .registry()
        .find(GuestContractId::from_u64(contract_id_a), 0)
        .expect("plugin A must still be registered in runtime_a");
    assert!(
        !handle_a_still_valid.is_null(),
        "handle_a must still be valid after runtime_b was created"
    );

    // Verify runtime_b does NOT have plugin A (isolation)
    let handle_a_in_b: Result<GuestContractHandle, polyplug::error::RegistryError> = runtime_b
        .registry()
        .find(GuestContractId::from_u64(contract_id_a), 0);
    assert!(
        handle_a_in_b.is_err()
            || handle_a_in_b
                .as_ref()
                .ok()
                .map(|h| h.is_null())
                .unwrap_or(true),
        "runtime_b must NOT have plugin A (isolation)"
    );

    // Verify runtime_a does NOT have plugin B (isolation)
    let handle_b_in_a: Result<GuestContractHandle, polyplug::error::RegistryError> = runtime_a
        .registry()
        .find(GuestContractId::from_u64(contract_id_b), 0);
    assert!(
        handle_b_in_a.is_err()
            || handle_b_in_a
                .as_ref()
                .ok()
                .map(|h| h.is_null())
                .unwrap_or(true),
        "runtime_a must NOT have plugin B (isolation)"
    );
}

#[test]
fn sequential_loads_of_different_contracts_all_succeed() {
    // Sequential re-use of the same JsLoader for multiple bundles.
    let loader: JsLoader = JsLoader::new(JsConfig {});
    let runtime: Arc<Runtime> = make_runtime();

    for i in 0..4_u32 {
        let contract_id: u64 =
            polyplug_utils::guest_contract_id(&format!("test.sequential.{i}"), 1);

        let bundle: String = make_bundle_js(contract_id, 1, &format!("test.sequential.{i}"));
        let (_dir, path) = write_temp_bundle(&bundle);

        let manifest: ManifestData = make_manifest(&path, "test.bundle");
        let result: Result<(), polyplug::error::LoaderError> = loader.load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        );
        assert!(
            result.is_ok(),
            "sequential load {i} must succeed: {result:?}"
        );
    }
}

// ── VM Dispatch Call Tests ─────────────────────────────────────────────────────

#[test]
fn dispatch_vm_call_works_correctly() {
    // This test actually invokes dispatch.vm.call to verify the JS function
    // can be called through the ABI dispatch mechanism.
    use polyplug_abi::AbiError;
    use polyplug_abi::AbiErrorCode;

    let contract_id: u64 = polyplug_utils::guest_contract_id("test.dispatch.call", 1);
    let bundle: String = make_bundle_js(contract_id, 1, "test.dispatch.call");
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = JsLoader::new(JsConfig {});

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "load must succeed: {result:?}");

    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must be registered");

    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("resolve must succeed");

    // SAFETY: vtable_ptr is a valid pointer returned by resolve.
    let vtable_ref: &GuestContractInterface = unsafe { &*vtable_ptr };

    assert_eq!(vtable_ref.dispatch_type, DispatchType::VirtualMachine);

    let mut call_result: AbiError = AbiError::ok();
    // SAFETY: dispatch_type is VirtualMachine, so accessing .vm is valid.
    // dispatch.vm.call is js_dispatch, loader_data is valid.
    unsafe {
        (vtable_ref.dispatch.vm.call)(
            vtable_ref.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            0, // fn_id = 0 (first function)
            core::ptr::null::<()>(),
            core::ptr::null_mut::<()>(),
            core::ptr::null_mut(),
            &mut call_result as *mut AbiError,
        );
    }

    assert_eq!(
        call_result.code,
        AbiErrorCode::Ok as u32,
        "dispatch.vm.call must return Ok, got code={}",
        call_result.code
    );
}

// ── StringView.toString() Tests ────────────────────────────────────────────────

#[test]
fn stringview_to_string_handles_empty_string() {
    // Test that StringView.toString() handles empty strings (len=0).
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.stringview.empty", 1);

    let bundle: String = format!(
        r#"
var testResult = null;

// Test empty string handling - should return '' without reading memory
function stringViewToString(sv) {{
    if (!sv || sv.len === 0) return '';
    return 'non-empty';
}}

var result = stringViewToString({{ ptr_lo: 0, ptr_hi: 0, len: 0 }});
if (result === '') {{
    testResult = "PASS";
}} else {{
    throw new Error("expected empty string, got: " + result);
}}

function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var iface = {{
        contractLo: {},
        contractHi: {},
        fnCount: 1,
        contractName: "test.stringview.empty",
        version: 0x00010000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [function(impl, args, out, arena, bridge) {{ return 0; }}]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#,
        contract_id as u32,
        (contract_id >> 32) as u32
    );
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = JsLoader::new(JsConfig {});

    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "Empty string test must succeed: {result:?}");
}

// ── Hot-reload ──────────────────────────────────────────────────────────────────

#[test]
fn js_reload_disabled_returns_error() {
    // With hot-reload disabled in the runtime config, the runtime gate (which now owns
    // the hot-reload check — the js loader's `reload` no longer inspects config) must
    // reject the reload up front. The loader still advertises
    // `supports_hot_reload() == true`, so the config flag is the sole reason for refusal.
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.reload.disabled", 1);

    let bundle: String = make_bundle_js(contract_id, 1, "test.reload.disabled");
    let (_dir, path) = write_temp_bundle(&bundle);

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();
    assert!(
        loader.supports_hot_reload(),
        "the js loader supports hot-reload; only the config flag must gate it here"
    );

    let result: Result<(), RuntimeError> = runtime.reload_bundle(path.as_path());
    assert!(
        matches!(result, Err(RuntimeError::HotReloadDisabled)),
        "reload_bundle with hot-reload disabled must return HotReloadDisabled: {result:?}"
    );
}

#[test]
fn js_reload_reinitializes_contracts() {
    // Load a bundle, then reload it through the runtime and verify the contract
    // remains resolvable after the interface swap.
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.reload.contract", 1);

    let bundle: String = make_bundle_js(contract_id, 1, "test.reload.contract");
    let (dir, _path) = write_temp_bundle_with_name(&bundle, "test.reload.contract");

    let runtime: Arc<Runtime> = make_runtime_hot_reload();

    runtime
        .load_bundle(dir.path())
        .expect("initial load must succeed");

    let handle_before: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must be registered after load");
    assert!(!handle_before.is_null(), "handle must be valid after load");

    let reload_result: Result<(), RuntimeError> = runtime.reload_bundle(dir.path());
    assert!(
        reload_result.is_ok(),
        "reload_bundle must succeed: {reload_result:?}"
    );

    let handle_after: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must still be registered after reload");
    assert!(!handle_after.is_null(), "handle must be valid after reload");

    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle_after)
        .expect("resolve must succeed after reload");
    // SAFETY: vtable_ptr is a valid pointer returned by resolve.
    let vtable_ref: &GuestContractInterface = unsafe { &*vtable_ptr };
    assert_eq!(vtable_ref.dispatch_type, DispatchType::VirtualMachine);
}

/// After a successful load, the contract must be attributed to the bundle's REAL
/// id in the registry — not bundle 0. The JS `register_guest_contract` call runs
/// after `polyplug_init` RETURNS its registrations array, so the init-bundle window
/// must stay open across that call for `host_register_guest_contract` to attribute
/// it correctly. Invalidating by the real id must then remove it.
#[test]
fn registrations_attributed_to_real_bundle_id() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.attribution.contract", 1);
    let bundle: String = make_bundle_js(contract_id, 1, "test.attribution.contract");
    let (dir, _path) = write_temp_bundle_with_name(&bundle, "test.attribution.contract");
    let bundle_id: u64 = polyplug_utils::bundle_id("test.attribution.contract");

    let runtime: Arc<Runtime> = make_runtime();
    runtime
        .load_bundle(dir.path())
        .expect("initial load must succeed");

    // The contract must be findable under the REAL bundle id.
    let by_real: Result<GuestContractHandle, polyplug::error::RegistryError> =
        runtime.find_guest_contract_by_bundle(bundle_id, contract_id, 0);
    assert!(
        by_real.is_ok(),
        "contract must be attributed to the real bundle id {bundle_id}, not bundle 0"
    );

    // And it must NOT be attributed to bundle 0.
    let by_zero: Result<GuestContractHandle, polyplug::error::RegistryError> =
        runtime.find_guest_contract_by_bundle(0, contract_id, 0);
    assert!(
        by_zero.is_err(),
        "contract must not be attributed to bundle 0"
    );

    // Invalidating by the real bundle id must remove the contract from the registry.
    runtime
        .registry()
        .invalidate_bundle(polyplug_utils::BundleId::from_u64(bundle_id))
        .expect("invalidate by real bundle id must succeed");
    let after: Result<GuestContractHandle, polyplug::error::RegistryError> = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0);
    assert!(
        after.is_err(),
        "contract must be gone after invalidating the real bundle id"
    );
}

// ── BundleSource::Code / Bytes ──────────────────────────────────────────────────

/// Absolute path to the shared JS fixture's `bundle.js` at the workspace root.
fn fixture_bundle_js_path() -> std::path::PathBuf {
    std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/test_plugin_js/bundle.js")
}

/// Build a ManifestData matching the shared `test_plugin_js` fixture, with the
/// given on-disk bundle directory (empty for in-memory sources).
fn fixture_manifest(bundle_dir: std::path::PathBuf) -> ManifestData {
    let mut function_count: HashMap<String, u32> = HashMap::new();
    function_count.insert("test.add@1".to_owned(), 5);
    ManifestData {
        id: polyplug_utils::bundle_id("test_bundle"),
        name: "test_bundle".to_owned(),
        loader: "js-quickjs".to_owned(),
        file: "bundle.js".to_owned(),
        path: bundle_dir,
        version: "1.0.0".to_owned(),
        provides: vec!["test.add@1".to_owned()],
        function_count,
        dependencies: Vec::new(),
        needs_reinit_on_dep_reload: false,
        bundle_dependencies: Vec::new(),
    }
}

/// Dispatch the fixture's `add` function (fn_id 0) with two i32 args, returning
/// the i32 written to the out buffer.
fn dispatch_add(runtime: &Runtime, contract_id: u64, a: i32, b: i32) -> i32 {
    use polyplug_abi::AbiError;
    use polyplug_abi::AbiErrorCode;

    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("plugin must be registered");
    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("resolve must succeed");
    // SAFETY: vtable_ptr is a valid pointer returned by resolve.
    let vtable_ref: &GuestContractInterface = unsafe { &*vtable_ptr };
    assert_eq!(vtable_ref.dispatch_type, DispatchType::VirtualMachine);

    // The fixture's `add` reads two i32 from argsPtr / argsPtr+4 and writes the
    // sum to outPtr. Lay out a packed [a, b] args buffer and a single-i32 out.
    let args: [i32; 2] = [a, b];
    let mut out: i32 = 0;
    let mut result: AbiError = AbiError::ok();
    // SAFETY: dispatch.vm.call is js_dispatch; args points at two valid i32 and
    // out at one valid i32, matching what the guest reads/writes.
    unsafe {
        (vtable_ref.dispatch.vm.call)(
            vtable_ref.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            0,
            args.as_ptr() as *const (),
            &mut out as *mut i32 as *mut (),
            core::ptr::null_mut(),
            &mut result as *mut AbiError,
        );
    }
    assert_eq!(result.code, AbiErrorCode::Ok as u32, "add must dispatch Ok");
    out
}

/// Loading the fixture via `BundleSource::Code` (in-memory source text) registers
/// the same contract and dispatches to the same result as path-based loading.
#[test]
fn load_code_source_has_parity_with_path() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.add", 1);

    // Path-loaded reference: load the on-disk fixture directory and dispatch add.
    let fixture_dir: std::path::PathBuf = fixture_bundle_js_path()
        .parent()
        .expect("fixture must have a parent directory")
        .to_path_buf();
    let runtime_path: Arc<Runtime> = make_runtime();
    runtime_path
        .load_bundle(&fixture_dir)
        .expect("path load of fixture must succeed");
    let path_result: i32 = dispatch_add(&runtime_path, contract_id, 2, 3);
    assert_eq!(path_result, 5, "path-loaded add(2,3) must be 5");

    // Code-loaded: read the same source to a String and load it via Code.
    let source: String =
        std::fs::read_to_string(fixture_bundle_js_path()).expect("read fixture bundle.js");
    let runtime_code: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = fixture_manifest(std::path::PathBuf::new());
    runtime_code
        .load_bundle_from_source(manifest, BundleSource::Code(source))
        .expect("code load of fixture must succeed");
    let code_result: i32 = dispatch_add(&runtime_code, contract_id, 2, 3);

    assert_eq!(
        code_result, path_result,
        "Code-loaded dispatch must match path-loaded dispatch"
    );
}

/// Loading the fixture via `BundleSource::Bytes` (valid UTF-8) takes the same path
/// as Code and registers the same contract.
#[test]
fn load_bytes_source_valid_utf8_succeeds() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.add", 1);

    let source: Vec<u8> = std::fs::read(fixture_bundle_js_path()).expect("read fixture bundle.js");
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = fixture_manifest(std::path::PathBuf::new());
    runtime
        .load_bundle_from_source(manifest, BundleSource::Bytes(source))
        .expect("bytes load of fixture must succeed");

    let result: i32 = dispatch_add(&runtime, contract_id, 7, 4);
    assert_eq!(result, 11, "bytes-loaded add(7,4) must be 11");
}

/// `BundleSource::Bytes` carrying invalid UTF-8 yields a structured
/// `LoaderError::InvalidSourceEncoding`, never a string error or a panic.
#[test]
fn load_bytes_source_invalid_utf8_returns_structured_error() {
    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();

    // 0xFF is never valid in a UTF-8 sequence.
    let invalid: Vec<u8> = vec![0xFF, 0xFE, 0x00, 0x01];
    let manifest: ManifestData = fixture_manifest(std::path::PathBuf::new());
    let result: Result<(), LoaderError> =
        loader.load(&manifest, &BundleSource::Bytes(invalid), &runtime);

    assert!(
        matches!(
            result,
            Err(LoaderError::InvalidSourceEncoding {
                loader: "js-quickjs",
                source_kind: "bytes",
                ..
            })
        ),
        "invalid UTF-8 bytes must yield InvalidSourceEncoding: {result:?}"
    );
}

// ── callHostContract from JS: instance lifecycle + bounds checks ───────────────

use core::sync::atomic::AtomicUsize;
use core::sync::atomic::Ordering;
use polyplug_abi::HostContractInstance;
use polyplug_abi::HostContractInterface;

// The counting host contract's create/destroy callbacks are plain `extern "C"`
// functions and cannot capture per-test state, so they share these process-wide
// counters. The tests that observe exact counts therefore serialize on TEST_LOCK
// (held for the whole test body) and reset the counters under it.
static CREATE_COUNT: AtomicUsize = AtomicUsize::new(0);
static DESTROY_COUNT: AtomicUsize = AtomicUsize::new(0);
static COUNTER_LOCK: Mutex<()> = Mutex::new(());

/// Counting create_instance: bumps CREATE_COUNT and returns a unique non-null
/// instance pointer (the running count, +1 so it is never null).
///
/// # Safety
/// Matches the `HostContractInterface::create_instance` ABI signature.
unsafe extern "C" fn counting_create_instance(
    _this: *const HostContractInterface,
    _args: *const (),
    out_instance: *mut HostContractInstance,
) {
    let n: usize = CREATE_COUNT.fetch_add(1, Ordering::SeqCst);
    // SAFETY: out_instance is a valid, writable HostContractInstance slot provided
    // by the host runtime per the create_instance out-param ABI.
    unsafe {
        *out_instance = HostContractInstance {
            data: (n + 1) as *mut core::ffi::c_void,
        };
    }
}

/// Counting destroy_instance: bumps DESTROY_COUNT. No real memory to free (the
/// "instance" is just an integer used as a pointer).
///
/// # Safety
/// Matches the `HostContractInterface::destroy_instance` ABI signature.
unsafe extern "C" fn counting_destroy_instance(
    _this: *const HostContractInterface,
    _instance: HostContractInstance,
) {
    DESTROY_COUNT.fetch_add(1, Ordering::SeqCst);
}

/// A no-op native host-contract function that writes `AbiError::ok()` through its
/// out-param.
///
/// # Safety
/// Matches the native dispatch signature `(state, args, out, out_err) -> ()`.
unsafe extern "C" fn host_noop_fn(
    _state: *const core::ffi::c_void,
    _args: *const core::ffi::c_void,
    _out: *mut core::ffi::c_void,
    out_err: *mut polyplug_abi::AbiError,
) {
    // SAFETY: out_err is a valid, writable AbiError slot supplied by the native
    // dispatch caller per the out-param ABI.
    unsafe {
        *out_err = polyplug_abi::AbiError::ok();
    }
}

/// `Sync` wrapper around a 'static read-only function-pointer table so it can live
/// in a `static`. Function pointers are safe to share across threads.
#[repr(transparent)]
struct HostFnTable([*const (); 1]);
// SAFETY: the table holds only 'static read-only function pointers; sharing them
// across threads is sound (the functions handle their own synchronization).
unsafe impl Sync for HostFnTable {}

// A single 'static native function table for the counting host contract.
static HOST_NOOP_FNS: HostFnTable = HostFnTable([host_noop_fn as *const ()]);

/// Build and leak a non-singleton counting host contract interface with one
/// native function. `Box::leak` gives the required `&'static` lifetime.
fn leak_counting_host_contract(contract_id: u64, major: u32) -> &'static HostContractInterface {
    Box::leak(Box::new(HostContractInterface {
        contract_id: polyplug_utils::HostContractId::from(contract_id),
        contract_version: polyplug_abi::types::Version {
            major,
            minor: 0,
            patch: 0,
        },
        singleton: false,
        dispatch_type: DispatchType::Native,
        runtime: core::ptr::null_mut(),
        user_data: core::ptr::null_mut(),
        create_instance: counting_create_instance,
        destroy_instance: counting_destroy_instance,
        dispatch: polyplug_abi::DispatchMechanisms {
            native: polyplug_abi::NativeDispatch {
                function_count: 1,
                functions: HOST_NOOP_FNS.0.as_ptr(),
            },
        },
    }))
}

/// Inline JS bundle whose single guest function calls
/// `bridge.callHostContract(lo, hi, minVer, fnId, argsPtr, outPtr)` and returns
/// the host call's AbiError code. The bridge is threaded into the dispatch wrapper
/// as its final argument (no `polyplug` global — Rule 12). The guest contract id /
/// name are parameterised so each test registers a distinct contract.
fn host_caller_bundle_source(
    guest_contract_id: u64,
    guest_name: &str,
    host_contract_id: u64,
    host_fn_id: u32,
) -> String {
    let guest_lo: u32 = (guest_contract_id & 0xFFFF_FFFF) as u32;
    let guest_hi: u32 = (guest_contract_id >> 32) as u32;
    let host_lo: u32 = (host_contract_id & 0xFFFF_FFFF) as u32;
    let host_hi: u32 = (host_contract_id >> 32) as u32;
    format!(
        r#"
function callHost(impl, argsPtr, outPtr, arena, bridge) {{
    // callHostContract(contractLo, contractHi, minVersion, fnId, argsPtr, outPtr).
    // minVersion is the PACKED version (major << 16 | minor); major 1 -> 0x10000.
    return bridge.callHostContract({host_lo}, {host_hi}, 0x10000, {host_fn_id}, argsPtr, outPtr);
}}

function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var iface = {{
        contractLo: {guest_lo} >>> 0,
        contractHi: {guest_hi} >>> 0,
        fnCount: 1,
        contractName: "{guest_name}",
        version: 0x10000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [callHost]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#
    )
}

/// Dispatch the guest's single function (fn_id 0), which calls callHostContract
/// and RETURNS that host call's AbiError code. `js_dispatch` surfaces the JS
/// return value as the dispatch's `AbiError.code`, so the returned code IS the
/// host-call result code (Ok on success, FunctionNotAvailable on a rejected fn_id).
fn dispatch_host_caller(runtime: &Runtime, guest_contract_id: u64) -> u32 {
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(guest_contract_id), 0)
        .expect("guest contract must be registered");
    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("resolve must succeed");
    // SAFETY: vtable_ptr is a valid pointer returned by resolve.
    let vtable_ref: &GuestContractInterface = unsafe { &*vtable_ptr };
    let mut out: i32 = 0;
    let mut result: polyplug_abi::AbiError = polyplug_abi::AbiError::ok();
    // SAFETY: dispatch.vm.call is js_dispatch; the guest fn forwards the (unused)
    // args/out pointers straight into callHostContract.
    unsafe {
        (vtable_ref.dispatch.vm.call)(
            vtable_ref.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            0,
            core::ptr::null::<()>(),
            &mut out as *mut i32 as *mut (),
            core::ptr::null_mut(),
            &mut result as *mut polyplug_abi::AbiError,
        );
    }
    result.code
}

/// B5 regression: calling a NON-singleton host contract from JS must destroy the
/// freshly-minted instance after each dispatch. Calling twice must yield exactly
/// two creates and two destroys — previously the instance leaked every call.
#[test]
fn callhostcontract_destroys_non_singleton_instance_each_call() {
    // Serialize with the other counter-observing test; reset counters under the lock.
    let _guard: std::sync::MutexGuard<'_, ()> =
        COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    CREATE_COUNT.store(0, Ordering::SeqCst);
    DESTROY_COUNT.store(0, Ordering::SeqCst);

    let guest_name: &str = "jstest.hostcaller_lifecycle";
    let guest_id: u64 = polyplug_utils::guest_contract_id(guest_name, 1);
    let host_name: &str = "jstest.counting_host_lifecycle";
    let host_id: u64 = polyplug_utils::host_contract_id(host_name, 1);

    let runtime: Arc<Runtime> = make_runtime();
    runtime
        .register_host_contract(host_id, leak_counting_host_contract(host_id, 1))
        .expect("host contract registration must succeed");

    let source: String = host_caller_bundle_source(guest_id, guest_name, host_id, 0);
    let manifest: ManifestData = make_manifest_named(guest_name);
    runtime
        .load_bundle_from_source(manifest, BundleSource::Code(source))
        .expect("guest bundle load must succeed");

    let code1: u32 = dispatch_host_caller(&runtime, guest_id);
    assert_eq!(
        code1,
        polyplug_abi::AbiErrorCode::Ok as u32,
        "first host call must succeed"
    );
    let code2: u32 = dispatch_host_caller(&runtime, guest_id);
    assert_eq!(
        code2,
        polyplug_abi::AbiErrorCode::Ok as u32,
        "second host call must succeed"
    );

    assert_eq!(
        CREATE_COUNT.load(Ordering::SeqCst),
        2,
        "two calls must mint two instances"
    );
    assert_eq!(
        DESTROY_COUNT.load(Ordering::SeqCst),
        2,
        "each non-singleton instance must be destroyed after its dispatch (no leak)"
    );
}

/// B4 regression: calling callHostContract with an out-of-range fn_id must return
/// FunctionNotAvailable instead of indexing past the host function table (UB /
/// crash). The bounds check must also destroy the non-singleton instance it took.
#[test]
fn callhostcontract_out_of_range_fn_id_returns_function_not_available() {
    // Serialize with the other counter-observing test; reset counters under the lock.
    let _guard: std::sync::MutexGuard<'_, ()> =
        COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    CREATE_COUNT.store(0, Ordering::SeqCst);
    DESTROY_COUNT.store(0, Ordering::SeqCst);

    let guest_name: &str = "jstest.hostcaller_bounds";
    let guest_id: u64 = polyplug_utils::guest_contract_id(guest_name, 1);
    let host_name: &str = "jstest.counting_host_bounds";
    let host_id: u64 = polyplug_utils::host_contract_id(host_name, 1);

    let runtime: Arc<Runtime> = make_runtime();
    runtime
        .register_host_contract(host_id, leak_counting_host_contract(host_id, 1))
        .expect("host contract registration must succeed");

    // The host contract has exactly one function (fn_id 0); ask for fn_id 5.
    let source: String = host_caller_bundle_source(guest_id, guest_name, host_id, 5);
    let manifest: ManifestData = make_manifest_named(guest_name);
    runtime
        .load_bundle_from_source(manifest, BundleSource::Code(source))
        .expect("guest bundle load must succeed");

    let code: u32 = dispatch_host_caller(&runtime, guest_id);
    assert_eq!(
        code,
        polyplug_abi::AbiErrorCode::FunctionNotAvailable as u32,
        "out-of-range fn_id must yield FunctionNotAvailable, not a crash"
    );

    // The bounds-check path still took (and must release) a non-singleton instance.
    assert_eq!(
        CREATE_COUNT.load(Ordering::SeqCst),
        1,
        "one call mints one instance even when the fn_id is rejected"
    );
    assert_eq!(
        DESTROY_COUNT.load(Ordering::SeqCst),
        1,
        "the instance must be destroyed even on the bounds-check bail-out (no leak)"
    );
}

/// Build a ManifestData for an in-memory JS guest bundle with the given contract
/// name (used as bundle name; provides one function).
fn make_manifest_named(name: &str) -> ManifestData {
    let mut function_count: HashMap<String, u32> = HashMap::new();
    function_count.insert(format!("{name}@1"), 1);
    ManifestData {
        id: polyplug_utils::bundle_id(name),
        name: name.to_owned(),
        loader: "js-quickjs".to_owned(),
        file: "bundle.js".to_owned(),
        path: std::path::PathBuf::new(),
        version: "1.0.0".to_owned(),
        provides: vec![format!("{name}@1")],
        function_count,
        dependencies: Vec::new(),
        needs_reinit_on_dep_reload: false,
        bundle_dependencies: Vec::new(),
    }
}

// ── Guest logging — the threaded `bridge.log` capability ─────────────────────

/// A guest calling the threaded `bridge.log(level, scope, message)` capability
/// mid-dispatch must deliver (level, scope, message) verbatim through
/// the host logger installed via `RuntimeBuilder::logger`, and an out-of-range
/// level must clamp to `LogLevel::Error`. The bridge runs inside `js_dispatch`'s
/// `Context::with` (the QuickJS VM lock is held by the calling thread) — this
/// test also proves that path is deadlock-free.
#[test]
fn guest_log_bridge_delivers_records_and_clamps_level() {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.guest.log", 1);
    let contract_lo: u32 = contract_id as u32;
    let contract_hi: u32 = (contract_id >> 32) as u32;
    let bundle: String = format!(
        r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {{
    var iface = {{
        contractLo: {contract_lo},
        contractHi: {contract_hi},
        fnCount: 1,
        contractName: "test.guest.log",
        version: 0x00010000,
        factory: function(bridge, hostLo, hostHi) {{ return {{}}; }},
        functions: [
            function(impl, args, out, arena, bridge) {{
                bridge.log(3, "guest.test-log", "hello from js guest");
                bridge.log(99, "guest.test-log", "out of range level");
                return 0;
            }}
        ]
    }};
    var registrations = [{{
        contractLo: iface.contractLo,
        contractHi: iface.contractHi,
        interface: iface,
        fnCount: iface.fnCount,
        contractName: iface.contractName,
        version: iface.version
    }}];
    return [registrations, {{ code: 0, message: "" }}];
}}
"#
    );
    let (_dir, path) = write_temp_bundle(&bundle);

    let records: Arc<Mutex<Vec<(LogLevel, String, String)>>> = Arc::new(Mutex::new(Vec::new()));
    let records_clone: Arc<Mutex<Vec<(LogLevel, String, String)>>> = Arc::clone(&records);
    let runtime: Arc<Runtime> = RuntimeBuilder::new()
        .logger(move |level: LogLevel, scope: &str, msg: &str| {
            records_clone.lock().expect("records lock").push((
                level,
                scope.to_owned(),
                msg.to_owned(),
            ));
        })
        .build()
        .expect("runtime build must succeed");

    let loader: JsLoader = JsLoader::new(JsConfig {});
    let manifest: ManifestData = make_manifest(&path, "test.bundle");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("logging bundle must load");

    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("test.guest.log@1 must be registered");
    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("handle must resolve to vtable");
    // SAFETY: vtable_ptr is a valid GuestContractInterface owned by the registry.
    let vtable: &GuestContractInterface = unsafe { &*vtable_ptr };

    let mut result: AbiError = AbiError::ok();
    // SAFETY: dispatch.vm.call is js_dispatch, loader_data is valid, and the
    // logging function never reads its (args, out) pointers.
    unsafe {
        (vtable.dispatch.vm.call)(
            vtable.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            0,
            core::ptr::null::<()>(),
            core::ptr::null_mut::<()>(),
            core::ptr::null_mut(),
            &mut result as *mut AbiError,
        );
    }
    assert_eq!(
        result.code,
        AbiErrorCode::Ok as u32,
        "logging guest function must dispatch Ok, got code={}",
        result.code
    );

    let captured: Vec<(LogLevel, String, String)> = records.lock().expect("records lock").clone();
    assert!(
        captured.contains(&(
            LogLevel::Info,
            String::from("guest.test-log"),
            String::from("hello from js guest"),
        )),
        "expected verbatim (Info, \"guest.test-log\", \"hello from js guest\") record, got: {captured:?}"
    );
    assert!(
        captured.contains(&(
            LogLevel::Error,
            String::from("guest.test-log"),
            String::from("out of range level"),
        )),
        "expected out-of-range level 99 to clamp to Error, got: {captured:?}"
    );
}

// ── polyplug_init returned AbiError ───────────────────────────────────────────

/// A plugin whose `polyplug_init` registers a valid vtable but returns a
/// non-zero AbiError must FAIL to load with that code and message. Before
/// the fix the loader discarded the return value and treated the bundle
/// as loaded.
#[test]
fn load_init_returning_error_code_fails_load() {
    let bundle: &str = r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {
    var iface = {
        factory: function(bridge, hostLo, hostHi) { return {}; },
        functions: [function(impl, args, out, arena, bridge) { return 0; }]
    };
    var registrations = [{
        contractLo: 0x1, contractHi: 0x0, interface: iface,
        fnCount: 1, contractName: "test.initerr", version: 0x00010000
    }];
    return [registrations, { code: 1, message: "init refused" }];
}
"#;
    let (_dir, path) = write_temp_bundle_with_name(bundle, "test.initerr");

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();
    let manifest: ManifestData = make_manifest(&path, "test.initerr");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_err(), "non-zero init code must fail the load");
    let err_str: String = result
        .expect_err("expected Err for non-zero init code")
        .to_string();
    assert!(
        err_str.contains("returned error code 1") && err_str.contains("init refused"),
        "error must carry the returned code and message, got: {err_str}"
    );
}

/// A non-zero AbiError `code` in the `[registrations, abiError]` return fails the
/// load even when no `message` is provided, surfacing the bare code.
#[test]
fn load_init_returning_error_code_without_message_fails_load() {
    let bundle: &str = r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {
    var iface = {
        factory: function(bridge, hostLo, hostHi) { return {}; },
        functions: [function(impl, args, out, arena, bridge) { return 0; }]
    };
    var registrations = [{
        contractLo: 0x2, contractHi: 0x0, interface: iface,
        fnCount: 1, contractName: "test.initnum", version: 0x00010000
    }];
    return [registrations, { code: 3, message: "" }];
}
"#;
    let (_dir, path) = write_temp_bundle_with_name(bundle, "test.initnum");

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();
    let manifest: ManifestData = make_manifest(&path, "test.initnum");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(
        result.is_err(),
        "non-zero init code must fail the load even without a message"
    );
    let err_str: String = result
        .expect_err("expected Err for non-zero init code")
        .to_string();
    assert!(
        err_str.contains("returned error code 3"),
        "error must carry the returned code, got: {err_str}"
    );
}

// ── malformed registration interfaces ─────────────────────────────────────────

/// A registration whose `interface` lacks a `functions` array must fail the load
/// with a precise error naming the missing field.
#[test]
fn register_interface_without_functions_array_fails_precisely() {
    let bundle: &str = r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {
    var registrations = [{
        contractLo: 0x3, contractHi: 0x0,
        interface: { notFunctions: [], factory: function(bridge, hostLo, hostHi) { return {}; } },
        fnCount: 1, contractName: "test.malformed", version: 0x00010000
    }];
    return [registrations, { code: 0, message: "" }];
}
"#;
    let (_dir, path) = write_temp_bundle_with_name(bundle, "test.malformed");

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();
    let manifest: ManifestData = make_manifest(&path, "test.malformed");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_err(), "malformed interface must fail the load");
    let err_str: String = result
        .expect_err("expected Err for malformed interface")
        .to_string();
    assert!(
        err_str.contains("no 'functions' array"),
        "error must name the missing functions array, got: {err_str}"
    );
}

/// A registration whose declared fnCount exceeds the functions array must fail
/// the load naming the missing index.
#[test]
fn register_interface_with_short_functions_array_fails_precisely() {
    let bundle: &str = r#"
function polyplug_init(host_lo, host_hi, ctx_lo, ctx_hi, bridge) {
    var iface = {
        factory: function(bridge, hostLo, hostHi) { return {}; },
        functions: [function(impl, args, out, arena, bridge) { return 0; }]
    };
    var registrations = [{
        contractLo: 0x4, contractHi: 0x0, interface: iface,
        fnCount: 2, contractName: "test.short", version: 0x00010000
    }];
    return [registrations, { code: 0, message: "" }];
}
"#;
    let (_dir, path) = write_temp_bundle_with_name(bundle, "test.short");

    let runtime: Arc<Runtime> = make_runtime();
    let loader: JsLoader = make_loader();
    let manifest: ManifestData = make_manifest(&path, "test.short");
    let result: Result<(), polyplug::error::LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_err(), "short functions array must fail the load");
    let err_str: String = result
        .expect_err("expected Err for short functions array")
        .to_string();
    assert!(
        err_str.contains("functions[1] is missing"),
        "error must name the missing function index, got: {err_str}"
    );
}