tsrun 0.1.23

A TypeScript interpreter designed for embedding in applications
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
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
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
//! Order system integration tests
//!
//! These tests demonstrate how the order system can be used for real-world async operations
//! like fetch(), setTimeout(), and file I/O. The global functions are implemented in TypeScript
//! using the request syscall from tsrun:host.

use super::{run, run_to_completion};
use serde_json::json;
use tsrun::{
    InternalModule, Interpreter, InterpreterConfig, JsString, JsValue, OrderId, OrderResponse,
    RuntimeValue, StepResult, api, create_eval_internal_module, value::PropertyKey,
};

// ═══════════════════════════════════════════════════════════════════════════════
// TypeScript Globals Source
// ═══════════════════════════════════════════════════════════════════════════════

/// TypeScript source that defines global functions using the order system.
/// This demonstrates how hosts can extend the interpreter with custom async operations.
///
/// With blocking request() semantics:
/// - request() suspends immediately, host provides any value
/// - Host can return plain values or Promises
/// - For parallel operations, host returns Promises and resolves them later
const GLOBALS_SOURCE: &str = r#"
import { order } from "tsrun:host";

// sleep(ms) - Returns Promise that resolves after delay
globalThis.sleep = async function(ms: number): Promise<void> {
    await order({ type: "sleep", delay: ms });
};

// fetch(url, options?) - Returns Promise with response
globalThis.fetch = async function(url: string, options?: {
    method?: string;
    body?: string;
    headers?: Record<string, string>;
}): Promise<any> {
    return await order({
        type: "fetch",
        url: url,
        method: options?.method || "GET",
        body: options?.body,
        headers: options?.headers
    });
};

// readFile(path) - Returns Promise with file content
globalThis.readFile = async function(path: string): Promise<string> {
    return await order({ type: "readFile", path: path });
};

// writeFile(path, content) - Returns Promise when complete
globalThis.writeFile = async function(path: string, content: string): Promise<string> {
    return await order({ type: "writeFile", path: path, content: content });
};
"#;

// ═══════════════════════════════════════════════════════════════════════════════
// Test Helpers
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a runtime with tsrun:host and eval:globals modules
fn create_test_interp() -> Interpreter {
    let config = InterpreterConfig {
        internal_modules: vec![
            create_eval_internal_module(),
            InternalModule::source("eval:globals", GLOBALS_SOURCE),
        ],
        ..Default::default()
    };
    let interp = Interpreter::with_config(config);

    // Set aggressive GC for testing
    let gc_threshold = std::env::var("GC_THRESHOLD")
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .unwrap_or(1);
    interp.set_gc_threshold(gc_threshold);

    interp
}

/// Extract string property from JsValue object
fn get_string_prop(obj: &JsValue, key: &str) -> Option<String> {
    if let JsValue::Object(o) = obj
        && let Some(JsValue::String(s)) = o
            .borrow()
            .get_property(&PropertyKey::String(JsString::from(key)))
    {
        return Some(s.to_string());
    }
    None
}

/// Extract number property from JsValue object
fn get_number_prop(obj: &JsValue, key: &str) -> Option<f64> {
    if let JsValue::Object(o) = obj
        && let Some(JsValue::Number(n)) = o
            .borrow()
            .get_property(&PropertyKey::String(JsString::from(key)))
    {
        return Some(n);
    }
    None
}

/// Run script with globals, handling the import of eval:globals first
#[allow(clippy::expect_used)]
fn run_with_globals(interp: &mut Interpreter, script: &str) -> StepResult {
    // Prepend import of globals module to register global functions
    let full_script = format!(
        r#"import "eval:globals";
{}"#,
        script
    );
    run(interp, &full_script, None).expect("eval should not fail")
}

// ═══════════════════════════════════════════════════════════════════════════════
// Promise .then() Tests
// With blocking request() semantics, to use .then() patterns:
// - Host returns a Promise via fulfill_orders()
// - Script calls .then() on that Promise
// - Host resolves the Promise to trigger the callback
// ═══════════════════════════════════════════════════════════════════════════════
#[test]
fn test_promise_then_callback_closure() {
    let mut interp = create_test_interp();

    // Test that .then() callbacks can access closure variables after Promise resolution
    // Host returns a Promise, script attaches .then() callback, host resolves Promise
    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Create a captured variable in module scope
        let captured = "initial";

        // Call request to get a Promise from host, then attach .then() callback
        const promise = order({ type: "getPromise" });
        await promise.then(() => {
            captured = "modified";
        });

        // Return the captured value (should be "modified" after callback ran)
        captured;
    "#,
    );

    // First suspension: waiting for request response
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for request");
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("getPromise".into())
    );

    // Host creates and returns a Promise
    let promise = api::create_promise(&mut interp);
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise.value().clone())),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    // Second suspension: script is awaiting the Promise (via .then())
    let StepResult::Suspended { .. } = result2 else {
        panic!("Expected Suspended waiting for Promise resolution");
    };

    // Resolve the Promise - this triggers the .then() callback
    api::resolve_promise(
        &mut interp,
        &promise,
        RuntimeValue::unguarded(JsValue::Undefined),
    )
    .unwrap();
    let result3 = run_to_completion(&mut interp).unwrap();

    // After resolution, the callback should have run and modified `captured`
    let StepResult::Complete(value) = result3 else {
        panic!("Expected Complete after Promise resolution");
    };
    assert_eq!(*value, JsValue::String("modified".into()));
}

#[test]
fn test_promise_then_callback_nested_closure() {
    let mut interp = create_test_interp();

    // Test that .then() callbacks can access module-level variables from inside
    // a function call (nested closure)
    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Module-level variable
        let moduleVar = "initial";

        // Function that returns a callback capturing moduleVar
        function createCallback(): () => void {
            return () => {
                moduleVar = "modified";
            };
        }

        // Call createCallback to get a callback, then use it in .then()
        const cb = createCallback();
        const promise = order({ type: "getPromise" });
        await promise.then(cb);

        moduleVar;
    "#,
    );

    // First suspension: waiting for request response
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for request");
    };
    assert_eq!(pending.len(), 1);

    // Host returns a Promise
    let promise = api::create_promise(&mut interp);
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise.value().clone())),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    // Second suspension: awaiting the Promise
    let StepResult::Suspended { .. } = result2 else {
        panic!("Expected Suspended waiting for Promise");
    };

    // Resolve the Promise
    api::resolve_promise(
        &mut interp,
        &promise,
        RuntimeValue::unguarded(JsValue::Undefined),
    )
    .unwrap();
    let result3 = run_to_completion(&mut interp).unwrap();

    let StepResult::Complete(value) = result3 else {
        panic!("Expected Complete after Promise resolution");
    };
    assert_eq!(*value, JsValue::String("modified".into()));
}

#[test]
fn test_cross_module_closure_simple() {
    // Test that callbacks from another module can access that module's variables
    // request returns a Promise immediately, host fulfills with a value
    let config = InterpreterConfig {
        internal_modules: vec![
            create_eval_internal_module(),
            InternalModule::source(
                "eval:timer-module",
                r#"
                import { order } from "tsrun:host";

                // Module-level variable
                let moduleState: string = "initial";

                // Function that gets a Promise from request and attaches .then() callback
                // The callback captures moduleState from this module
                export function runWithCallback(): Promise<void> {
                    const promise = order({ type: "getPromise" });
                    return promise.then(() => {
                        moduleState = "from-callback";
                    });
                }

                export function getState(): string {
                    return moduleState;
                }
            "#,
            ),
        ],
        ..Default::default()
    };
    let mut interp = Interpreter::with_config(config);

    let gc_threshold = std::env::var("GC_THRESHOLD")
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .unwrap_or(1);
    interp.set_gc_threshold(gc_threshold);

    let result = run(
        &mut interp,
        r#"
            import { runWithCallback, getState } from "eval:timer-module";

            // Call the function that uses .then()
            await runWithCallback();

            // Check the state
            getState();
        "#,
        None,
    )
    .expect("eval should work");

    // Suspension: request waiting for host response
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for request");
    };
    assert_eq!(pending.len(), 1);

    // Host returns a Promise (since script calls .then() on the result)
    let promise = api::create_promise(&mut interp);
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise.value().clone())),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    // Second suspension: awaiting the Promise (via .then())
    let StepResult::Suspended { .. } = result2 else {
        panic!("Expected Suspended waiting for Promise");
    };

    // Resolve the Promise to trigger the .then() callback
    api::resolve_promise(
        &mut interp,
        &promise,
        RuntimeValue::unguarded(JsValue::Undefined),
    )
    .unwrap();
    let result3 = run_to_completion(&mut interp).unwrap();

    // The .then() callback should have run and modified `moduleState`
    let StepResult::Complete(value) = result3 else {
        panic!("Expected Complete after Promise resolution");
    };
    assert_eq!(*value, JsValue::String("from-callback".into()));
}

#[test]
fn test_cross_module_nested_closure() {
    // Test that a callback defined in one module can access a variable from an outer
    // function's closure, where that function is defined in another module
    // request returns a Promise immediately, host fulfills with a value
    let config = InterpreterConfig {
        internal_modules: vec![
            create_eval_internal_module(),
            InternalModule::source(
                "eval:helper-module",
                r#"
                import { order } from "tsrun:host";

                // Module-level state
                let moduleState: string = "module-initial";

                // This function gets a Promise from request and attaches .then() callback that
                // accesses BOTH function-local variable AND module variable
                export function wrapWithThen(userCallback: () => void): Promise<void> {
                    const functionLocal = "function-local";

                    const promise = order({ type: "getPromise" });
                    return promise.then(() => {
                        // Access module variable
                        moduleState = "from-then";
                        // Access function-local variable
                        const combined = functionLocal + "+" + moduleState;
                        // Call user callback
                        userCallback();
                    });
                }

                export function getState(): string {
                    return moduleState;
                }
            "#,
            ),
        ],
        ..Default::default()
    };
    let mut interp = Interpreter::with_config(config);

    let gc_threshold = std::env::var("GC_THRESHOLD")
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .unwrap_or(1);
    interp.set_gc_threshold(gc_threshold);

    let result = run(
        &mut interp,
        r#"
            import { wrapWithThen, getState } from "eval:helper-module";

            let userResult = "not-called";

            await wrapWithThen(() => {
                userResult = "user-callback-ran";
            });

            // Return both the module state and user result
            getState() + " / " + userResult;
        "#,
        None,
    )
    .expect("eval should work");

    // Suspension: request waiting for host response
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for request");
    };
    assert_eq!(pending.len(), 1);

    // Host returns a Promise (since script calls .then() on the result)
    let promise = api::create_promise(&mut interp);
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise.value().clone())),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    // Second suspension: awaiting the Promise (via .then())
    let StepResult::Suspended { .. } = result2 else {
        panic!("Expected Suspended waiting for Promise");
    };

    // Resolve the Promise to trigger the .then() callback
    api::resolve_promise(
        &mut interp,
        &promise,
        RuntimeValue::unguarded(JsValue::Undefined),
    )
    .unwrap();
    let result3 = run_to_completion(&mut interp).unwrap();

    // The .then() callback should have run
    let StepResult::Complete(value) = result3 else {
        panic!("Expected Complete after Promise resolution");
    };
    assert_eq!(
        *value,
        JsValue::String("from-then / user-callback-ran".into())
    );
}

#[test]
fn test_debug_closure_gc() {
    // Test GC with closures accessing local and module variables
    // request returns a Promise immediately, host fulfills with a value
    let config = InterpreterConfig {
        internal_modules: vec![create_eval_internal_module()],
        ..Default::default()
    };
    let mut interp = Interpreter::with_config(config);
    interp.set_gc_threshold(1);

    // Test that callback closure survives GC with local variables
    let result = run(
        &mut interp,
        r#"
            import { order } from "tsrun:host";

            let state: string = "initial";

            // Wrapper function WITH a local variable
            function wrapper(): Promise<void> {
                const local = "local";  // This triggers call env creation
                const promise = order({ type: "getPromise" });
                return promise.then(() => {
                    state = "modified-" + local;
                });
            }

            await wrapper();
            state;
        "#,
        None,
    )
    .expect("eval should work");

    // Suspension: request waiting for host response
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for request");
    };

    // Host returns a Promise (since script calls .then() on the result)
    let promise = api::create_promise(&mut interp);
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise.value().clone())),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    // Second suspension: awaiting the Promise (via .then())
    let StepResult::Suspended { .. } = result2 else {
        panic!("Expected Suspended waiting for Promise");
    };

    // Resolve the Promise to trigger the .then() callback
    api::resolve_promise(
        &mut interp,
        &promise,
        RuntimeValue::unguarded(JsValue::Undefined),
    )
    .unwrap();
    let result3 = run_to_completion(&mut interp).unwrap();

    // The .then() callback should have run with the closure
    let StepResult::Complete(value) = result3 else {
        panic!("Expected Complete after Promise resolution");
    };
    assert_eq!(*value, JsValue::String("modified-local".into()));
}

// ═══════════════════════════════════════════════════════════════════════════════
// sleep() Tests (blocking delay using orders)
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_sleep_basic() {
    let mut interp = create_test_interp();

    // Use async sleep() which returns a Promise
    let result = run_with_globals(
        &mut interp,
        r#"
        let result = "before";
        await sleep(100);
        result = "after";
        result;
    "#,
    );

    // Should suspend for sleep()
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for sleep()");
    };
    assert_eq!(pending.len(), 1);

    // Verify the order payload
    let payload = pending[0].payload.value();
    assert_eq!(get_string_prop(payload, "type"), Some("sleep".into()));

    // Fulfill the order (host would wait the delay then respond)
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(JsValue::Undefined)),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    let StepResult::Complete(value) = result2 else {
        panic!("Expected Complete after sleep");
    };
    assert_eq!(*value, JsValue::String("after".into()));
}

#[test]
fn test_sleep_sequential() {
    let mut interp = create_test_interp();

    // Multiple sequential await sleep() calls
    let result = run_with_globals(
        &mut interp,
        r#"
        let count = 0;
        await sleep(10);
        count += 1;
        await sleep(20);
        count += 1;
        await sleep(30);
        count += 1;
        count;
    "#,
    );

    // First sleep
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first sleep");
    };
    assert_eq!(pending.len(), 1);

    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(JsValue::Undefined)),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second sleep
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second sleep");
    };
    assert_eq!(pending.len(), 1);

    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(JsValue::Undefined)),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Third sleep
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for third sleep");
    };
    assert_eq!(pending.len(), 1);

    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(JsValue::Undefined)),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Complete
    let StepResult::Complete(value) = result else {
        panic!("Expected Complete after all sleeps");
    };
    assert_eq!(*value, JsValue::Number(3.0));
}

// ═══════════════════════════════════════════════════════════════════════════════
// fetch Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_fetch_get_basic() {
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        const response = await fetch("https://api.example.com/users/1");
        response.name;
    "#,
    );

    match result {
        StepResult::Suspended { pending, .. } => {
            assert_eq!(pending.len(), 1);

            // Verify the order payload
            let payload = pending[0].payload.value();
            assert_eq!(get_string_prop(payload, "type"), Some("fetch".into()));
            assert_eq!(
                get_string_prop(payload, "url"),
                Some("https://api.example.com/users/1".into())
            );
            assert_eq!(get_string_prop(payload, "method"), Some("GET".into()));

            // Return mock response using create_response_object
            let mock_response = api::create_response_object(
                &mut interp,
                &json!({
                    "id": 1,
                    "name": "John",
                    "email": "john@example.com"
                }),
            )
            .unwrap();

            let response = OrderResponse {
                id: pending[0].id,
                result: Ok(mock_response),
            };

            interp.fulfill_orders(vec![response]);
            let result2 = run_to_completion(&mut interp).unwrap();

            match result2 {
                StepResult::Complete(value) => {
                    assert_eq!(*value, JsValue::String("John".into()));
                }
                _ => panic!("Expected Complete after fulfillment"),
            }
        }
        _ => panic!("Expected Suspended"),
    }
}

#[test]
fn test_fetch_post_with_body() {
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        const response = await fetch("https://api.example.com/users", {
            method: "POST",
            body: JSON.stringify({ name: "Jane" }),
            headers: { "Content-Type": "application/json" }
        });
        response.id;
    "#,
    );

    match result {
        StepResult::Suspended { pending, .. } => {
            assert_eq!(pending.len(), 1);

            let payload = pending[0].payload.value();
            assert_eq!(get_string_prop(payload, "type"), Some("fetch".into()));
            assert_eq!(
                get_string_prop(payload, "url"),
                Some("https://api.example.com/users".into())
            );
            assert_eq!(get_string_prop(payload, "method"), Some("POST".into()));
            assert_eq!(
                get_string_prop(payload, "body"),
                Some(r#"{"name":"Jane"}"#.into())
            );

            // Return mock created response
            let mock_response =
                api::create_response_object(&mut interp, &json!({ "id": 42, "name": "Jane" }))
                    .unwrap();

            let response = OrderResponse {
                id: pending[0].id,
                result: Ok(mock_response),
            };

            interp.fulfill_orders(vec![response]);
            let result2 = run_to_completion(&mut interp).unwrap();

            match result2 {
                StepResult::Complete(value) => {
                    assert_eq!(*value, JsValue::Number(42.0));
                }
                _ => panic!("Expected Complete after fulfillment"),
            }
        }
        _ => panic!("Expected Suspended"),
    }
}

#[test]
fn test_fetch_parallel() {
    let mut interp = create_test_interp();

    // Simplified test - two sequential awaits instead of Promise.all
    let result = run_with_globals(
        &mut interp,
        r#"
        const user = await fetch("/users/1");
        const posts = await fetch("/posts?userId=1");
        user.name + " has " + posts.length + " posts";
    "#,
    );

    // First suspension: fetch("/users/1")
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first fetch");
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "url"),
        Some("/users/1".into())
    );

    let user_response =
        api::create_response_object(&mut interp, &json!({ "name": "John" })).unwrap();
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(user_response),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    // Second suspension: fetch("/posts?userId=1")
    let StepResult::Suspended { pending, .. } = result2 else {
        panic!("Expected Suspended for second fetch, got {:?}", result2);
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "url"),
        Some("/posts?userId=1".into())
    );

    let posts_response =
        api::create_response_object(&mut interp, &json!([{ "id": 1 }, { "id": 2 }, { "id": 3 }]))
            .unwrap();
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(posts_response),
    }]);
    let result3 = run_to_completion(&mut interp).unwrap();

    // Final result
    let StepResult::Complete(value) = result3 else {
        panic!("Expected Complete after fulfillment, got {:?}", result3);
    };
    assert_eq!(*value, JsValue::String("John has 3 posts".into()));
}

// ═══════════════════════════════════════════════════════════════════════════════
// File System Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_read_file_basic() {
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        const content = await readFile("/config.txt");
        content;
    "#,
    );

    match result {
        StepResult::Suspended { pending, .. } => {
            assert_eq!(pending.len(), 1);

            let payload = pending[0].payload.value();
            assert_eq!(get_string_prop(payload, "type"), Some("readFile".into()));
            assert_eq!(get_string_prop(payload, "path"), Some("/config.txt".into()));

            // Return mock file content
            let response = OrderResponse {
                id: pending[0].id,
                result: Ok(RuntimeValue::unguarded(JsValue::String(
                    "Hello, World!".into(),
                ))),
            };

            interp.fulfill_orders(vec![response]);
            let result2 = run_to_completion(&mut interp).unwrap();

            match result2 {
                StepResult::Complete(value) => {
                    assert_eq!(*value, JsValue::String("Hello, World!".into()));
                }
                _ => panic!("Expected Complete after fulfillment"),
            }
        }
        _ => panic!("Expected Suspended"),
    }
}

#[test]
fn test_read_file_json_parse() {
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        const raw = await readFile("/config.json");
        const config = JSON.parse(raw);
        config.database.host;
    "#,
    );

    match result {
        StepResult::Suspended { pending, .. } => {
            assert_eq!(pending.len(), 1);

            // Return mock JSON content
            let json_content = r#"{"database": {"host": "localhost", "port": 5432}}"#;
            let response = OrderResponse {
                id: pending[0].id,
                result: Ok(RuntimeValue::unguarded(JsValue::String(
                    json_content.into(),
                ))),
            };

            interp.fulfill_orders(vec![response]);
            let result2 = run_to_completion(&mut interp).unwrap();

            match result2 {
                StepResult::Complete(value) => {
                    assert_eq!(*value, JsValue::String("localhost".into()));
                }
                _ => panic!("Expected Complete after fulfillment"),
            }
        }
        _ => panic!("Expected Suspended"),
    }
}

#[test]
fn test_write_file_basic() {
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        await writeFile("/output.txt", "Hello from TypeScript!");
        "written";
    "#,
    );

    match result {
        StepResult::Suspended { pending, .. } => {
            assert_eq!(pending.len(), 1);

            let payload = pending[0].payload.value();
            assert_eq!(get_string_prop(payload, "type"), Some("writeFile".into()));
            assert_eq!(get_string_prop(payload, "path"), Some("/output.txt".into()));
            assert_eq!(
                get_string_prop(payload, "content"),
                Some("Hello from TypeScript!".into())
            );

            // Acknowledge write success
            let response = OrderResponse {
                id: pending[0].id,
                result: Ok(RuntimeValue::unguarded(JsValue::Undefined)),
            };

            interp.fulfill_orders(vec![response]);
            let result2 = run_to_completion(&mut interp).unwrap();

            match result2 {
                StepResult::Complete(value) => {
                    assert_eq!(*value, JsValue::String("written".into()));
                }
                _ => panic!("Expected Complete after fulfillment"),
            }
        }
        _ => panic!("Expected Suspended"),
    }
}

#[test]
fn test_read_write_roundtrip() {
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        const data = "test data 12345";
        await writeFile("/temp.txt", data);
        const read = await readFile("/temp.txt");
        read === data;
    "#,
    );

    // First: writeFile
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for writeFile");
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("writeFile".into())
    );

    // Capture the written content
    let file_content = get_string_prop(pending[0].payload.value(), "content").unwrap_or_default();
    assert_eq!(file_content, "test data 12345");

    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(JsValue::Undefined)),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second: readFile
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for readFile");
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("readFile".into())
    );

    // Return the "stored" content
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(JsValue::String(
            file_content.into(),
        ))),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Complete
    let StepResult::Complete(value) = result else {
        panic!("Expected Complete after roundtrip");
    };
    assert_eq!(*value, JsValue::Boolean(true));
}

// ═══════════════════════════════════════════════════════════════════════════════
// Combined Workflow Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_config_generation_workflow() {
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        // 1. Read local config
        const configRaw = await readFile("/app.json");
        const config = JSON.parse(configRaw);

        // 2. Fetch remote data
        const apiData = await fetch(config.apiUrl + "/settings");

        // 3. Generate manifest
        const manifest = {
            name: config.name,
            version: config.version,
            settings: apiData,
        };

        // 4. Write output
        await writeFile("/manifest.json", JSON.stringify(manifest));

        manifest.name + " v" + manifest.version;
    "#,
    );

    // Step 1: readFile /app.json
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for readFile");
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("readFile".into())
    );

    let config_json =
        r#"{"name": "MyApp", "version": "1.0.0", "apiUrl": "https://api.example.com"}"#;
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(JsValue::String(config_json.into()))),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Step 2: fetch api settings
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for fetch");
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("fetch".into())
    );
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "url"),
        Some("https://api.example.com/settings".into())
    );

    let api_response =
        api::create_response_object(&mut interp, &json!({ "theme": "dark", "language": "en" }))
            .unwrap();
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(api_response),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Step 3: writeFile /manifest.json
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for writeFile");
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("writeFile".into())
    );
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "path"),
        Some("/manifest.json".into())
    );

    // Verify the manifest content
    let manifest_content = get_string_prop(pending[0].payload.value(), "content").unwrap();
    assert!(manifest_content.contains("MyApp"));
    assert!(manifest_content.contains("1.0.0"));
    assert!(manifest_content.contains("dark"));

    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(JsValue::Undefined)),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Complete
    let StepResult::Complete(value) = result else {
        panic!("Expected Complete after workflow");
    };
    assert_eq!(*value, JsValue::String("MyApp v1.0.0".into()));
}

// ═══════════════════════════════════════════════════════════════════════════════
// Host Promise API Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_host_create_and_resolve_promise() {
    // Test that host can create a Promise and resolve it later
    let mut interp = create_test_interp();

    // Create an unresolved promise from the host
    let host_promise = api::create_promise(&mut interp);

    // The script must await the returned Promise separately
    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // request returns a PendingOrder, await it to get the host's Promise
        const promise = await order({ type: "getHostPromise" });
        // Then await the Promise to get the actual value
        const result = await promise;
        "Got: " + result;
    "#,
    );

    // First suspension: waiting for order
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended waiting for order");
    };
    assert_eq!(pending.len(), 1);
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("getHostPromise".into())
    );

    // Fulfill with the unresolved promise - use the value directly
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(host_promise.value().clone())),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    // Still suspended - waiting for the Promise to be resolved
    let StepResult::Suspended { .. } = result2 else {
        panic!("Expected Suspended waiting for Promise to be resolved");
    };

    // Now resolve the promise with a value
    let value = RuntimeValue::unguarded(JsValue::String("Hello from host!".into()));
    api::resolve_promise(&mut interp, &host_promise, value).unwrap();
    let result3 = run_to_completion(&mut interp).unwrap();

    // Should complete now
    let StepResult::Complete(final_value) = result3 else {
        panic!("Expected Complete after resolving Promise");
    };
    assert_eq!(
        *final_value,
        JsValue::String("Got: Hello from host!".into())
    );
}

#[test]
fn test_host_create_and_reject_promise() {
    // Test that host can create a Promise and reject it later
    let mut interp = create_test_interp();

    let host_promise = api::create_promise(&mut interp);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        try {
            // Get the Promise from host and await it
            const promise = await order({ type: "getHostPromise" });
            const result = await promise;
            "Success: " + result;
        } catch (e) {
            "Error: " + e;
        }
    "#,
    );

    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended");
    };

    // Fulfill with the unresolved promise
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(host_promise.value().clone())),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    let StepResult::Suspended { .. } = result2 else {
        panic!("Expected Suspended waiting for Promise");
    };

    // Reject the promise
    let reason = RuntimeValue::unguarded(JsValue::String("Something went wrong".into()));
    api::reject_promise(&mut interp, &host_promise, reason).unwrap();
    let result3 = run_to_completion(&mut interp).unwrap();

    let StepResult::Complete(final_value) = result3 else {
        panic!("Expected Complete after rejecting Promise");
    };
    assert_eq!(
        *final_value,
        JsValue::String("Error: Something went wrong".into())
    );
}

#[test]
fn test_host_promise_immediate_resolve() {
    // Test resolving a Promise immediately before returning it
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Get the Promise from host and await it
        const promise = await order({ type: "quickResolve" });
        const result = await promise;
        "Result: " + result;
    "#,
    );

    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended");
    };

    // Create promise and resolve it first
    let promise = api::create_promise(&mut interp);
    let value = RuntimeValue::unguarded(JsValue::Number(42.0));

    // Resolve the promise BEFORE returning it to the script
    // This is valid - the Promise is already fulfilled when returned
    api::resolve_promise(&mut interp, &promise, value).unwrap();

    // Now fulfill the order with the already-resolved promise
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise.value().clone())),
    }]);
    let result2 = run_to_completion(&mut interp).unwrap();

    // Since the Promise was already resolved, await should complete immediately
    let StepResult::Complete(final_value) = result2 else {
        panic!("Expected Complete");
    };
    assert_eq!(*final_value, JsValue::String("Result: 42".into()));
}

// ═══════════════════════════════════════════════════════════════════════════════
// Concurrency Tests (via host-returned Promises)
// With blocking request(), concurrency is achieved by:
// 1. Script calls request() which SUSPENDS immediately
// 2. Host returns an unresolved Promise (or any other value)
// 3. Script continues to next request(), which also suspends
// 4. Eventually script reaches await Promise.all with multiple host Promises
// 5. Host resolves Promises in any order (can do work in parallel)
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_concurrent_fetch_with_promise_all() {
    // Simulate concurrent fetching via host-returned Promises
    // Blocking request semantics:
    // 1. First request suspends immediately, host sees "/users" order
    // 2. Host fulfills with unresolved Promise
    // 3. Second request suspends, host sees "/posts" order
    // 4. Host fulfills with unresolved Promise
    // 5. await Promise.all waits for both Promises
    // 6. Host resolves Promises (can do work in parallel)
    let mut interp = create_test_interp();

    // Create two Promises that will be returned by orders
    let users_promise = api::create_promise(&mut interp);
    let posts_promise = api::create_promise(&mut interp);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Each request suspends immediately - host sees one at a time
        const usersPromise = order({ type: "fetch", url: "/users" });
        const postsPromise = order({ type: "fetch", url: "/posts" });

        // await Promise.all waits for both host Promises
        const [users, posts] = await Promise.all([usersPromise, postsPromise]);

        `${users.count} users, ${posts.count} posts`;
    "#,
    );

    // First suspension: request for "/users"
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended at first request");
    };
    assert_eq!(pending.len(), 1, "First order pending");
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "url"),
        Some("/users".into())
    );
    let users_order_id = pending[0].id;

    // Fulfill first order with unresolved Promise
    // Note: users_promise RuntimeValue stays alive, keeping the Promise guarded
    interp.fulfill_orders(vec![OrderResponse {
        id: users_order_id,
        result: Ok(RuntimeValue::unguarded(users_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second suspension: request for "/posts"
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended at second request, got {:?}", result);
    };
    assert_eq!(pending.len(), 1, "Second order pending");
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "url"),
        Some("/posts".into())
    );
    let posts_order_id = pending[0].id;

    // Fulfill second order with unresolved Promise
    // Note: posts_promise RuntimeValue stays alive, keeping the Promise guarded
    interp.fulfill_orders(vec![OrderResponse {
        id: posts_order_id,
        result: Ok(RuntimeValue::unguarded(posts_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.all with two unresolved Promises
    // No more orders pending, just waiting for Promises
    match &result {
        StepResult::Suspended { pending, .. } if pending.is_empty() => {
            // Suspended with no orders - just awaiting Promises
        }
        StepResult::Done => {
            // Done - async work pending, no more sync work
        }
        other => {
            panic!(
                "Expected Done or Suspended while awaiting Promises, got {:?}",
                other
            );
        }
    }

    // Resolve both Promises - host can do this in parallel
    let users_data = api::create_response_object(&mut interp, &json!({ "count": 5 })).unwrap();
    let posts_data = api::create_response_object(&mut interp, &json!({ "count": 10 })).unwrap();
    api::resolve_promise(&mut interp, &users_promise, users_data).unwrap();
    api::resolve_promise(&mut interp, &posts_promise, posts_data).unwrap();

    // After resolving Promises, step to process the results
    let result = run_to_completion(&mut interp).unwrap();

    // Complete - results in original order
    let StepResult::Complete(value) = result else {
        panic!("Expected Complete after both resolved, got {:?}", result);
    };
    assert_eq!(*value, JsValue::String("5 users, 10 posts".into()));
}

#[test]
fn test_promise_race_first_wins() {
    // Promise.race: first to resolve determines the result
    // With blocking request:
    // 1. First request suspends, host returns Promise1
    // 2. Second request suspends, host returns Promise2
    // 3. Promise.race waits for first Promise to resolve
    // 4. Host resolves first Promise - it wins
    let mut interp = create_test_interp();

    // Create two Promises that will be returned by orders
    let fast_promise = api::create_promise(&mut interp);
    let slow_promise = api::create_promise(&mut interp);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Each request suspends, host returns a Promise
        const fast = order({ type: "fetch", server: "fast" });
        const slow = order({ type: "fetch", server: "slow" });

        // Race: first to resolve wins
        const winner = await Promise.race([fast, slow]);
        winner.server;
    "#,
    );

    // First order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    let first_order_id = pending[0].id;
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "server"),
        Some("fast".into())
    );

    // Fulfill first order with Promise (not resolved yet)
    interp.fulfill_orders(vec![OrderResponse {
        id: first_order_id,
        result: Ok(RuntimeValue::unguarded(fast_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    let second_order_id = pending[0].id;
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "server"),
        Some("slow".into())
    );

    // Fulfill second order with Promise (not resolved yet)
    interp.fulfill_orders(vec![OrderResponse {
        id: second_order_id,
        result: Ok(RuntimeValue::unguarded(slow_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.race with two unresolved Promises
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.race");
    };
    assert!(
        pending.is_empty(),
        "No orders pending, just awaiting Promises"
    );

    // Resolve first Promise - it wins the race
    let fast_data = api::create_response_object(&mut interp, &json!({ "server": "fast" })).unwrap();
    api::resolve_promise(&mut interp, &fast_promise, fast_data).unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    // Race completes - first resolved wins
    let StepResult::Complete(value) = result else {
        panic!("Expected Complete after fulfillment, got {:?}", result);
    };
    assert_eq!(*value, JsValue::String("fast".into()));
}

#[test]
fn test_promise_race_second_wins() {
    // Verify race works when second Promise is resolved first
    // With blocking request:
    // 1. First request suspends, host returns Promise1
    // 2. Second request suspends, host returns Promise2
    // 3. Promise.race waits for first Promise to resolve
    // 4. Host resolves second Promise first - it wins
    let mut interp = create_test_interp();

    // Create two Promises that will be returned by orders
    let a_promise = api::create_promise(&mut interp);
    let b_promise = api::create_promise(&mut interp);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Each request suspends, host returns a Promise
        const a = order({ type: "fetch", id: "a" });
        const b = order({ type: "fetch", id: "b" });

        const winner = await Promise.race([a, b]);
        winner.winner;
    "#,
    );

    // First order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    let first_order_id = pending[0].id;
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "id"),
        Some("a".into())
    );

    // Fulfill first order with Promise (not resolved yet)
    interp.fulfill_orders(vec![OrderResponse {
        id: first_order_id,
        result: Ok(RuntimeValue::unguarded(a_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    let second_order_id = pending[0].id;
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "id"),
        Some("b".into())
    );

    // Fulfill second order with Promise (not resolved yet)
    interp.fulfill_orders(vec![OrderResponse {
        id: second_order_id,
        result: Ok(RuntimeValue::unguarded(b_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.race with two unresolved Promises
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.race");
    };
    assert!(
        pending.is_empty(),
        "No orders pending, just awaiting Promises"
    );

    // Resolve B first - it wins even though it was second in array
    let b_data = api::create_response_object(&mut interp, &json!({ "winner": "B" })).unwrap();
    api::resolve_promise(&mut interp, &b_promise, b_data).unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    // Race completes - B wins because it was resolved first
    let StepResult::Complete(value) = result else {
        panic!("Expected Complete, got {:?}", result);
    };
    assert_eq!(*value, JsValue::String("B".into()));
}

#[test]
fn test_concurrent_with_partial_failure() {
    // One Promise resolves, one rejects - test error handling with Promise.all
    // With blocking request:
    // 1. First request suspends, host returns Promise1
    // 2. Second request suspends, host returns Promise2
    // 3. Promise.all waits for both Promises
    // 4. Host resolves first, rejects second - Promise.all catches the error
    let mut interp = create_test_interp();

    // Create two Promises that will be returned by orders
    let ok_promise = api::create_promise(&mut interp);
    let fail_promise = api::create_promise(&mut interp);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Each request suspends, host returns a Promise
        const ok = order({ type: "fetch", url: "/ok" });
        const fail = order({ type: "fetch", url: "/fail" });

        try {
            const results = await Promise.all([ok, fail]);
            "Success: " + JSON.stringify(results);
        } catch (e) {
            "Error: " + e;
        }
    "#,
    );

    // First order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    let first_order_id = pending[0].id;
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "url"),
        Some("/ok".into())
    );

    // Fulfill first order with Promise (not resolved yet)
    interp.fulfill_orders(vec![OrderResponse {
        id: first_order_id,
        result: Ok(RuntimeValue::unguarded(ok_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    let second_order_id = pending[0].id;
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "url"),
        Some("/fail".into())
    );

    // Fulfill second order with Promise (not resolved yet)
    interp.fulfill_orders(vec![OrderResponse {
        id: second_order_id,
        result: Ok(RuntimeValue::unguarded(fail_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.all with two unresolved Promises
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.all");
    };
    assert!(
        pending.is_empty(),
        "No orders pending, just awaiting Promises"
    );

    // Resolve first Promise with success
    let ok_data = RuntimeValue::unguarded(JsValue::String("OK".into()));
    api::resolve_promise(&mut interp, &ok_promise, ok_data).unwrap();

    // Reject second Promise with error
    let error_value = RuntimeValue::unguarded(JsValue::String("Network error".into()));
    api::reject_promise(&mut interp, &fail_promise, error_value).unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    // Promise.all rejects if any Promise rejects
    let StepResult::Complete(value) = result else {
        panic!("Expected Complete with error, got {:?}", result);
    };
    assert_eq!(*value, JsValue::String("Error: Network error".into()));
}

#[test]
fn test_concurrent_three_way_race() {
    // Race with three Promises, middle one wins
    // With blocking request, each order suspends one at a time
    let mut interp = create_test_interp();

    // Create three host Promises upfront
    let promise1 = api::create_promise(&mut interp);
    let promise2 = api::create_promise(&mut interp);
    let promise3 = api::create_promise(&mut interp);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Get three Promises from host (each request suspends)
        const p1 = order({ id: 1 });
        const p2 = order({ id: 2 });
        const p3 = order({ id: 3 });

        // Race: first to resolve wins
        const winner = await Promise.race([p1, p2, p3]);
        "Winner: " + winner;
    "#,
    );

    // First order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(1.0));

    // Fulfill first order with Promise1
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise1.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(2.0));

    // Fulfill second order with Promise2
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise2.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Third order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for third order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(3.0));

    // Fulfill third order with Promise3
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise3.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.race with three unresolved Promises
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.race");
    };
    assert!(
        pending.is_empty(),
        "No orders pending, just awaiting Promises"
    );

    // Resolve Promise2 first - it should win the race
    api::resolve_promise(
        &mut interp,
        &promise2,
        RuntimeValue::unguarded(JsValue::Number(2.0)),
    )
    .unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    let StepResult::Complete(value) = result else {
        panic!("Expected Complete after resolving winner, got {:?}", result);
    };
    assert_eq!(*value, JsValue::String("Winner: 2".into()));
}

#[test]
fn test_concurrent_chained_operations() {
    // Start concurrent fetches, then chain more operations on results
    // With blocking request:
    // 1. First request suspends, host returns Promise1
    // 2. Second request suspends, host returns Promise2
    // 3. .then() chains transformations on each Promise
    // 4. Promise.all waits for both transformed Promises
    // 5. Host resolves both Promises
    let mut interp = create_test_interp();

    // Create two Promises that will be returned by orders
    let user_promise = api::create_promise(&mut interp);
    let profile_promise = api::create_promise(&mut interp);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Each request suspends, host returns a Promise
        const userPromise = order({ type: "getUser" });
        const profilePromise = order({ type: "getProfile" });

        // Chain transformations on each
        const user = userPromise.then(u => ({ ...u, type: "user" }));
        const profile = profilePromise.then(p => ({ ...p, type: "profile" }));

        // Wait for both transformed results
        const [u, p] = await Promise.all([user, profile]);
        `${u.name} (${u.type}), ${p.bio} (${p.type})`;
    "#,
    );

    // First order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    let first_order_id = pending[0].id;
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("getUser".into())
    );

    // Fulfill first order with Promise (not resolved yet)
    interp.fulfill_orders(vec![OrderResponse {
        id: first_order_id,
        result: Ok(RuntimeValue::unguarded(user_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    let second_order_id = pending[0].id;
    assert_eq!(
        get_string_prop(pending[0].payload.value(), "type"),
        Some("getProfile".into())
    );

    // Fulfill second order with Promise (not resolved yet)
    interp.fulfill_orders(vec![OrderResponse {
        id: second_order_id,
        result: Ok(RuntimeValue::unguarded(profile_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.all with two unresolved Promises (with .then() chains)
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.all");
    };
    assert!(
        pending.is_empty(),
        "No orders pending, just awaiting Promises"
    );

    // Resolve both Promises - host can do this in parallel
    let user_data = api::create_response_object(&mut interp, &json!({ "name": "Alice" })).unwrap();
    let profile_data =
        api::create_response_object(&mut interp, &json!({ "bio": "Developer" })).unwrap();
    api::resolve_promise(&mut interp, &user_promise, user_data).unwrap();
    api::resolve_promise(&mut interp, &profile_promise, profile_data).unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    // Complete - .then() chains should have run
    let StepResult::Complete(value) = result else {
        panic!("Expected Complete, got {:?}", result);
    };
    assert_eq!(
        *value,
        JsValue::String("Alice (user), Developer (profile)".into())
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Order Cancellation Tests
// When host Promises are abandoned (e.g., lose in Promise.race) or rejected,
// their associated order IDs are reported back to the host via cancelled list.
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_promise_race_cancels_losing_order() {
    // When Promise.race settles, losing Promises' order IDs should be cancelled
    // With blocking request, each order suspends one at a time
    let mut interp = create_test_interp();

    // Create two host Promises with order IDs for cancellation tracking
    let order1_id = OrderId(1);
    let order2_id = OrderId(2);
    let promise1 = api::create_order_promise(&mut interp, order1_id);
    let promise2 = api::create_order_promise(&mut interp, order2_id);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        const p1 = order({ id: 1 });
        const p2 = order({ id: 2 });

        const winner = await Promise.race([p1, p2]);
        winner;
    "#,
    );

    // First order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(1.0));

    // Fulfill first order with Promise1 (with order_id for cancellation tracking)
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise1.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(2.0));

    // Fulfill second order with Promise2 (with order_id for cancellation tracking)
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise2.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.race with two unresolved Promises
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.race");
    };
    assert!(
        pending.is_empty(),
        "No orders pending, just awaiting Promises"
    );

    // Resolve Promise1 first - it wins the race, Promise2's order should be cancelled
    api::resolve_promise(
        &mut interp,
        &promise1,
        RuntimeValue::unguarded(JsValue::String("first".into())),
    )
    .unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    // Check that the result includes cancelled order
    match result {
        StepResult::Complete(value) => {
            assert_eq!(*value, JsValue::String("first".into()));
        }
        StepResult::Suspended { cancelled, .. } => {
            // The loser's order_id (order2_id) should be in cancelled
            assert!(
                cancelled.contains(&order2_id),
                "Expected order2_id ({:?}) in cancelled list: {:?}",
                order2_id,
                cancelled
            );
            // Continue to get final result
            let result = run_to_completion(&mut interp).unwrap();
            if let StepResult::Complete(value) = result {
                assert_eq!(*value, JsValue::String("first".into()));
            }
        }
        _ => panic!("Unexpected result"),
    }
}

#[test]
fn test_promise_race_second_wins_cancels_first() {
    // Verify cancellation works when second Promise wins
    // With blocking request, each order suspends one at a time
    let mut interp = create_test_interp();

    // Create two host Promises with order IDs for cancellation tracking
    let order1_id = OrderId(1);
    let order2_id = OrderId(2);
    let promise1 = api::create_order_promise(&mut interp, order1_id);
    let promise2 = api::create_order_promise(&mut interp, order2_id);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        const p1 = order({ id: 1 });
        const p2 = order({ id: 2 });

        const winner = await Promise.race([p1, p2]);
        winner;
    "#,
    );

    // First order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(1.0));

    // Fulfill first order with Promise1
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise1.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(2.0));

    // Fulfill second order with Promise2
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise2.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.race with two unresolved Promises
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.race");
    };
    assert!(
        pending.is_empty(),
        "No orders pending, just awaiting Promises"
    );

    // Resolve Promise2 first - it wins the race, Promise1's order should be cancelled
    api::resolve_promise(
        &mut interp,
        &promise2,
        RuntimeValue::unguarded(JsValue::String("second".into())),
    )
    .unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    match result {
        StepResult::Complete(value) => {
            assert_eq!(*value, JsValue::String("second".into()));
        }
        StepResult::Suspended { cancelled, .. } => {
            // The loser's order_id (order1_id) should be in cancelled
            assert!(
                cancelled.contains(&order1_id),
                "Expected order1_id ({:?}) in cancelled list: {:?}",
                order1_id,
                cancelled
            );
        }
        _ => panic!("Unexpected result"),
    }
}

#[test]
fn test_promise_rejection_signals_cancelled_order() {
    // When a host Promise is rejected, its order should be signalled as cancelled
    let mut interp = create_test_interp();

    let order_id = OrderId(999);
    let promise = api::create_order_promise(&mut interp, order_id);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        try {
            const p = order({ type: "will_fail" });
            await p;
            "resolved";
        } catch (e) {
            "caught: " + e;
        }
    "#,
    );

    // Get order and return Promise
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended");
    };
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    let StepResult::Suspended { .. } = result else {
        panic!("Expected Suspended");
    };

    // Reject the Promise - its order should be cancelled
    api::reject_promise(
        &mut interp,
        &promise,
        RuntimeValue::unguarded(JsValue::String("error".into())),
    )
    .unwrap();
    let result = run_to_completion(&mut interp).unwrap();

    match result {
        StepResult::Complete(value) => {
            assert_eq!(*value, JsValue::String("caught: error".into()));
        }
        StepResult::Suspended { cancelled, .. } => {
            // Rejected Promise's order should be in cancelled
            assert!(
                cancelled.contains(&order_id),
                "Expected order_id ({:?}) in cancelled list: {:?}",
                order_id,
                cancelled
            );
            // Continue to get final result
            let result = run_to_completion(&mut interp).unwrap();
            if let StepResult::Complete(value) = result {
                assert_eq!(*value, JsValue::String("caught: error".into()));
            }
        }
        _ => panic!("Unexpected result"),
    }
}

#[test]
fn test_three_way_race_cancels_two_losers() {
    // Three-way race: winner gets result, two losers' orders cancelled
    // With blocking request, each order suspends one at a time
    let mut interp = create_test_interp();

    // Create three host Promises with order IDs for cancellation tracking
    let order1_id = OrderId(1);
    let order2_id = OrderId(2);
    let order3_id = OrderId(3);
    let promise1 = api::create_order_promise(&mut interp, order1_id);
    let promise2 = api::create_order_promise(&mut interp, order2_id);
    let promise3 = api::create_order_promise(&mut interp, order3_id);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        const p1 = order({ id: 1 });
        const p2 = order({ id: 2 });
        const p3 = order({ id: 3 });

        const winner = await Promise.race([p1, p2, p3]);
        "Winner: " + winner;
    "#,
    );

    // First order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for first order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(1.0));

    // Fulfill first order with Promise1
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise1.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for second order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(2.0));

    // Fulfill second order with Promise2
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise2.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Third order suspends
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for third order");
    };
    assert_eq!(pending.len(), 1, "One order at a time");
    assert_eq!(get_number_prop(pending[0].payload.value(), "id"), Some(3.0));

    // Fulfill third order with Promise3
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(promise3.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.race with three unresolved Promises
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.race");
    };
    assert!(
        pending.is_empty(),
        "No orders pending, just awaiting Promises"
    );

    // Resolve Promise2 first (order2 wins), Promise1 and Promise3's orders should be cancelled
    api::resolve_promise(
        &mut interp,
        &promise2,
        RuntimeValue::unguarded(JsValue::Number(2.0)),
    )
    .unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    // Check that both losers' orders are cancelled
    let cancelled = match &result {
        StepResult::Suspended { cancelled, .. } => cancelled.clone(),
        StepResult::Complete(_) => {
            // May have completed immediately, check via continue_eval
            Vec::new()
        }
        _ => panic!("Unexpected result"),
    };

    // order1_id and order3_id should be cancelled (order2_id won)
    assert!(
        cancelled.contains(&order1_id) || cancelled.is_empty(),
        "Expected order1_id in cancelled: {:?}",
        cancelled
    );
    assert!(
        cancelled.contains(&order3_id) || cancelled.is_empty(),
        "Expected order3_id in cancelled: {:?}",
        cancelled
    );
    // Winner's order should NOT be cancelled
    assert!(
        !cancelled.contains(&order2_id),
        "Winner's order should not be cancelled: {:?}",
        cancelled
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Documentation Example Pattern Tests
// These tests demonstrate the patterns shown in README.md and CLAUDE.md:
// - Multiple order types with type-based dispatch
// - Returning unresolved Promises for concurrent execution
// - Error handling for unknown order types
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_concurrent_mixed_order_types() {
    // Demonstrates the pattern from documentation examples:
    // 1. Multiple order types (fetch, timeout)
    // 2. Host checks payload.type to dispatch
    // 3. Returns unresolved Promises for concurrent execution
    let mut interp = create_test_interp();

    // Create Promises upfront for concurrent resolution
    let fetch_promise = api::create_promise(&mut interp);
    let timeout_promise = api::create_promise(&mut interp);

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        // Issue two orders with different types
        const fetchPromise = order({ type: "fetch", url: "/api/users" });
        const timeoutPromise = order({ type: "timeout", ms: 100 });

        // Wait for both concurrently
        const [data, _] = await Promise.all([fetchPromise, timeoutPromise]);
        data.name;
    "#,
    );

    // First order: fetch
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for fetch order");
    };
    assert_eq!(pending.len(), 1);

    // Host checks type to dispatch
    let payload = pending[0].payload.value();
    let order_type = get_string_prop(payload, "type");
    assert_eq!(order_type, Some("fetch".into()));

    // Return unresolved Promise immediately
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(fetch_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Second order: timeout
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for timeout order");
    };
    assert_eq!(pending.len(), 1);

    // Host checks type to dispatch
    let payload = pending[0].payload.value();
    let order_type = get_string_prop(payload, "type");
    assert_eq!(order_type, Some("timeout".into()));
    let ms = get_number_prop(payload, "ms");
    assert_eq!(ms, Some(100.0));

    // Return unresolved Promise immediately
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Ok(RuntimeValue::unguarded(timeout_promise.value().clone())),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    // Now awaiting Promise.all - host can resolve concurrently
    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended for Promise.all");
    };
    assert!(pending.is_empty());

    // Simulate concurrent resolution (timeout resolves first, then fetch)
    api::resolve_promise(
        &mut interp,
        &timeout_promise,
        RuntimeValue::unguarded(JsValue::Undefined),
    )
    .unwrap();

    let fetch_data = api::create_response_object(&mut interp, &json!({ "name": "Alice" })).unwrap();
    api::resolve_promise(&mut interp, &fetch_promise, fetch_data).unwrap();

    let result = run_to_completion(&mut interp).unwrap();

    let StepResult::Complete(value) = result else {
        panic!("Expected Complete");
    };
    assert_eq!(*value, JsValue::String("Alice".into()));
}

#[test]
fn test_unknown_order_type_rejection() {
    // Test that unknown order types can be rejected by the host
    let mut interp = create_test_interp();

    let result = run_with_globals(
        &mut interp,
        r#"
        import { order } from "tsrun:host";

        try {
            const result = await order({ type: "unknown_type" });
            "success: " + result;
        } catch (e) {
            "error: " + e;
        }
    "#,
    );

    let StepResult::Suspended { pending, .. } = result else {
        panic!("Expected Suspended");
    };

    // Host checks type - unknown type, return error
    let order_type = get_string_prop(pending[0].payload.value(), "type");
    assert_eq!(order_type, Some("unknown_type".into()));

    // Reject with error for unknown type
    interp.fulfill_orders(vec![OrderResponse {
        id: pending[0].id,
        result: Err(tsrun::JsError::type_error(
            "Unknown order type: unknown_type",
        )),
    }]);
    let result = run_to_completion(&mut interp).unwrap();

    let StepResult::Complete(value) = result else {
        panic!("Expected Complete with error");
    };
    let result_str = value.as_str().expect("Expected string result");
    assert!(
        result_str.contains("Unknown order type"),
        "Expected error message, got: {}",
        result_str
    );
}