js-component-bindgen 2.12.1

JS component bindgen for transpiling WebAssembly components into JavaScript
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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
//! Intrinsics used from JS

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;
use std::sync::Mutex;

use wasmtime_environ::Trap;

use crate::source::Source;
use crate::{TranspileOpts, uwrite, uwriteln};

pub(crate) mod conversion;
use conversion::ConversionIntrinsic;

pub(crate) mod js_helper;
use js_helper::JsHelperIntrinsic;

pub(crate) mod webidl;
use webidl::WebIdlIntrinsic;

pub(crate) mod string;
use string::StringIntrinsic;

pub(crate) mod resource;
use resource::ResourceIntrinsic;

pub(crate) mod lift;
use lift::LiftIntrinsic;

pub(crate) mod lower;
use lower::LowerIntrinsic;

pub(crate) mod component;
use component::ComponentIntrinsic;

pub(crate) mod p3;
use p3::async_future::AsyncFutureIntrinsic;
use p3::async_stream::AsyncStreamIntrinsic;
use p3::async_task::AsyncTaskIntrinsic;
use p3::error_context::ErrCtxIntrinsic;
use p3::host::HostIntrinsic;
use p3::waitable::WaitableIntrinsic;

/// List of all intrinsics that are used by these
///
/// These intrinsics refer to JS code that is included in order to make
/// transpiled WebAssembly components and their imports/exports functional
/// in the relevant JS context.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum Intrinsic {
    JsHelper(JsHelperIntrinsic),
    WebIdl(WebIdlIntrinsic),
    Conversion(ConversionIntrinsic),
    String(StringIntrinsic),
    Resource(ResourceIntrinsic),
    ErrCtx(ErrCtxIntrinsic),
    AsyncTask(AsyncTaskIntrinsic),
    Waitable(WaitableIntrinsic),
    Lift(LiftIntrinsic),
    Lower(LowerIntrinsic),
    AsyncStream(AsyncStreamIntrinsic),
    AsyncFuture(AsyncFutureIntrinsic),
    Component(ComponentIntrinsic),
    Host(HostIntrinsic),

    // Polyfills
    PromiseWithResolversPonyfill,

    /// Enable debug logging
    DebugLog,

    /// Global setting for determinism (used in async)
    GlobalAsyncDeterminism,

    /// Randomly produce a boolean true/false
    CoinFlip,

    // Basic type helpers
    ConstantI32Max,
    ConstantI32Min,
    TypeCheckValidI32,
    TypeCheckAsyncFn,
    AsyncFunctionCtor,

    Base64Compile,
    ClampGuest,
    FetchCompile,

    // Globals
    SymbolCabiDispose,
    SymbolCabiLower,
    SymbolResourceHandle,
    SymbolResourceRep,
    SymbolDispose,
    SymbolAsyncIterator,
    SymbolIterator,
    ScopeId,
    HandleTables,

    /// Class that conforms to a `ReadableStreams`-like interface and is usable externally
    ///
    /// This is normally the `ReadableStream` class provided by the platform itself.
    PlatformReadableStreamClass,

    // Global Initializers
    FinalizationRegistryCreate,

    // Global classes
    ComponentError,
    WebAssemblyRuntimeError,

    /// Canonical trap messages indexed by their FACT discriminant.
    FactTrapMessages,

    // WASI object helpers
    GetErrorPayload,
    GetErrorPayloadString,

    /// Class that manages (and synchronizes) writes to managed buffers
    ManagedBufferClass,

    /// Buffer manager that is used to synchronize component writes
    BufferManagerClass,

    /// Global for an instantiated buffer manager singleton
    GlobalBufferManager,

    /// Reusable table structure for holding canonical ABI objects by their representation/identifier of (e.g. resources, waitables, etc)
    ///
    /// Representations of objects stored in one of these tables is a u32 (0 is expected to be an invalid index).
    RepTableClass,

    /// Event codes used for async, as a JS enum
    AsyncEventCodeEnum,

    // JS helper functions
    IsLE,
    ThrowInvalidBool,
    ThrowUninitialized,
    HasOwnProperty,
    InstantiateCore,

    /// Tracking of component memories
    GlobalComponentMemoryMap,

    /// Tracking of component memories
    RegisterGlobalMemoryForComponent,

    /// Tracking of component memories
    LookupMemoriesForComponent,

    /// Per-component task registers plus `current`, the task executing core Wasm.
    /// FACT adapters use `current` because they have no owning component.
    GlobalCurrentTaskMeta,

    /// Gets the current global task state
    GetGlobalCurrentTaskMetaFn,

    /// Gets the current global task state
    SetGlobalCurrentTaskMetaFn,

    /// Execute a closure with a certain set current task
    WithGlobalCurrentTaskMetaFn,

    /// Execute an async closure with a certain set current task
    WithGlobalCurrentTaskMetaFnAsync,

    /// Clear the global task meta
    ClearGlobalCurrentTaskMetaFn,

    /// Wrap the JS payload of a `WebAssembly.Suspending` import so the
    /// importing component's current-task register survives suspension
    SuspendingImportWrapperFn,

    /// Build an `(i32) -> i32` Wasm trampoline that calls a plain fast path
    /// before falling back to a JSPI-suspending slow path when it returns -2.
    ConditionalSuspending1I32ToI32Fn,

    /// Build an `(i32, i32) -> i32` Wasm trampoline that calls a plain fast
    /// path before falling back to a JSPI-suspending slow path.
    ConditionalSuspending2I32ToI32Fn,

    /// Build an `(i32, i32, i32) -> ()` Wasm trampoline that calls a plain fast
    /// path before falling back to a JSPI-suspending slow path.
    ConditionalSuspending3I32ToVoidFn,
}

macro_rules! impl_from_intrinsic {
    ($($ty:ty => $variant:ident),+ $(,)?) => {
        $(
            impl From<$ty> for Intrinsic {
                fn from(intrinsic: $ty) -> Self {
                    Self::$variant(intrinsic)
                }
            }
        )+
    };
}

impl_from_intrinsic! {
    JsHelperIntrinsic => JsHelper,
    WebIdlIntrinsic => WebIdl,
    ConversionIntrinsic => Conversion,
    StringIntrinsic => String,
    ResourceIntrinsic => Resource,
    ErrCtxIntrinsic => ErrCtx,
    AsyncTaskIntrinsic => AsyncTask,
    WaitableIntrinsic => Waitable,
    LiftIntrinsic => Lift,
    LowerIntrinsic => Lower,
    AsyncStreamIntrinsic => AsyncStream,
    AsyncFutureIntrinsic => AsyncFuture,
    ComponentIntrinsic => Component,
    HostIntrinsic => Host,
}

fn fact_trap_messages_js() -> String {
    let messages = (0..=u8::MAX)
        .filter_map(|code| {
            Trap::from_u8(code).map(|trap| format!("{code}: {:?}", trap.to_string()))
        })
        .collect::<Vec<_>>();
    format!("{{ {} }}", messages.join(", "))
}

impl Intrinsic {
    pub fn render(&self, output: &mut Source, args: &RenderIntrinsicsArgs) {
        match self {
            Intrinsic::JsHelper(i) => i.render(output, args),
            Intrinsic::Conversion(i) => i.render(output, args),
            Intrinsic::String(i) => i.render(output, args),
            Intrinsic::ErrCtx(i) => i.render(output, args),
            Intrinsic::Resource(i) => i.render(output, args),
            Intrinsic::AsyncTask(i) => i.render(output, args),
            Intrinsic::Waitable(i) => i.render(output, args),
            Intrinsic::Lift(i) => i.render(output, args),
            Intrinsic::Lower(i) => i.render(output, args),
            Intrinsic::AsyncStream(i) => i.render(output, args),
            Intrinsic::AsyncFuture(i) => i.render(output, args),
            Intrinsic::Component(i) => i.render(output, args),
            Intrinsic::Host(i) => i.render(output, args),

            Intrinsic::GlobalAsyncDeterminism => {
                uwriteln!(
                    output,
                    "const {var_name} = '{determinism}';",
                    var_name = self.name(),
                    determinism = args.determinism_profile,
                );
            }

            Intrinsic::CoinFlip => {
                uwriteln!(
                    output,
                    "const {var_name} = () => {{ return Math.random() > 0.5; }};",
                    var_name = self.name(),
                );
            }

            Intrinsic::ConstantI32Min => output.push_str(&format!(
                "const {const_name} = -2_147_483_648;\n",
                const_name = self.name()
            )),

            Intrinsic::ConstantI32Max => {
                uwriteln!(
                    output,
                    r#"
                      const {const_name} = 2_147_483_647;
                    "#,
                    const_name = self.name()
                )
            }

            Intrinsic::TypeCheckValidI32 => {
                let i32_const_min = args.require_intrinsic(Intrinsic::ConstantI32Min);
                let i32_const_max = args.require_intrinsic(Intrinsic::ConstantI32Max);

                uwriteln!(
                    output,
                    r#"
                      const {fn_name} = (n) => typeof n === 'number' && n >= {i32_const_min} && n <= {i32_const_max};
                    "#,
                    fn_name = self.name()
                );
            }

            Intrinsic::AsyncFunctionCtor => {
                let async_fn_type = args.require_intrinsic(Intrinsic::AsyncFunctionCtor);
                uwriteln!(
                    output,
                    "const {async_fn_type} = (async () => {{}}).constructor;"
                );
            }

            Intrinsic::TypeCheckAsyncFn => {
                let async_fn_check = args.require_intrinsic(Intrinsic::TypeCheckAsyncFn);
                let async_fn_ctor = args.require_intrinsic(Intrinsic::AsyncFunctionCtor);
                uwriteln!(
                    output,
                    r#"
                    const {async_fn_check} = (f) => {{
                        return f instanceof {async_fn_ctor};
                    }};
                    "#,
                );
            }

            Intrinsic::Base64Compile => {
                if !args.transpile_opts.nodejs_compat_disabled {
                    uwriteln!(
                        output,
                        r#"
                          const base64Compile = str => WebAssembly.compile(
                              typeof Buffer !== 'undefined'
                                  ? Buffer.from(str, 'base64')
                                  : Uint8Array.from(atob(str), b => b.charCodeAt(0))
                          );
                        "#
                    );
                } else {
                    uwriteln!(
                        output,
                        r#"
                          const base64Compile = str => WebAssembly.compile(Uint8Array.from(atob(str), b => b.charCodeAt(0)));
                        "#
                    );
                }
            }

            Intrinsic::ClampGuest => {
                uwriteln!(
                    output,
                    r#"
                      function clampGuest(i, min, max) {{
                          if (i < min || i > max) {{
                              throw new TypeError(`must be between ${{min}} and ${{max}}`);
                          }}
                          return i;
                      }}
                    "#
                );
            }

            Intrinsic::ComponentError => output.push_str(
                "
                class ComponentError extends Error {
                    constructor (value) {
                        const enumerable = typeof value !== 'string';
                        super(enumerable ? `${String(value)} (see error.payload)` : value);
                        Object.defineProperty(this, 'payload', { value, enumerable });
                    }
                }
            ",
            ),

            Intrinsic::WebAssemblyRuntimeError => {
                output.push_str("const WebAssemblyRuntimeError = WebAssembly.RuntimeError;\n")
            }

            Intrinsic::FactTrapMessages => {
                uwriteln!(
                    output,
                    "const {name} = {messages};",
                    name = self.name(),
                    messages = fact_trap_messages_js(),
                );
            }

            Intrinsic::FinalizationRegistryCreate => output.push_str(
                "
                function finalizationRegistryCreate (unregister) {
                    if (typeof FinalizationRegistry === 'undefined') {
                        return { unregister () {} };
                    }
                    return new FinalizationRegistry(unregister);
                }
            ",
            ),

            Intrinsic::FetchCompile => {
                if !args.transpile_opts.nodejs_compat_disabled {
                    output.push_str("
                    const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
                    let _fs;
                    async function fetchCompile (url) {
                        if (isNode) {
                            _fs = _fs || await import('node:fs/promises');
                            return WebAssembly.compile(await _fs.readFile(url));
                        }
                        return fetch(url).then(WebAssembly.compileStreaming);
                    }
                ")
                } else {
                    output.push_str(
                        "
                    const fetchCompile = url => fetch(url).then(WebAssembly.compileStreaming);
                ",
                    )
                }
            }

            Intrinsic::GetErrorPayload => {
                let hop = args.require_intrinsic(Intrinsic::HasOwnProperty);
                uwrite!(
                    output,
                    "
                    function getErrorPayload(e) {{
                        if (e && {hop}.call(e, 'payload')) return e.payload;
                        if (e instanceof Error) throw e;
                        return e;
                    }}
                "
                )
            }

            Intrinsic::GetErrorPayloadString => {
                let hop = args.require_intrinsic(Intrinsic::HasOwnProperty);
                uwrite!(
                    output,
                    "
                    function getErrorPayloadString(e) {{
                        if (e && {hop}.call(e, 'payload')) return e.payload;
                        if (e instanceof Error) return e.message;
                        return e;
                    }}
                "
                )
            }

            Intrinsic::WebIdl(w) => w.render(output),

            Intrinsic::HandleTables => {
                let var_name = self.name();
                uwriteln!(
                    output,
                    r#"
                      const {var_name} = [];
                    "#,
                );
            }

            Intrinsic::HasOwnProperty => output.push_str(
                "
                const hasOwnProperty = Object.prototype.hasOwnProperty;
            ",
            ),

            Intrinsic::InstantiateCore => {
                if !args.instantiation_occurred {
                    output.push_str(
                        "
                    const instantiateCore = WebAssembly.instantiate;
                ",
                    )
                }
            }

            Intrinsic::IsLE => output.push_str(
                "
                const isLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
            ",
            ),

            Intrinsic::SymbolCabiDispose => output.push_str(
                "
                const symbolCabiDispose = Symbol.for('cabiDispose');
            ",
            ),

            Intrinsic::SymbolCabiLower => output.push_str(
                "
                const symbolCabiLower = Symbol.for('cabiLower');
            ",
            ),

            Intrinsic::ScopeId => {
                let name = self.name();
                uwriteln!(output, "let {name} = 0;");
            }

            Intrinsic::SymbolResourceHandle => output.push_str(
                "
                const symbolRscHandle = Symbol('handle');
            ",
            ),

            Intrinsic::SymbolResourceRep => output.push_str(
                "
                const symbolRscRep = Symbol.for('cabiRep');
            ",
            ),

            Intrinsic::SymbolDispose => {
                let var_name = self.name();
                uwriteln!(
                    output,
                    "const {var_name} = Symbol.dispose || Symbol.for('dispose');"
                );
            }

            Intrinsic::SymbolAsyncIterator => {
                let var_name = self.name();
                uwriteln!(output, "const {var_name} = Symbol.asyncIterator;");
            }

            Intrinsic::SymbolIterator => {
                let var_name = self.name();
                uwriteln!(output, "const {var_name} = Symbol.iterator;");
            }

            Intrinsic::ThrowInvalidBool => output.push_str(
                "
                function throwInvalidBool() {
                    throw new TypeError('invalid variant discriminant for bool');
                }
            ",
            ),

            Intrinsic::ThrowUninitialized => output.push_str(
                "
                function throwUninitialized() {
                    throw new TypeError('Wasm uninitialized use `await $init` first');
                }
            ",
            ),

            Intrinsic::DebugLog => {
                let fn_name = args.require_intrinsic(Intrinsic::DebugLog);
                output.push_str(&format!(
                    "
                    const {fn_name} = (...args) => {{
                        if (!globalThis?.process?.env?.JCO_DEBUG) {{ return; }}
                        console.debug(...args);
                    }};
                "
                ));
            }

            Intrinsic::PromiseWithResolversPonyfill => {
                let fn_name = self.name();
                output.push_str(&format!(
                    r#"
                    function {fn_name}() {{
                        if (Promise.withResolvers) {{
                            return Promise.withResolvers();
                        }} else {{
                            let resolve;
                            let reject;
                            const promise = new Promise((res, rej) => {{
                                resolve = res;
                                reject = rej;
                            }});
                            return {{ promise, resolve, reject }};
                        }}
                    }}
                "#
                ));
            }

            Intrinsic::AsyncEventCodeEnum => {
                let name = args.require_intrinsic(Intrinsic::AsyncEventCodeEnum);
                output.push_str(&format!(
                    "
                    const {name} = {{
                        NONE: 0,
                        SUBTASK: 1,
                        STREAM_READ: 2,
                        STREAM_WRITE: 3,
                        FUTURE_READ: 4,
                        FUTURE_WRITE: 5,
                        TASK_CANCELLED: 6,
                    }};
                "
                ));
            }

            Intrinsic::ManagedBufferClass => {
                let debug_log_fn = args.require_intrinsic(Intrinsic::DebugLog);
                let managed_buffer_class = args.require_intrinsic(Intrinsic::ManagedBufferClass);
                let handle_tables = args.require_intrinsic(Intrinsic::HandleTables);
                let table_flag = args
                    .require_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
                let table_remove = args
                    .require_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
                let table_create_own = args.require_intrinsic(Intrinsic::Resource(
                    ResourceIntrinsic::ResourceTableCreateOwn,
                ));
                output.push_str(&format!(
                    r#"
                    class {managed_buffer_class} {{
                        static MAX_LENGTH = 2**28 - 1;
                        #componentIdx;
                        #memory;

                        #elemMeta = null;

                        #start;
                        #ptr;
                        capacity;
                        processed = 0;

                        #hostOnlyData; // initial data (only filled out for host-owned)

                        target;

                        constructor(args) {{
                            if (args.capacity > {managed_buffer_class}.MAX_LENGTH) {{
                                 throw new Error(`buffer size [${{args.capacity}}] greater than max length`);
                            }}
                            if (args.componentIdx === undefined) {{ throw new TypeError('missing/invalid component idx'); }}
                            if (args.capacity === undefined) {{ throw new TypeError('missing/invalid capacity'); }}
                            if (!args.elemMeta || typeof args.elemMeta.align32 !== 'number') {{
                                throw new TypeError('missing/invalid element metadata');
                            }}

                            if (!args.memory && args.start === undefined && args.data === undefined) {{
                                throw new TypeError('either memory and start ptr or data must be provided for managed buffers');
                            }}

                            if (args.memory && args.start == undefined) {{
                                throw new TypeError('missing/invalid start ptr, depsite memory being present');
                            }}

                            if (!args.elemMeta.isNone && args.capacity > 0) {{
                                if (args.start && args.start % args.elemMeta.align32 !== 0) {{
                                    throw new Error(`invalid alignment: type with 32bit alignment [${{args.elemMeta.align32}}] at starting pointer [${{args.start}}]`);
                                }}
                                // TODO: memory lenght bounds check
                            }}

                            this.#componentIdx = args.componentIdx;
                            this.#memory = args.memory;
                            this.#start = args.start;
                            this.#ptr = this.#start;
                            this.capacity = args.capacity;
                            this.#elemMeta = args.elemMeta;

                            if (args.data !== undefined && !Array.isArray(args.data)) {{
                                throw new TypeError('host-only data must be an array');
                            }}
                            this.#hostOnlyData = args.data;

                            this.target = args.target;
                        }}

                        setTarget(tgt) {{ this.target = tgt; }}

                        remaining() {{
                            return this.capacity - this.processed;
                        }}

                        componentIdx() {{ return this.#componentIdx; }}

                        getElemMeta() {{ return this.#elemMeta; }}

                        isHostOwned() {{ return !this.#memory; }}

                        read(count, opts = {{}}) {{
                            {debug_log_fn}('[{managed_buffer_class}#read()] args', {{ count }});
                            if (count === undefined || count <= 0) {{
                                throw new TypeError(`missing/invalid count [${{count}}]`);
                            }}

                            const cap = this.capacity;
                            if (count > cap) {{
                                throw new Error(`cannot read [${{count}}] elements from buffer with capacity [${{cap}}]`);
                            }}

                            let values = [];
                            if (this.#elemMeta.isNone) {{
                                values = [...new Array(count)].map(() => null);
                            }} else {{
                                if (this.isHostOwned()) {{
                                    values = this.#hostOnlyData.slice(0, count);
                                    this.#hostOnlyData = this.#hostOnlyData.slice(count);
                                }} else if (this.#elemMeta.payloadTypeName === 'U8') {{
                                    values = Array.from(new Uint8Array(this.#memory.buffer, this.#ptr, count));
                                    this.#ptr += count;
                                }} else {{
                                    let currentCount = count;
                                    let startPtr = this.#ptr;
                                    if (this.#elemMeta.stringEncoding === undefined) {{
                                        throw new Error('string encoding unknown during read');
                                    }}
                                    let liftCtx = {{
                                        storagePtr: startPtr,
                                        memory: this.#memory,
                                        componentIdx: this.#componentIdx,
                                        stringEncoding: this.#elemMeta.stringEncoding,
                                        liftResource: opts.transferResources ? (handle, tableIdx) => {{
                                            const {{ rep }} = {table_remove}({handle_tables}[tableIdx], handle);
                                            return {{ rep }};
                                        }} : undefined,
                                    }};
                                    if (currentCount < 0) {{ throw new Error('unexpectedly invalid count'); }}
                                    while (currentCount > 0) {{
                                        const [value, _ctx] = this.#elemMeta.liftFn(liftCtx);
                                        values.push(value);
                                        currentCount -= 1;
                                    }}
                                    this.#ptr = liftCtx.storagePtr;
                                }}
                            }}

                            this.processed += count;
                            return values;
                        }}

                        write(values, opts = {{}}) {{
                            {debug_log_fn}('[{managed_buffer_class}#write()] args', {{ values }});

                            if (!Array.isArray(values)) {{ throw new TypeError('values input to write() must be an array'); }}
                            let rc = this.remaining();
                            if (values.length > rc) {{
                                throw new Error(`cannot write [${{values.length}}] elements to managed buffer with remaining capacity [${{rc}}]`);
                            }}

                            if (this.#elemMeta.isNone) {{
                                if (!values.every(v => v === null)) {{
                                    throw new Error('non-null values in write() to unit managed buffer');
                                }}
                            }} else {{
                                if (this.isHostOwned()) {{
                                    this.#hostOnlyData = this.#hostOnlyData.concat(values);
                                }} else if (this.#elemMeta.payloadTypeName === 'U8') {{
                                    new Uint8Array(this.#memory.buffer, this.#ptr, values.length).set(values);
                                    this.#ptr += values.length;
                                }} else {{
                                    let startPtr = this.#ptr;
                                    if (this.#elemMeta.stringEncoding === undefined) {{
                                        throw new Error('string encoding unknown during write');
                                    }}

                                    const lowerCtx = {{
                                        memory: this.#memory,
                                        storagePtr: startPtr,
                                        componentIdx: this.#componentIdx,
                                        stringEncoding: this.#elemMeta.stringEncoding,
                                        realloc: this.#elemMeta.getReallocFn?.(),
                                        getReallocFn: this.#elemMeta.getReallocFn,
                                        lowerResource: opts.transferResources ? (resource, tableIdx) => {{
                                            let table = {handle_tables}[tableIdx];
                                            if (!table) {{
                                                table = [{table_flag}, 0];
                                                table._createdReps = new Set();
                                                {handle_tables}[tableIdx] = table;
                                            }}
                                            return {table_create_own}(table, resource.rep);
                                        }} : undefined,
                                    }}
                                    for (const v of values) {{
                                        lowerCtx.vals = [v];
                                        this.#elemMeta.lowerFn(lowerCtx);
                                    }}

                                    this.#ptr = lowerCtx.storagePtr;
                                }}
                            }}

                            this.processed += values.length;
                        }}

                    }}
                "#
                ));
            }

            Intrinsic::BufferManagerClass => {
                let debug_log_fn = args.require_intrinsic(Intrinsic::DebugLog);
                let buffer_manager_class = args.require_intrinsic(Intrinsic::BufferManagerClass);
                let managed_buffer_class = args.require_intrinsic(Intrinsic::ManagedBufferClass);

                output.push_str(&format!(r#"
                    class {buffer_manager_class} {{
                        #buffers = new Map();
                        #bufferIDs = new Map();

                        // NOTE: componentIdx === -1 indicates the host
                        getNextBufferID(componentIdx) {{
                            const current = this.#bufferIDs.get(componentIdx);
                            if (current === undefined) {{
                                this.#bufferIDs.set(componentIdx, 1n);
                                return 1n;
                            }}
                            const next = current + 1n;
                            this.#bufferIDs.set(componentIdx, next);
                            return next;
                        }}

                        getBuffer(componentIdx, bufferID) {{
                            {debug_log_fn}('[{buffer_manager_class}#getBuffer()] args', {{ componentIdx, bufferID }});
                            return this.#buffers.get(componentIdx)?.get(bufferID);
                        }}

                        createBuffer(args) {{
                            {debug_log_fn}('[{buffer_manager_class}#createBuffer()] args', args);
                            if (!args || typeof args !== 'object') {{ throw new TypeError('missing/invalid argument object'); }}

                            if (args.start === undefined && args.data === undefined) {{
                                throw new  TypeError('either a starting pointer or initial values must be provided');
                            }}

                            if (args.start !== undefined && args.componentIdx === undefined) {{ throw new TypeError('missing/invalid component idx'); }}
                            if (args.count === undefined) {{ throw new TypeError('missing/invalid obj count'); }}
                            if (!args.elemMeta) {{ throw new TypeError('missing/invalid element metadata for use with managed buffer'); }}

                            const {{ componentIdx, data, start, count }} = args;

                            if (!this.#buffers.has(componentIdx)) {{ this.#buffers.set(componentIdx, new Map()); }}
                            const instanceBuffers = this.#buffers.get(componentIdx);

                            const nextBufID = this.getNextBufferID(componentIdx);

                            const buffer = new {managed_buffer_class}({{
                                componentIdx,
                                memory: args.memory,
                                start: args.start,
                                capacity: args.count,
                                elemMeta: args.elemMeta,
                                data: args.data,
                                target: args.target,
                                stringEncoding: args.stringEncoding,
                            }});

                            if (instanceBuffers.has(nextBufID)) {{
                                throw new Error(`managed buffer with ID [${{nextBufID}}] already exists`);
                            }}
                            instanceBuffers.set(nextBufID, buffer);

                            return {{ id: nextBufID, buffer }};
                        }}

                        deleteBuffer(componentIdx, bufferID) {{
                            {debug_log_fn}('[{buffer_manager_class}#deleteBuffer()] args', {{ componentIdx, bufferID }});
                            return this.#buffers.get(componentIdx)?.delete(bufferID);
                        }}

                    }}
                "#));
            }

            Intrinsic::GlobalBufferManager => {
                let global_buffer_manager = args.require_intrinsic(Intrinsic::GlobalBufferManager);
                let buffer_manager_class = args.require_intrinsic(Intrinsic::BufferManagerClass);
                output.push_str(&format!(
                    "const {global_buffer_manager} = new {buffer_manager_class}();"
                ));
            }

            Intrinsic::RepTableClass => {
                let debug_log_fn = args.require_intrinsic(Intrinsic::DebugLog);
                let rep_table_class = args.require_intrinsic(Intrinsic::RepTableClass);
                output.push_str(&format!(r#"
                    class {rep_table_class} {{
                        // Sentinel marking a freed slot; the freelist link for a freed slot
                        // lives in the odd cell. This keeps get()/contains()/remove() on freed
                        // reps well-defined (previously they returned/corrupted freelist links).
                        static FREE = Symbol('{rep_table_class}.free');

                        #data = [0, null];
                        #size = 0;
                        #target;

                        constructor(args) {{
                            this.target = args?.target;
                        }}

                        data() {{ return this.#data; }}

                        insert(val) {{
                            {debug_log_fn}('[{rep_table_class}#insert()] args', {{ val, target: this.target }});
                            const freeIdx = this.#data[0];
                            if (freeIdx === 0) {{
                                this.#data.push(val);
                                this.#data.push(null);
                                const rep = (this.#data.length >> 1) - 1;
                                {debug_log_fn}('[{rep_table_class}#insert()] inserted', {{ val, target: this.target, rep }});
                                this.#size += 1;
                                return rep;
                            }}
                            const placementIdx = freeIdx << 1;
                            if (this.#data[placementIdx] !== {rep_table_class}.FREE) {{
                                throw new Error('corrupt rep table freelist: head does not point at a freed slot');
                            }}
                            this.#data[0] = this.#data[placementIdx + 1];
                            this.#data[placementIdx] = val;
                            this.#data[placementIdx + 1] = null;
                            {debug_log_fn}('[{rep_table_class}#insert()] inserted', {{ val, target: this.target, rep: freeIdx }});
                            this.#size += 1;
                            return freeIdx;
                        }}

                        get(rep) {{
                            {debug_log_fn}('[{rep_table_class}#get()] args', {{ rep, target: this.target }});
                            if (rep === 0) {{ throw new Error('invalid resource rep during get, (cannot be 0)'); }}

                            const baseIdx = rep << 1;
                            const val = this.#data[baseIdx];
                            if (val === {rep_table_class}.FREE) {{ return undefined; }}
                            return val;
                        }}

                        contains(rep) {{
                            {debug_log_fn}('[{rep_table_class}#contains()] args', {{ rep, target: this.target }});
                            if (rep === 0) {{ throw new Error('invalid resource rep during contains, (cannot be 0)'); }}

                            const baseIdx = rep << 1;
                            const val = this.#data[baseIdx];
                            return val !== {rep_table_class}.FREE && !!val;
                        }}

                        remove(rep) {{
                            {debug_log_fn}('[{rep_table_class}#remove()] args', {{ rep, target: this.target }});
                            if (rep === 0) {{ throw new Error('invalid resource rep during remove, (cannot be 0)'); }}
                            if (this.#data.length === 2) {{ throw new Error('invalid'); }}

                            const baseIdx = rep << 1;
                            if (baseIdx >= this.#data.length) {{
                                throw new Error(`invalid rep [${{rep}}] during remove, out of range`);
                            }}
                            const val = this.#data[baseIdx];
                            if (val === {rep_table_class}.FREE) {{
                                throw new Error(`double removal of rep [${{rep}}] (already freed)`);
                            }}

                            this.#data[baseIdx] = {rep_table_class}.FREE;
                            this.#data[baseIdx + 1] = this.#data[0];
                            this.#data[0] = rep;
                            this.#size -= 1;

                            return val;
                        }}

                        size() {{ return this.#size; }}

                        clear() {{
                            {debug_log_fn}('[{rep_table_class}#clear()] args', {{ rep, target: this.target }});
                            this.#data = [0, null];
                        }}
                    }}
                "#));
            }

            Intrinsic::GlobalComponentMemoryMap => {
                let global_component_memory_map =
                    args.require_intrinsic(Intrinsic::GlobalComponentMemoryMap);
                output.push_str(&format!(
                    "const {global_component_memory_map} = new Map();\n"
                ));
            }

            Intrinsic::RegisterGlobalMemoryForComponent => {
                let global_component_memory_map =
                    args.require_intrinsic(Intrinsic::GlobalComponentMemoryMap);
                let register_global_component_memory =
                    args.require_intrinsic(Intrinsic::RegisterGlobalMemoryForComponent);
                output.push_str(&format!(
                    r#"
                      function {register_global_component_memory}(args) {{
                          const {{ componentIdx, memory, memoryIdx }} = args ?? {{}};
                          if (componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          if (memory === undefined && memoryIdx === undefined) {{ throw new TypeError('missing both memory & memory idx'); }}
                          let inner = {global_component_memory_map}.get(componentIdx);
                          if (!inner) {{
                              inner = {{}};
                              {global_component_memory_map}.set(componentIdx, inner);
                          }}

                          inner[memoryIdx] = {{ memory, memoryIdx, componentIdx }};
                      }}
                    "#)
                );
            }

            Intrinsic::LookupMemoriesForComponent => {
                let global_component_memory_map =
                    args.require_intrinsic(Intrinsic::GlobalComponentMemoryMap);
                let lookup_global_memories_for_component =
                    args.require_intrinsic(Intrinsic::LookupMemoriesForComponent);
                output.push_str(&format!(
                    r#"
                      function {lookup_global_memories_for_component}(args) {{
                          const {{ componentIdx }} = args ?? {{}};
                          if (args.componentIdx === undefined) {{ throw new TypeError("missing component idx"); }}

                          const metas = {global_component_memory_map}.get(componentIdx);
                          if (!metas) {{ return []; }}

                          if (args.memoryIdx === undefined) {{
                              return Object.values(metas);
                          }}

                          const meta = metas[args.memoryIdx];
                          return meta?.memory;
                      }}
                    "#)
                );
            }

            Self::GlobalCurrentTaskMeta => {
                let name = self.name();
                output.push_str(&format!("const {name} = {{}};\n"));
            }

            Self::GetGlobalCurrentTaskMetaFn => {
                let get_current_global_task_meta_fn =
                    args.require_intrinsic(Self::GetGlobalCurrentTaskMetaFn);
                let global_current_task_meta_obj =
                    args.require_intrinsic(Self::GlobalCurrentTaskMeta);

                uwriteln!(
                    output,
                    r#"
                      function {get_current_global_task_meta_fn}(componentIdx) {{
                          const v = componentIdx === undefined || componentIdx === null
                              ? {global_current_task_meta_obj}.current
                              : {global_current_task_meta_obj}[componentIdx];
                          if (v === undefined || v === null) {{
                              return undefined;
                          }}
                          return {{ ...v }};
                      }}
                    "#,
                );
            }

            Self::SetGlobalCurrentTaskMetaFn => {
                let set_global_current_task_meta_fn = self.name();
                let global_current_task_meta_obj =
                    args.require_intrinsic(Self::GlobalCurrentTaskMeta);

                uwriteln!(
                    output,
                    r#"
                      function {set_global_current_task_meta_fn}(args) {{
                          if (!args) {{ throw new TypeError('args missing'); }}
                          if (args.taskID === undefined) {{ throw new TypeError('missing task ID'); }}
                          if (args.componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          const {{ taskID, componentIdx }} = args;
                          return {global_current_task_meta_obj}.current =
                              {global_current_task_meta_obj}[componentIdx] = {{ taskID, componentIdx }};
                      }}
                    "#,
                );
            }

            Self::WithGlobalCurrentTaskMetaFn => {
                let debug_log_fn = args.require_intrinsic(Intrinsic::DebugLog);
                let with_global_current_task_meta_fn =
                    args.require_intrinsic(Self::WithGlobalCurrentTaskMetaFn);
                let global_current_task_meta_obj =
                    args.require_intrinsic(Self::GlobalCurrentTaskMeta);

                output.push_str(&format!(
                    r#"
                      function {with_global_current_task_meta_fn}(args) {{
                          {debug_log_fn}('[{with_global_current_task_meta_fn}()] args', args);
                          if (!args) {{ throw new TypeError('args missing'); }}
                          if (args.taskID === undefined) {{ throw new TypeError('missing task ID'); }}
                          if (args.componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          if (!args.fn) {{ throw new TypeError('missing fn'); }}
                          const {{ taskID, componentIdx, fn }} = args;
                          const previous = {global_current_task_meta_obj}[componentIdx] ?? null;
                          const previousCurrent = {global_current_task_meta_obj}.current ?? null;

                          try {{
                              {global_current_task_meta_obj}.current =
                                  {global_current_task_meta_obj}[componentIdx] = {{ taskID, componentIdx }};
                              return fn();
                          }} catch (err) {{
                              {debug_log_fn}("error while executing sync callee/callback", {{
                                  ...args,
                                  err,
                              }});
                              throw err;
                          }} finally {{
                              // Synchronous wrappers can nest without any intervening JS
                              // scheduling. Restore the caller rather than clearing it so
                              // helper core exports (for example fused return adapters) can
                              // temporarily run under a different task of the same component.
                              {global_current_task_meta_obj}[componentIdx] = previous;
                              {global_current_task_meta_obj}.current = previousCurrent;
                          }}
                      }}
                    "#,
                ));
            }

            // NOTE: this function wrapper/closure intrinsic essentially acts as a
            // defactor task queue, ensuring that the right "current task" is set when
            // callees and/or callbacks (WebAssembly functions) run.
            //
            // The idea here is to avoid creating *our own* centralized task queue/event loop,
            // and allow the underlying JS runtime (NodeJS, Browser) to do it's normal scheduling.
            //
            // This costs us complexity -- an `await`/`.then()`/etc anywhere else could park a
            // runtime task and bring us here, in which case we'd be executing *right* before a completely
            // unrelated task (this matters most when it's multiple tasks in the same component idx)
            //
            // e.g.:
            // 1. [componentIdx 1, task 2] entered -- it's async so this is an `await task.enter()`
            // 2. JS runtime switches away from that task
            // 3. [componentIdx 1, task 1] already running, and is about to run it's callee or a callback
            //
            // At (3), we must be careful because the "current" thread is *not* [componentIdx 1, task 1] which
            // is about to try to run it's callback.
            //
            // This is complicated because when two tasks run at the same time, we have to ensure that the component
            // is not exclusively locked by one task. This generally happens @ task.enter(), but an interleaving
            // of events in which this check happens, then *another* task attempts to exclusively lock could happen.
            //
            // In the future, this mechanism may be replaced with a simple event loop that necessarily executes
            // all pending work serially, with this intrinsic becoming simply queueing work onto that event loop.
            //
            Self::WithGlobalCurrentTaskMetaFnAsync => {
                let debug_log_fn = args.require_intrinsic(Intrinsic::DebugLog);
                let with_global_current_task_meta_async_fn =
                    args.require_intrinsic(Self::WithGlobalCurrentTaskMetaFnAsync);
                let global_current_task_meta_obj =
                    args.require_intrinsic(Self::GlobalCurrentTaskMeta);

                output.push_str(&format!(
                    r#"
                      async function {with_global_current_task_meta_async_fn}(args) {{
                          {debug_log_fn}('[{with_global_current_task_meta_async_fn}()] args', args);
                          if (!args) {{ throw new TypeError('args missing'); }}
                          if (args.taskID === undefined) {{ throw new TypeError('missing task ID'); }}
                          if (args.componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          if (!args.fn) {{ throw new TypeError('missing fn'); }}

                          const {{ taskID, componentIdx, fn }} = args;

                          try {{
                              {global_current_task_meta_obj}.current =
                                  {global_current_task_meta_obj}[componentIdx] = {{ taskID, componentIdx }};
                              return await fn();
                          }} catch (err) {{
                              {debug_log_fn}("error while executing async callee/callback", {{
                                  ...args,
                                  err,
                              }});
                              throw err;
                          }} finally {{
                              {global_current_task_meta_obj}[componentIdx] = null;
                              if ({global_current_task_meta_obj}.current?.taskID === taskID) {{
                                  {global_current_task_meta_obj}.current = null;
                              }}
                          }}
                      }}
                    "#,
                ));
            }

            Self::ClearGlobalCurrentTaskMetaFn => {
                let debug_log_fn = args.require_intrinsic(Intrinsic::DebugLog);
                let clear_global_current_task_meta_fn =
                    args.require_intrinsic(Self::ClearGlobalCurrentTaskMetaFn);
                let global_current_task_meta_obj =
                    args.require_intrinsic(Self::GlobalCurrentTaskMeta);

                output.push_str(&format!(
                    r#"
                      async function {clear_global_current_task_meta_fn}(args) {{
                          {debug_log_fn}('[{clear_global_current_task_meta_fn}()] args', args);
                          if (!args) {{ throw new TypeError('args missing'); }}
                          if (args.taskID === undefined) {{ throw new TypeError('missing task ID'); }}
                          if (args.componentIdx === undefined) {{ throw new TypeError('missing component idx'); }}
                          const {{ taskID, componentIdx }} = args;

                          const meta = {global_current_task_meta_obj}[componentIdx];
                          if (!meta) {{ throw new Error(`missing current task meta for component idx [${{componentIdx}}]`); }}

                          if (meta.taskID !== taskID) {{
                              throw new Error(`task ID [${{meta.taskID}}] != requested ID [${{taskID}}]`);
                          }}
                          if (meta.componentIdx !== componentIdx) {{
                              throw new Error(`component idx [${{meta.componentIdx}}] != requested idx [${{componentIdx}}]`);
                          }}

                          {global_current_task_meta_obj}[componentIdx] = null;
                          if ({global_current_task_meta_obj}.current?.taskID === taskID) {{
                              {global_current_task_meta_obj}.current = null;
                          }}
                      }}
                    "#,
                ));
            }

            // Reject a blocking core start synchronously, before the JS engine
            // can abandon an unobserved promise. A nonblocking task may still
            // call a suspending import when the helper completes synchronously,
            // so preserve its raw result and reject only a returned promise.
            //
            // Run blocking helpers entirely inside an async function. Moving
            // the helper invocation outside that function changes JSPI
            // continuation scheduling and can strand later stream operations.
            // Restoring the captured entry is the last JS to run before the
            // suspended stack resumes. EnterSyncCall instead leaves the newly
            // entered callee current (switchesTask), including after lock contention.
            Self::SuspendingImportWrapperFn => {
                let suspending_import_wrapper_fn =
                    args.require_intrinsic(Self::SuspendingImportWrapperFn);
                let global_current_task_meta_obj =
                    args.require_intrinsic(Self::GlobalCurrentTaskMeta);
                let check_may_leave_fn = args.require_intrinsic(ComponentIntrinsic::CheckMayLeave);
                let current_task_may_block =
                    args.require_intrinsic(p3::async_task::AsyncTaskIntrinsic::CurrentTaskMayBlock);
                let get_current_task =
                    args.require_intrinsic(p3::async_task::AsyncTaskIntrinsic::GetCurrentTask);
                let runtime_error_class =
                    args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);

                output.push_str(&format!(
                    r#"
                      function {suspending_import_wrapper_fn}(componentIdx, fn, syncOnly = false, switchesTask = false) {{
                          return function (...args) {{
                              {check_may_leave_fn}(componentIdx);
                              const saved = {global_current_task_meta_obj}[componentIdx] ?? null;

                              const savedTask = saved
                                  ? {get_current_task}(saved.componentIdx, saved.taskID)?.task
                                  : null;
                              const mayBlock = savedTask
                                  ? (savedTask?.mayBlock() ?? ({current_task_may_block}.value !== 0))
                                  : false;
                              if (!saved && !mayBlock) {{
                                  throw new {runtime_error_class}('cannot block a synchronous task before returning');
                              }}

                              if (syncOnly || !mayBlock) {{
                                  let result;
                                  try {{
                                      result = fn.apply(null, args);
                                  }} catch (err) {{
                                      {global_current_task_meta_obj}[componentIdx] = saved;
                                      if (!switchesTask) {{ {global_current_task_meta_obj}.current = saved; }}
                                      throw err;
                                  }}

                                  {global_current_task_meta_obj}[componentIdx] = saved;
                                  if (!switchesTask) {{ {global_current_task_meta_obj}.current = saved; }}

                                  if (result !== null &&
                                      (typeof result === 'object' || typeof result === 'function') &&
                                      typeof result.then === 'function') {{
                                      // The helper may already have returned a rejected promise.
                                      // Mark it handled before replacing it with the canonical
                                      // synchronous-task trap.
                                      Promise.resolve(result).catch(() => {{}});
                                      throw new {runtime_error_class}('cannot block a synchronous task before returning');
                                  }}
                                  return result;
                              }}

                              return (async () => {{
                                  try {{
                                      return await fn.apply(null, args);
                                  }} finally {{
                                      {global_current_task_meta_obj}[componentIdx] = saved;
                                      if (!switchesTask) {{ {global_current_task_meta_obj}.current = saved; }}
                                  }}
                              }})();
                          }};
                      }}
                    "#,
                ));
            }

            Self::ConditionalSuspending2I32ToI32Fn => {
                let conditional_suspending_fn =
                    args.require_intrinsic(Self::ConditionalSuspending2I32ToI32Fn);

                output.push_str(&format!(
                    r#"
                      const {conditional_suspending_fn}Module = new WebAssembly.Module(new Uint8Array([
                          0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
                          0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,
                          0x02, 0x11, 0x02, 0x00, 0x04, 0x66, 0x61, 0x73, 0x74,
                          0x00, 0x00, 0x00, 0x04, 0x73, 0x6c, 0x6f, 0x77, 0x00,
                          0x00, 0x03, 0x02, 0x01, 0x00, 0x07, 0x07, 0x01, 0x03,
                          0x72, 0x75, 0x6e, 0x00, 0x02, 0x0a, 0x1d, 0x01, 0x1b,
                          0x01, 0x01, 0x7f, 0x20, 0x00, 0x20, 0x01, 0x10, 0x00,
                          0x22, 0x02, 0x41, 0x7f, 0x47, 0x04, 0x7f, 0x20, 0x02,
                          0x05, 0x20, 0x00, 0x20, 0x01, 0x10, 0x01, 0x0b, 0x0b,
                      ]));

                      function {conditional_suspending_fn}(fast, slow) {{
                          return new WebAssembly.Instance(
                              {conditional_suspending_fn}Module,
                              {{ '': {{ fast, slow: new WebAssembly.Suspending(slow) }} }},
                          ).exports.run;
                      }}
                    "#,
                ));
            }

            Self::ConditionalSuspending1I32ToI32Fn => {
                let conditional_suspending_fn =
                    args.require_intrinsic(Self::ConditionalSuspending1I32ToI32Fn);

                output.push_str(&format!(
                    r#"
                      const {conditional_suspending_fn}Module = new WebAssembly.Module(new Uint8Array([
                          0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
                          0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,
                          0x02, 0x11, 0x02, 0x00, 0x04, 0x66, 0x61, 0x73,
                          0x74, 0x00, 0x00, 0x00, 0x04, 0x73, 0x6c, 0x6f,
                          0x77, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0x07,
                          0x07, 0x01, 0x03, 0x72, 0x75, 0x6e, 0x00, 0x02,
                          0x0a, 0x19, 0x01, 0x17, 0x01, 0x01, 0x7f, 0x20,
                          0x00, 0x10, 0x00, 0x22, 0x01, 0x41, 0x7e, 0x47,
                          0x04, 0x7f, 0x20, 0x01, 0x05, 0x20, 0x00, 0x10,
                          0x01, 0x0b, 0x0b,
                      ]));

                      function {conditional_suspending_fn}(fast, slow) {{
                          return new WebAssembly.Instance(
                              {conditional_suspending_fn}Module,
                              {{ '': {{ fast, slow: new WebAssembly.Suspending(slow) }} }},
                          ).exports.run;
                      }}
                    "#,
                ));
            }

            Self::ConditionalSuspending3I32ToVoidFn => {
                let conditional_suspending_fn =
                    args.require_intrinsic(Self::ConditionalSuspending3I32ToVoidFn);

                output.push_str(&format!(
                    r#"
                      const {conditional_suspending_fn}Module = new WebAssembly.Module(new Uint8Array([
                          0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
                          0x01, 0x0e, 0x02, 0x60, 0x03, 0x7f, 0x7f, 0x7f,
                          0x01, 0x7f, 0x60, 0x03, 0x7f, 0x7f, 0x7f, 0x00,
                          0x02, 0x11, 0x02, 0x00, 0x04, 0x66, 0x61, 0x73,
                          0x74, 0x00, 0x00, 0x00, 0x04, 0x73, 0x6c, 0x6f,
                          0x77, 0x00, 0x00, 0x03, 0x02, 0x01, 0x01, 0x07,
                          0x07, 0x01, 0x03, 0x72, 0x75, 0x6e, 0x00, 0x02,
                          0x0a, 0x19, 0x01, 0x17, 0x00, 0x20, 0x00, 0x20,
                          0x01, 0x20, 0x02, 0x10, 0x00, 0x45, 0x04, 0x40,
                          0x20, 0x00, 0x20, 0x01, 0x20, 0x02, 0x10, 0x01,
                          0x1a, 0x0b, 0x0b,
                      ]));

                      function {conditional_suspending_fn}(fast, slow) {{
                          return new WebAssembly.Instance(
                              {conditional_suspending_fn}Module,
                              {{ '': {{ fast, slow: new WebAssembly.Suspending(slow) }} }},
                          ).exports.run;
                      }}
                    "#,
                ));
            }

            // TODO(feat): customizable stream classes
            Intrinsic::PlatformReadableStreamClass => {
                let name = self.name();
                uwriteln!(
                    output,
                    r#"
                        if (!ReadableStream) {{
                            throw new Error('builtin stream class [ReadableStream] is not available');
                        }}
                        const {name} = ReadableStream;
                    "#
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn render(initial: impl IntoIterator<Item = Intrinsic>) -> (Source, BTreeSet<Intrinsic>) {
        let mut intrinsics = initial.into_iter().collect();
        let opts = TranspileOpts::default();
        let source = render_intrinsics(
            RenderIntrinsicsArgs::builder()
                .intrinsics(&mut intrinsics)
                .transpile_opts(&opts)
                .build(),
        );
        (source, intrinsics)
    }

    fn render_intrinsic_body(intrinsic: Intrinsic) -> Source {
        let mut source = Source::default();
        let mut intrinsics = BTreeSet::new();
        let opts = TranspileOpts::default();
        let args = RenderIntrinsicsArgs::builder()
            .intrinsics(&mut intrinsics)
            .transpile_opts(&opts)
            .build();
        intrinsic.render(&mut source, &args);
        source
    }

    #[test]
    fn renders_only_requested_and_discovered_intrinsics() {
        let (source, intrinsics) = render([Intrinsic::CoinFlip]);

        assert_eq!(intrinsics, BTreeSet::from([Intrinsic::CoinFlip]));
        assert!(source.contains("Math.random()"));
        assert!(!source.contains("_debugLog"));
        assert!(!source.contains("class RepTable"));
    }

    #[test]
    fn fact_trap_messages_are_shared_and_emitted_on_demand() {
        let (source, intrinsics) = render([Intrinsic::FactTrapMessages]);

        assert_eq!(intrinsics, BTreeSet::from([Intrinsic::FactTrapMessages]));
        assert_eq!(source.matches("const FACT_TRAP_MESSAGES =").count(), 1);
        assert!(source.contains(&format!(
            "{}: {:?}",
            Trap::CannotEnterComponent as u8,
            "wasm trap: cannot enter component instance"
        )));
        assert!(source.contains(&format!(
            "{}: {:?}",
            Trap::CannotLeaveComponent as u8,
            "wasm trap: cannot leave component instance"
        )));

        let (source, intrinsics) = render([Intrinsic::WebAssemblyRuntimeError]);
        assert!(!intrinsics.contains(&Intrinsic::FactTrapMessages));
        assert!(!source.contains("FACT_TRAP_MESSAGES"));
    }

    #[test]
    fn component_async_state_does_not_pull_in_create_stream_or_create_future() {
        let state = Intrinsic::Component(ComponentIntrinsic::ComponentAsyncStateClass);
        let create_stream = Intrinsic::AsyncStream(AsyncStreamIntrinsic::CreateStream);
        let get_stream_end = Intrinsic::AsyncStream(AsyncStreamIntrinsic::GetStreamEnd);
        let create_future = Intrinsic::AsyncFuture(AsyncFutureIntrinsic::CreateFuture);
        let get_future_end = Intrinsic::AsyncFuture(AsyncFutureIntrinsic::GetFutureEnd);
        let (source, intrinsics) = render([state]);

        assert!(!intrinsics.contains(&create_stream));
        assert!(!intrinsics.contains(&get_stream_end));
        assert!(!intrinsics.contains(&create_future));
        assert!(!intrinsics.contains(&get_future_end));
        assert!(!source.contains("function createStream(cstate, args)"));
        assert!(!source.contains("function createFuture(cstate, args)"));

        let (source, _) = render([create_stream]);
        assert!(source.contains("function createStream(cstate, args)"));
        assert!(!source.contains("function getStreamEnd(args)"));
        assert!(!source.contains("function createFuture(cstate, args)"));

        let (source, _) = render([create_future]);
        assert!(source.contains("function createFuture(cstate, args)"));
        assert!(!source.contains("function getFutureEnd(args)"));
        assert!(!source.contains("function createStream(cstate, args)"));

        let (_, intrinsics) = render([Intrinsic::Lift(LiftIntrinsic::LiftFlatStream)]);
        assert!(intrinsics.contains(&get_stream_end));
        assert!(!intrinsics.contains(&create_stream));

        let (_, intrinsics) = render([Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture)]);
        assert!(intrinsics.contains(&get_future_end));
        assert!(!intrinsics.contains(&create_future));
    }

    #[test]
    fn invalid_resource_handles_use_canonical_traps() {
        let get = Intrinsic::Resource(ResourceIntrinsic::ResourceTableGet);
        let remove = Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove);
        let (source, _) = render([get, remove]);

        assert!(source.contains(
            "throw new WebAssemblyRuntimeError(`unknown handle index ${(handle << 1) + 1}`);"
        ));
    }

    #[test]
    fn stream_and_future_helpers_are_individual_intrinsics() {
        let helpers = [
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::CreateStream),
                "createStream",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::GetStreamEnd),
                "getStreamEnd",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::AddStreamEndToTable),
                "addStreamEndToTable",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::DeleteStreamEnd),
                "deleteStreamEnd",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::RemoveStreamEndFromTable),
                "removeStreamEndFromTable",
            ),
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::CreateFuture),
                "createFuture",
            ),
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::GetFutureEnd),
                "getFutureEnd",
            ),
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::AddFutureEndToTable),
                "addFutureEndToTable",
            ),
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::RemoveFutureEndFromTable),
                "removeFutureEndFromTable",
            ),
        ];

        for &(intrinsic, name) in &helpers {
            let (source, intrinsics) = render([intrinsic]);
            assert!(intrinsics.contains(&intrinsic));

            for &(_, other_name) in &helpers {
                assert_eq!(
                    source.contains(&format!("function {other_name}(")),
                    name == other_name,
                    "rendering {name} unexpectedly changed whether {other_name} was emitted",
                );
            }
        }
    }

    #[test]
    fn discovers_transitive_dependencies_in_dependency_order() {
        let transfer = Intrinsic::Resource(ResourceIntrinsic::ResourceTransferBorrow);
        let table_flag = Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag);
        let table_get = Intrinsic::Resource(ResourceIntrinsic::ResourceTableGet);
        let table_remove = Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove);
        let (source, intrinsics) = render([transfer]);

        for dependency in [table_flag, table_get] {
            assert!(intrinsics.contains(&dependency));
        }
        assert!(!intrinsics.contains(&table_remove));

        let flag_position = source.find("const T_FLAG").unwrap();
        let get_position = source.find("function rscTableGet").unwrap();
        let transfer_position = source.find("function resourceTransferBorrow").unwrap();
        assert!(flag_position < get_position);
        assert!(get_position < transfer_position);
    }

    #[test]
    fn self_dependencies_are_cycle_safe() {
        let current_tasks = Intrinsic::AsyncTask(AsyncTaskIntrinsic::GlobalAsyncCurrentTaskMap);
        let (source, intrinsics) = render([current_tasks]);

        assert_eq!(intrinsics, BTreeSet::from([current_tasks]));
        assert_eq!(
            source.matches("const ASYNC_TASKS_BY_COMPONENT_IDX").count(),
            1
        );
    }

    #[test]
    fn sync_current_task_wrapper_restores_nested_task() {
        let (source, _) = render([Intrinsic::WithGlobalCurrentTaskMetaFn]);

        assert!(source.contains("const previous = CURRENT_TASK_META[componentIdx] ?? null;"));
        assert!(source.contains("CURRENT_TASK_META[componentIdx] = previous;"));
    }

    #[test]
    fn suspending_import_preserves_sync_results_and_rejects_disallowed_blocking() {
        let source = render_intrinsic_body(Intrinsic::SuspendingImportWrapperFn);

        assert!(source.contains("return function (...args) {"));
        assert!(source.contains("syncOnly = false"));
        assert!(
            source.contains("? (savedTask?.mayBlock() ?? (CURRENT_TASK_MAY_BLOCK.value !== 0))")
        );
        assert!(source.contains(": false;"));
        assert!(source.contains("if (syncOnly || !mayBlock) {"));

        assert!(!source.contains("return async function (...args) {"));
        assert!(source.contains("if (!saved && !mayBlock) {"));

        assert!(source.contains("result = fn.apply(null, args);"));
        assert!(source.contains("typeof result.then === 'function'"));
        assert!(source.contains("Promise.resolve(result).catch(() => {});"));
        assert!(source.contains("if (syncOnly || !mayBlock) {"));
        assert!(source.contains(
            "new WebAssemblyRuntimeError('cannot block a synchronous task before returning')"
        ));
        assert!(source.contains("return (async () => {"));
        assert!(source.contains("return await fn.apply(null, args);"));
        assert!(source.contains("CURRENT_TASK_META[componentIdx] = saved;"));
    }

    #[test]
    fn manually_async_tasks_may_block() {
        let source =
            render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass));

        assert!(source.contains("isManualAsync() { return this.#isManualAsync; }"));
        assert!(source.contains(
            "mayBlock() { return this.isAsync() || this.isManualAsync() || this.isResolvedState() }"
        ));
    }

    #[test]
    fn resource_destructor_call_creates_and_completes_a_sync_guest_task() {
        let source = render_intrinsic_body(Intrinsic::Resource(
            ResourceIntrinsic::ResourceDestructorCall,
        ));

        assert!(!source.contains("if (_getGlobalCurrentTaskMeta(componentIdx))"));
        assert!(source.contains("const result = dtor(rep);"));
        assert!(source.contains("const [task] = createNewCurrentTask({"));
        assert!(source.contains("isAsync: false,"));
        assert!(source.contains("callingWasmExport: true,"));
        assert!(source.contains("task.enterSync();"));
        assert!(source.contains("return _withGlobalCurrentTaskMeta({"));
        assert!(source.contains("task.resolve([]);"));
        assert!(source.contains("task.exit();"));
        assert!(source.contains("task.setErrored(err);"));
        assert!(source.contains("task.reject(err);"));
        assert!(source.contains("task.exit({ skipExclusiveLockCheck: true });"));
    }

    #[test]
    fn task_return_fused_adapter_runs_in_the_caller_task() {
        let source = render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::TaskReturn));

        assert!(source.contains("const callerTask = task.getParentSubtask().getParentTask();"));
        assert!(source.contains("taskID: callerTask.id(),"));
        assert!(source.contains("componentIdx: callerTask.componentIdx(),"));
        assert!(source.contains(
            "fn: () => subtaskCallMetadata.returnFn.apply(null, [...params, subtaskCallMetadata.resultPtr]),"
        ));
    }

    #[test]
    fn deferred_fused_adapter_runs_in_the_caller_task() {
        let source =
            render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass));

        assert!(source.contains("const callerTask = this.#parentSubtask.getParentTask();"));
        assert!(source.contains("taskID: callerTask.id(),"));
        assert!(source.contains("componentIdx: callerTask.componentIdx(),"));
        assert!(
            source.contains("fn: () => meta.returnFn.apply(null, [taskValue, meta.resultPtr]),")
        );
    }

    #[test]
    fn async_task_post_return_runs_in_the_completing_task() {
        let source =
            render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass));

        assert!(source.contains("taskID: this.#id,"));
        assert!(source.contains("componentIdx: this.#componentIdx,"));
        assert!(source.contains("fn: () => this.#postReturnFn(taskValue),"));
    }

    #[test]
    fn cancelled_tasks_skip_return_lowering_and_post_return() {
        let source =
            render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass));

        assert!(source.contains("const taskReturned = !this.isCancelled();"));
        assert!(source.contains("if (parentSubtaskPending && taskReturned) {"));
        assert!(source.contains("if (this.#postReturnFn && taskReturned) {"));
    }

    #[test]
    fn async_start_fused_adapter_runs_in_the_caller_task() {
        let source = render_intrinsic_body(Intrinsic::Host(HostIntrinsic::AsyncStartCall));

        assert!(source.contains("const callerTask = subtask.getParentTask();"));
        assert!(source.contains("taskID: callerTask.id(),"));
        assert!(source.contains("componentIdx: callerTask.componentIdx(),"));
        assert!(source.contains(
            "fn: () => subtaskCallMeta.returnFn.apply(null, [subtaskCallMeta.resultPtr]),"
        ));
        assert!(source.contains("preparedTask.setCalleeIsAsync((flags & 1) !== 0);"));
        // Every callee attempts eager entry.  `tryEnter` preserves STARTING only for real
        // backpressure or lock contention, while otherwise exposing STARTED after the
        // callee has run to its first suspension point.
        assert!(source.contains("const enteredSynchronously = preparedTask.tryEnter();"));
        assert!(!source.contains("const mayStartSynchronously"));
        assert!(source.contains("fn: () => callee.apply(null, startRes),"));
        assert!(!source.contains("if (callbackResult !== undefined)"));
        assert!(source.contains("driveCallback(callbackResult)?.catch(err =>"));
        assert!(source.contains("const driveJspiCallee = async () => {"));
        assert!(source.contains("if (enteredSynchronously === true) {"));
        assert!(source.contains("startSubtask();"));
        assert!(source.contains("registerSubtaskProgress();"));
        assert!(source.contains("driveJspiCallee();"));
        assert!(source.contains("} else if (enteredSynchronously === null) {"));
        assert!(source.contains("const enterPromise = preparedTask.enter().then(started => {"));
        assert!(source.contains("if (subtask.isReturned()) {"));
        assert!(source.contains("callerComponentState.handles.remove(subtask.waitableRep())"));
    }

    #[test]
    fn subtask_cancel_drives_one_cancellable_child_slice() {
        let cancel = render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::SubtaskCancel));
        assert!(cancel.contains("childState.suspendedTaskReady(childTask.id())"));
        assert!(cancel.contains("childState.resumeTaskByID(childTask.id())"));
        assert!(cancel.contains("function subtaskCancel"));
        assert!(!cancel.contains("async function subtaskCancel"));
        assert!(cancel.contains(".then(finishCancel)"));
        assert!(cancel.contains("cancellationWillCompleteAsync ? 0xFFFFFFFE : 0xFFFFFFFF"));
        assert!(cancel.contains("childState.exclusivelyLockedBy(childTask.id())"));
        assert!(cancel.contains("!childState.isTaskSuspended(childTask.id())"));
        assert!(cancel.contains("return progress.then(() =>"));
        let subscribe = cancel.find("childTask?.waitForProgress()").unwrap();
        let request = cancel.find("subtask.requestCancellation();").unwrap();
        assert!(subscribe < request);

        let task = render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass));
        assert!(task.contains("suspendUntilCallback(opts, onResume)"));
        assert!(task.contains("this.#callbackFn._jcoMaySuspend === false"));
        assert!(task.contains("if (this.isResolvedState() || this.isCancelled())"));
        assert!(task.contains("cancellationRequested() { return this.cancelRequested; }"));
        let release = task
            .find("state.exclusiveRelease(this.#id);")
            .expect("task exit should release component entry");
        let progress = task
            .find("this.notifyProgress();")
            .expect("task exit should report progress");
        assert!(release < progress);
        assert!(task.contains("parentTask.notifyProgress();"));

        let state = render_intrinsic_body(Intrinsic::Component(
            ComponentIntrinsic::ComponentAsyncStateClass,
        ));
        assert!(state.contains("const { task, readyFn, cancellable, onResume } = args;"));
        assert!(state.contains("resume = () => onResume(!task.isCancelled());"));
        assert!(state.contains("suspendedTaskCancellable(taskID)"));
        assert!(state.contains("task.notifyProgress();"));
        assert!(state.contains("suspendedTaskReady(taskID)"));
    }

    #[test]
    fn cancellation_cleanup_can_start_host_imports() {
        let lower = render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::LowerImport));
        assert!(lower.contains("subtask.cancellationRequested()"));
        assert!(lower.contains("task.taskState() === AsyncTask.State.CANCEL_PENDING"));
        assert!(!lower.contains("if (task.cancellationRequested())"));
    }

    #[test]
    fn cancellable_wait_poll_and_yield_reach_task_state() {
        let waitable_set =
            render_intrinsic_body(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetClass));
        assert!(waitable_set.contains("tryWait(opts)"));
        assert!(waitable_set.contains("waitUntil(opts)"));
        assert!(!waitable_set.contains("async waitUntil(opts)"));
        assert!(waitable_set.contains("if (isReady()) { return finishWait(true); }"));

        let wait = render_intrinsic_body(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetWait));
        assert!(wait.contains("const wset = cstate.handles.get(waitableSetRep);"));
        assert!(!wait.contains("await cstate.handles.get(waitableSetRep);"));
        assert!(wait.contains("cancellable: isCancellable"));
        assert!(wait.contains("function waitableSetWait"));
        assert!(!wait.contains("async function waitableSetWait"));
        assert!(wait.contains("syncOnly ? wset.tryWait(waitOpts) : wset.waitUntil(waitOpts)"));
        assert!(wait.contains("return event.then(storeEvent);"));

        let conditional = render_intrinsic_body(Intrinsic::ConditionalSuspending2I32ToI32Fn);
        assert!(conditional.contains("new WebAssembly.Suspending(slow)"));
        assert!(conditional.contains("0x66, 0x61, 0x73, 0x74"));

        let poll = render_intrinsic_body(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetPoll));
        assert!(poll.contains("deliverPendingCancel({ cancellable: isCancellable })"));

        let yield_ = render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::Yield));
        assert!(yield_.contains("const keepGoing = await task.immediateSuspend({"));
        assert!(yield_.contains("cancellable: isCancellable"));
        assert!(yield_.contains("return keepGoing ? 0 : 1;"));
    }

    #[test]
    fn async_scheduler_detects_store_wide_deadlocks() {
        let state = render_intrinsic_body(Intrinsic::Component(
            ComponentIntrinsic::ComponentAsyncStateClass,
        ));
        assert!(state.contains("_checkForDeadlock();"));
        assert!(state.contains("suspendedTaskMetas()"));
        assert!(state.contains("hasPendingSchedulerWork()"));

        let check =
            render_intrinsic_body(Intrinsic::Component(ComponentIntrinsic::CheckForDeadlock));
        assert!(check.contains("for (const state of ASYNC_STATE.values())"));
        assert!(check.contains("STORE_ASYNC_STATE.pendingHostOperations > 0"));
        assert!(check.contains("const root = task.getRootTask();"));
        assert!(check.contains(
            "new WebAssemblyRuntimeError('wasm trap: deadlock detected: event loop cannot make further progress')"
        ));
        assert!(check.contains("for (const root of unresolvedRoots)"));
        assert!(check.contains("root.reject(err);"));
        assert!(check.contains("task.reject(err);"));
    }

    #[test]
    fn detected_deadlocks_carry_the_state_that_produced_them() {
        let check =
            render_intrinsic_body(Intrinsic::Component(ComponentIntrinsic::CheckForDeadlock));

        // The message is what the Canonical ABI asks for and is asserted on elsewhere, so
        // the state that produced the deadlock rides beside it rather than inside it.
        assert!(check.contains("err.deadlockDetail = {"));
        assert!(check.contains("pendingHostOperations: STORE_ASYNC_STATE.pendingHostOperations,"));
        assert!(check.contains("taskID: task.id(),"));
        assert!(check.contains("componentIdx: task.componentIdx(),"));
        assert!(check.contains("state: task.taskState(),"));
        assert!(check.contains("rootTaskID: task.getRootTask().id(),"));
        assert!(check.contains("unresolvedRootTaskIDs:"));
    }

    #[test]
    fn deferred_stream_cancel_is_tracked_as_host_work() {
        // A guest cancelling a read on a host-lowered stream is suspended until the
        // deferred cancel completion runs. Counting that deferral like a host operation
        // keeps an already-scheduled deadlock check from reporting the wait.
        for intrinsic in [
            AsyncStreamIntrinsic::StreamReadableEndClass,
            AsyncStreamIntrinsic::StreamWritableEndClass,
        ] {
            let end = render_intrinsic_body(Intrinsic::AsyncStream(intrinsic));
            assert!(end.contains("_trackHostOperation(() => new Promise((resolve) => {"));
            assert!(end.contains("try { completeCancel(); } finally { resolve(); }"));
            assert!(!end.contains("setTimeout(completeCancel, 0);"));
        }
    }

    #[test]
    fn injected_stream_writes_reset_the_write_end_before_writing() {
        // Back-to-back guest reads can outrun the lazy consumption of the previous
        // injected write's completion event; the next write must not start while
        // that stale event still marks the write end as copying.
        let inject = render_intrinsic_body(Intrinsic::AsyncStream(
            AsyncStreamIntrinsic::GenStreamHostInjectFn,
        ));
        let write_values = inject
            .find("const writeValues = async (writeValues, dropAfterCopy = false) => {")
            .expect("writeValues helper");
        let write_values_body = &inject[write_values..];
        let reset = write_values_body
            .find("resetWriteEndToIdleFn();")
            .expect("reset before injected write");
        let write = write_values_body
            .find("hostWriteEnd.writeMany(writeValues, { dropAfterCopy });")
            .expect("injected write");
        assert!(reset < write);

        let cancel = inject
            .find("readEnd.setHostCancelFn?.(() => {")
            .expect("host cancel fn");
        let cancel_body = &inject[cancel..];
        let reset = cancel_body
            .find("resetWriteEndToIdleFn();")
            .expect("reset before cancel write");
        let write = cancel_body
            .find("hostWriteEnd.writeMany(cancelValues);")
            .expect("cancel write");
        assert!(reset < write);
    }

    #[test]
    fn host_async_operations_suppress_deadlock_detection() {
        let tracker =
            render_intrinsic_body(Intrinsic::Component(ComponentIntrinsic::TrackHostOperation));
        assert!(tracker.contains("STORE_ASYNC_STATE.pendingHostOperations++;"));
        assert!(tracker.contains("Promise.resolve(result).finally(() =>"));
        assert!(tracker.contains("STORE_ASYNC_STATE.pendingHostOperations--;"));
        assert!(tracker.contains("_checkForDeadlock();"));

        let future = render_intrinsic_body(Intrinsic::AsyncFuture(
            AsyncFutureIntrinsic::GenFutureHostInjectFn,
        ));
        assert!(future.contains("await _trackHostOperation(() => promise);"));

        let stream = render_intrinsic_body(Intrinsic::AsyncStream(
            AsyncStreamIntrinsic::PendingValueQueueClass,
        ));
        assert!(stream.contains("await _trackHostOperation(() => this.#readFn());"));
    }

    #[test]
    fn native_core_traps_are_canonicalized_before_poisoning() {
        let normalizer =
            render_intrinsic_body(Intrinsic::Component(ComponentIntrinsic::NormalizeCoreTrap));
        let state = render_intrinsic_body(Intrinsic::Component(
            ComponentIntrinsic::ComponentAsyncStateClass,
        ));

        assert!(
            normalizer.contains(
                r#"['unreachable', "wasm trap: wasm `unreachable` instruction executed"]"#
            )
        );
        assert!(normalizer.contains("['divide by zero', \"wasm trap: integer divide by zero\"]"));
        assert!(state.contains("err = _normalizeCoreTrap(err);"));
    }

    #[test]
    fn traps_lock_down_only_the_current_component_instance() {
        let state = render_intrinsic_body(Intrinsic::Component(
            ComponentIntrinsic::ComponentAsyncStateClass,
        ));

        assert!(state.contains("#trapped = false;"));
        assert!(state.contains("this.#trapped = true;"));
        assert!(state.contains(
            r#"throw new WebAssemblyRuntimeError("wasm trap: cannot enter component instance");"#
        ));
        assert!(!state.contains("if (STORE_TRAP.error !== null) { throw STORE_TRAP.error; }"));
    }

    #[test]
    fn sync_start_fused_adapter_runs_in_the_caller_task() {
        let source = render_intrinsic_body(Intrinsic::Host(HostIntrinsic::SyncStartCall));

        assert!(source.contains("const callerTask = subtask.getParentTask();"));
        assert!(source.contains("taskID: callerTask.id(),"));
        assert!(source.contains("componentIdx: callerTask.componentIdx(),"));
        assert!(source.contains(
            "fn: () => subtaskCallMeta.returnFn.apply(null, [subtaskCallMeta.resultPtr]),"
        ));
        assert!(source.contains("preparedTask.registerOnResolveHandler(() => {"));
        assert!(source.contains("const calleeLifecyclePromise = (async () => {"));
        assert!(source.contains("await _driverLoop({"));
        assert!(source.contains("await Promise.race(["));
        assert!(source.contains("calleeLifecyclePromise.then(() => taskReturnPromise),"));
        assert!(source.contains("calleeComponentState.markTrapped(err);"));
        assert!(source.contains("preparedTask.exit({ skipExclusiveLockCheck: true });"));
    }

    #[test]
    fn sync_prepare_call_rejects_blocking_from_core_start() {
        let source = render_intrinsic_body(Intrinsic::Host(HostIntrinsic::PrepareCall));

        assert!(source.contains("if (!isAsync && CURRENT_TASK_MAY_BLOCK.value === 0) {"));
        assert!(source.contains(
            "new WebAssemblyRuntimeError('cannot block a synchronous task before returning')"
        ));
        assert!(source.contains(
            "throw new Error('invalid/missing current task for caller during prepare call');"
        ));
    }

    #[test]
    fn symmetric_guest_calls_switch_task_may_block_state() {
        let enter = render_intrinsic_body(Intrinsic::AsyncTask(
            AsyncTaskIntrinsic::EnterSymmetricSyncGuestCall,
        ));
        assert!(!enter.contains("symmetric sync guest->guest call should not be async"));
        assert!(enter.contains("isAsync: false,"));
        assert!(enter.contains("isAsync: !!calleeIsAsync,"));
        assert!(enter.contains("isManualAsync: callerTask.isManualAsync(),"));
        assert!(enter.contains("syncOnly && !calleeIsAsync && cstate.isExclusivelyLocked()"));
        assert!(enter.contains("return 0;"));
        assert!(enter.contains("return 1;"));
        assert!(enter.contains("previousTaskMayBlock: CURRENT_TASK_MAY_BLOCK.value,"));
        assert!(enter.contains("CURRENT_TASK_MAY_BLOCK.value = newTask.mayBlock() ? 1 : 0;"));

        let exit = render_intrinsic_body(Intrinsic::AsyncTask(
            AsyncTaskIntrinsic::ExitSymmetricSyncGuestCall,
        ));
        assert!(exit.contains("const { componentIdx, previousTaskMayBlock }"));
        assert!(exit.contains("CURRENT_TASK_MAY_BLOCK.value = previousTaskMayBlock;"));
    }

    #[test]
    fn resource_transfer_borrow_lends_without_consuming_source() {
        let mut intrinsics = BTreeSet::from([Intrinsic::Resource(
            ResourceIntrinsic::ResourceTransferBorrow,
        )]);
        let opts = TranspileOpts::default();
        let source = render_intrinsics(
            RenderIntrinsicsArgs::builder()
                .intrinsics(&mut intrinsics)
                .transpile_opts(&opts)
                .build(),
        );

        assert!(source.contains("function rscTableGet(table, handle)"));
        assert!(source.contains("const { rep, own } = rscTableGet(fromTable, handle);"));
        assert!(!source.contains("if (!own) rscTableRemove(fromTable, handle);"));
        assert!(source.contains("fromTable[handle << 1]++;"));
        assert!(source.contains("borrowTask.addResourceLender(fromTable, handle);"));
        assert!(source.contains("borrowTask?.resourceScopeId() ?? SCOPE_ID"));
        assert!(source.contains("borrowTask.addBorrowedHandle();"));
    }

    #[test]
    fn resource_drop_updates_the_borrowing_task_scope() {
        let source =
            render_intrinsic_body(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));

        assert!(
            source
                .contains("const borrowTask = own ? undefined : RESOURCE_SCOPE_TASKS.get(scope);")
        );
        assert!(source.contains("borrowTask?.removeBorrowedHandle();"));
        assert!(source.contains(
            "throw new WebAssemblyRuntimeError('cannot remove owned resource while borrowed');"
        ));
    }

    #[test]
    fn tasks_validate_and_release_their_resource_scope() {
        let source =
            render_intrinsic_body(Intrinsic::AsyncTask(AsyncTaskIntrinsic::AsyncTaskClass));

        assert!(source.contains("this.#resourceScopeId = ++RESOURCE_SCOPE_ID;"));
        assert!(source.contains("RESOURCE_SCOPE_TASKS.set(this.#resourceScopeId, this);"));
        assert!(source.contains("addBorrowedHandle()"));
        assert!(source.contains("removeBorrowedHandle()"));
        assert!(source.contains("addResourceLender(table, handle)"));
        assert!(source.contains(
            "throw new WebAssemblyRuntimeError('borrow handles still remain at the end of the call');"
        ));
        assert!(source.contains("table[idx] = lendCount - 1;"));
        assert!(source.contains("RESOURCE_SCOPE_TASKS.delete(this.#resourceScopeId);"));
    }

    /// Future read/write trampoline code references the future end classes
    /// (`instanceof FutureReadableEnd`, `FutureEnd.CopyState`), so the classes
    /// must be emitted even when `FutureNew` is absent (see #1898).
    #[test]
    fn future_read_write_emit_future_end_classes() {
        for (op, end_class) in [
            (AsyncFutureIntrinsic::FutureRead, "class FutureReadableEnd"),
            (AsyncFutureIntrinsic::FutureWrite, "class FutureWritableEnd"),
        ] {
            let mut intrinsics = BTreeSet::from([Intrinsic::AsyncFuture(op)]);
            let opts = TranspileOpts::default();
            let source = render_intrinsics(
                RenderIntrinsicsArgs::builder()
                    .intrinsics(&mut intrinsics)
                    .transpile_opts(&opts)
                    .build(),
            );

            assert!(source.contains(end_class), "missing {end_class}");
            assert!(source.contains("class FutureEnd"), "missing FutureEnd");
        }
    }

    #[test]
    fn future_new_allocates_the_readable_end_first() {
        let source =
            render_intrinsic_body(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::CreateFuture));
        let read = source.find("const readEnd = future.readEnd();").unwrap();
        let write = source.find("const writeEnd = future.writeEnd();").unwrap();

        assert!(read < write);
    }

    #[test]
    fn future_writer_preserves_component_identity_when_blocked() {
        let writer = render_intrinsic_body(Intrinsic::AsyncFuture(
            AsyncFutureIntrinsic::FutureWritableEndClass,
        ));
        let pending_meta = writer
            .split_once("this.setPendingBufferMeta({")
            .and_then(|(_, rest)| rest.split_once("});"))
            .map(|(args, _)| args)
            .expect("writer should save a blocked operation");
        assert!(pending_meta.contains("componentIdx,"));
    }

    #[test]
    fn future_ends_use_canonical_intra_component_copy_trap() {
        let error = "throw new WebAssemblyRuntimeError('cannot read from and write to intra-component future');";

        for end in [
            AsyncFutureIntrinsic::FutureReadableEndClass,
            AsyncFutureIntrinsic::FutureWritableEndClass,
        ] {
            let source = render_intrinsic_body(Intrinsic::AsyncFuture(end));
            assert!(source.contains(error));
            assert!(source.contains("componentIdx === meta.componentIdx"));
        }
    }

    #[test]
    fn stream_new_allocates_the_readable_end_first() {
        let source =
            render_intrinsic_body(Intrinsic::AsyncStream(AsyncStreamIntrinsic::CreateStream));
        let read = source.find("const readEnd = stream.readEnd();").unwrap();
        let write = source.find("const writeEnd = stream.writeEnd();").unwrap();

        assert!(read < write);
    }

    #[test]
    fn future_operations_only_suspend_for_sync_canonical_calls() {
        for op in [
            AsyncFutureIntrinsic::FutureRead,
            AsyncFutureIntrinsic::FutureWrite,
        ] {
            let source = render_intrinsic_body(Intrinsic::AsyncFuture(op));

            assert!(source.contains(&format!("function {}(", op.name())));
            assert!(!source.contains(&format!("async function {}(", op.name())));
            assert!(source.contains("if (isAsync) {"));
            assert!(source.contains("return task.suspendUntil({"));
        }
    }

    #[test]
    fn stream_operations_only_suspend_for_sync_canonical_calls() {
        for op in [
            AsyncStreamIntrinsic::StreamRead,
            AsyncStreamIntrinsic::StreamWrite,
        ] {
            let source = render_intrinsic_body(Intrinsic::AsyncStream(op));

            assert!(source.contains(&format!("function {}(", op.name())));
            assert!(!source.contains(&format!("async function {}(", op.name())));
        }

        for end in [
            AsyncStreamIntrinsic::StreamReadableEndClass,
            AsyncStreamIntrinsic::StreamWritableEndClass,
        ] {
            let source = render_intrinsic_body(Intrinsic::AsyncStream(end));
            assert!(source.contains("copy(args) {"));
            assert!(!source.contains("async copy(args) {"));
            assert!(source.contains("if (isAsync) {"));
            assert!(source.contains("return task.suspendUntil({"));
        }
    }

    #[test]
    fn stream_drop_rejects_busy_ends_before_table_removal() {
        for (intrinsic, error) in [
            (
                AsyncStreamIntrinsic::StreamDropReadable,
                "cannot remove busy stream",
            ),
            (
                AsyncStreamIntrinsic::StreamDropWritable,
                "cannot drop busy stream",
            ),
        ] {
            let source = render_intrinsic_body(Intrinsic::AsyncStream(intrinsic));
            let busy_check = source
                .find("if (streamEnd.isCopying() || streamEnd.hasPendingEvent()) {")
                .expect("stream drop should reject an active or undelivered copy");
            let removal = source
                .find("const removedStreamEnd = deleteStreamEnd(")
                .expect("stream drop should remove a validated idle end");

            assert!(source.contains(&format!("throw new WebAssemblyRuntimeError('{error}');")));
            assert!(busy_check < removal, "busy validation must precede removal");
            assert!(source.contains("if (removedStreamEnd !== streamEnd) {"));
        }
    }

    #[test]
    fn future_and_stream_terminal_states_use_canonical_traps() {
        for (intrinsic, message) in [
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureWrite),
                "cannot write to future after previous write succeeded or readable end dropped",
            ),
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureRead),
                "cannot read from future after previous read succeeded",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamWrite),
                "cannot write to stream after being notified that the readable end dropped",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamRead),
                "cannot read from stream after being notified that the writable end dropped",
            ),
        ] {
            let source = render_intrinsic_body(intrinsic);
            assert!(
                source.contains("if (futureEnd.isDoneState()) {")
                    || source.contains("if (streamEnd.isDoneState()) {")
            );
            assert!(source.contains(message));
            assert!(source.contains("throw new WebAssemblyRuntimeError(message);"));
        }

        for (intrinsic, get, remove, message) in [
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureTransfer),
                "const futureEnd = getFutureEnd(",
                "const removedFutureEnd = removeFutureEndFromTable(",
                "cannot lift future after previous read succeeded",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamTransfer),
                "const streamEnd = getStreamEnd(",
                "const removedStreamEnd = removeStreamEndFromTable(",
                "cannot lift stream after being notified that the writable end dropped",
            ),
        ] {
            let source = render_intrinsic_body(intrinsic);
            let get = source.find(get).expect("terminal validation lookup");
            let remove = source.find(remove).expect("validated endpoint removal");
            assert!(get < remove);
            assert!(source.contains(message));
        }

        for (intrinsic, message) in [
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::HostFutureClass),
                "cannot lift future after previous read succeeded",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::HostStreamClass),
                "cannot lift stream after being notified that the writable end dropped",
            ),
            (
                Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture),
                "cannot lift future after previous read succeeded",
            ),
            (
                Intrinsic::Lift(LiftIntrinsic::LiftFlatStream),
                "cannot lift stream after being notified that the writable end dropped",
            ),
        ] {
            let source = render_intrinsic_body(intrinsic);
            assert!(source.contains("End.isDoneState()) {"));
            assert!(source.contains(message));
        }
    }

    #[test]
    fn future_and_stream_waitable_membership_traps_before_transfer() {
        for (intrinsic, check, remove, message) in [
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureTransfer),
                "if (futureEnd.isInSet()) {",
                "const removedFutureEnd = removeFutureEndFromTable(",
                "cannot lift future while it's in a waitable set",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamTransfer),
                "if (streamEnd.isInSet()) {",
                "const removedStreamEnd = removeStreamEndFromTable(",
                "cannot lift stream while it's in a waitable set",
            ),
        ] {
            let source = render_intrinsic_body(intrinsic);
            let check = source.find(check).expect("waitable membership check");
            let remove = source.find(remove).expect("endpoint table removal");

            assert!(check < remove, "membership validation must precede removal");
            assert!(source.contains(&format!(
                "throw new WebAssemblyRuntimeError(\"{message}\");"
            )));
        }

        for (intrinsic, message) in [
            (
                Intrinsic::AsyncFuture(AsyncFutureIntrinsic::HostFutureClass),
                "cannot lift future while it's in a waitable set",
            ),
            (
                Intrinsic::AsyncStream(AsyncStreamIntrinsic::HostStreamClass),
                "cannot lift stream while it's in a waitable set",
            ),
            (
                Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture),
                "cannot lift future while it's in a waitable set",
            ),
            (
                Intrinsic::Lift(LiftIntrinsic::LiftFlatStream),
                "cannot lift stream while it's in a waitable set",
            ),
        ] {
            let source = render_intrinsic_body(intrinsic);
            assert!(source.contains(&format!("\"{message}\"")));
            assert!(!source.contains("in waitable sets cannot be lifted"));
        }
    }

    #[test]
    fn future_ends_track_own_and_peer_drop_state_separately() {
        let mut intrinsics = BTreeSet::from([Intrinsic::AsyncFuture(
            AsyncFutureIntrinsic::InternalFutureClass,
        )]);
        let opts = TranspileOpts::default();
        let source = render_intrinsics(
            RenderIntrinsicsArgs::builder()
                .intrinsics(&mut intrinsics)
                .transpile_opts(&opts)
                .build(),
        );

        assert!(source.contains("#dropped = false;"));
        assert!(source.contains("isDropped() { return this.#dropped; }"));
        assert!(source.contains("isPeerDropped() { return this.#isPeerDroppedFn(); }"));
        assert!(source.contains("isPeerDroppedFn: () => this.#writeEnd?.isDropped() ?? false,"));
        assert!(source.contains("isPeerDroppedFn: () => this.#readEnd.isDropped(),"));
        assert!(source.contains("if (this.isPeerDropped()) {"));
    }

    #[test]
    fn flat_flags_bigint_representation_is_opt_in() {
        fn render(flags_as_bigint: bool) -> Source {
            let mut intrinsics = BTreeSet::from([
                Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags),
                Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags),
            ]);
            let opts = TranspileOpts::builder()
                .name("test".into())
                .flags_as_bigint(flags_as_bigint)
                .build();
            render_intrinsics(
                RenderIntrinsicsArgs::builder()
                    .intrinsics(&mut intrinsics)
                    .transpile_opts(&opts)
                    .build(),
            )
        }

        let default_source = render(false);
        assert!(default_source.contains("val[name] = (bits & 1) === 1;"));
        assert!(default_source.contains("const flagObj = ctx.vals[0];"));
        assert!(!default_source.contains("val = BigInt(bits >>> 0);"));

        let bigint_source = render(true);
        assert!(bigint_source.contains("val = BigInt(bits >>> 0);"));
        assert!(bigint_source.contains("typeof bigintFlags !== 'bigint'"));
        assert!(!bigint_source.contains("const flagObj = ctx.vals[0];"));
    }
}

/// Profile for determinism to be used by async implementation
#[derive(Debug, Default, PartialEq, Eq)]
pub enum AsyncDeterminismProfile {
    /// Allow random ordering non-determinism
    #[default]
    Random,

    /// Require determinism
    #[allow(unused)]
    Deterministic,
}

impl std::fmt::Display for AsyncDeterminismProfile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Deterministic => "deterministic",
                Self::Random => "random",
            }
        )
    }
}

/// Arguments to `render_intrinsics`
#[derive(bon::Builder)]
#[non_exhaustive]
pub struct RenderIntrinsicsArgs<'a> {
    /// List of intrinsics being built for use
    pub(crate) intrinsics: &'a mut BTreeSet<Intrinsic>,
    /// Whether instantiation has occurred
    #[builder(default)]
    pub(crate) instantiation_occurred: bool,
    /// The kind of determinism to use
    #[builder(default)]
    pub(crate) determinism_profile: AsyncDeterminismProfile,
    /// Options provided when performing transpilation
    pub(crate) transpile_opts: &'a TranspileOpts,
    /// Intrinsic dependencies discovered while rendering one intrinsic
    #[builder(default)]
    discovered_intrinsics: Mutex<BTreeSet<Intrinsic>>,
}

impl RenderIntrinsicsArgs<'_> {
    /// Retrieve an intrinsic's name and register it as a dependency of the
    /// intrinsic currently being rendered.
    pub fn require_intrinsic(&self, intrinsic: impl Into<Intrinsic>) -> &'static str {
        let intrinsic = intrinsic.into();
        self.discovered_intrinsics
            .lock()
            .expect("intrinsic dependency collector lock should not be poisoned")
            .insert(intrinsic);
        intrinsic.name()
    }

    fn take_discovered_intrinsics(&self) -> BTreeSet<Intrinsic> {
        std::mem::take(
            &mut *self
                .discovered_intrinsics
                .lock()
                .expect("intrinsic dependency collector lock should not be poisoned"),
        )
    }
}

/// Emits the intrinsic `i` to this file and then returns the name of the
/// intrinsic.
pub fn render_intrinsics(mut args: RenderIntrinsicsArgs) -> Source {
    render_intrinsics_discovered(&mut args)
}

fn render_intrinsics_discovered(args: &mut RenderIntrinsicsArgs<'_>) -> Source {
    let mut pending = args.intrinsics.clone();
    let mut rendered = BTreeMap::new();
    let mut dependencies = BTreeMap::new();

    while let Some(intrinsic) = pending.pop_first() {
        if rendered.contains_key(&intrinsic) {
            continue;
        }

        debug_assert!(args.take_discovered_intrinsics().is_empty());
        let mut source = Source::default();
        intrinsic.render(&mut source, args);
        let discovered = args.take_discovered_intrinsics();
        for dependency in &discovered {
            if !rendered.contains_key(dependency) {
                pending.insert(*dependency);
            }
            args.intrinsics.insert(*dependency);
        }
        dependencies.insert(intrinsic, discovered);
        rendered.insert(intrinsic, source);
    }

    let mut output = Source::default();
    if args
        .intrinsics
        .contains(&Intrinsic::Conversion(ConversionIntrinsic::F32ToI32))
        || args
            .intrinsics
            .contains(&Intrinsic::Conversion(ConversionIntrinsic::I32ToF32))
    {
        output.push_str(
            "
            const i32ToF32I = new Int32Array(1);
            const i32ToF32F = new Float32Array(i32ToF32I.buffer);
        ",
        );
    }

    if args
        .intrinsics
        .contains(&Intrinsic::Conversion(ConversionIntrinsic::F64ToI64))
        || args
            .intrinsics
            .contains(&Intrinsic::Conversion(ConversionIntrinsic::I64ToF64))
    {
        output.push_str(
            "
            const i64ToF64I = new BigInt64Array(1);
            const i64ToF64F = new Float64Array(i64ToF64I.buffer);
        ",
        );
    }

    let mut visiting = BTreeSet::new();
    let mut emitted = BTreeSet::new();
    for intrinsic in args.intrinsics.iter().copied() {
        emit_intrinsic(
            intrinsic,
            &dependencies,
            &rendered,
            &mut visiting,
            &mut emitted,
            &mut output,
        );
    }
    output
}

fn emit_intrinsic(
    intrinsic: Intrinsic,
    dependencies: &BTreeMap<Intrinsic, BTreeSet<Intrinsic>>,
    rendered: &BTreeMap<Intrinsic, Source>,
    visiting: &mut BTreeSet<Intrinsic>,
    emitted: &mut BTreeSet<Intrinsic>,
    output: &mut Source,
) {
    if emitted.contains(&intrinsic) || !visiting.insert(intrinsic) {
        return;
    }

    if let Some(intrinsic_dependencies) = dependencies.get(&intrinsic) {
        for dependency in intrinsic_dependencies {
            emit_intrinsic(
                *dependency,
                dependencies,
                rendered,
                visiting,
                emitted,
                output,
            );
        }
    }

    visiting.remove(&intrinsic);
    if emitted.insert(intrinsic) {
        output.push_str(
            rendered
                .get(&intrinsic)
                .expect("intrinsic should have been rendered"),
        );
    }
}

impl Intrinsic {
    pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
        JsHelperIntrinsic::get_global_names()
            .into_iter()
            .chain(vec![
                // Intrinsic list exactly as below
                "base64Compile",
                "clampGuest",
                "ComponentError",
                "WebAssemblyRuntimeError",
                "FACT_TRAP_MESSAGES",
                "fetchCompile",
                "finalizationRegistryCreate",
                "getErrorPayload",
                "HANDLE_TABLES",
                "hasOwnProperty",
                "imports",
                "instantiateCore",
                "isLE",
                "scopeId",
                "symbolCabiDispose",
                "symbolCabiLower",
                "symbolDispose",
                "symbolAsyncIterator",
                "symbolIterator",
                "symbolRscHandle",
                "symbolRscRep",
                "T_FLAG",
                "throwInvalidBool",
                "throwUninitialized",
                // JS Globals / non intrinsic names
                "ArrayBuffer",
                "BigInt",
                "BigInt64Array",
                "DataView",
                "dv",
                "emptyFunc",
                "Error",
                "fetch",
                "Float32Array",
                "Float64Array",
                "Int32Array",
                "Object",
                "process",
                "String",
                "TextDecoder",
                "TextEncoder",
                "TypeError",
                "Uint16Array",
                "Uint8Array",
                "URL",
                "WebAssembly",
                "GlobalComponentMemories",
            ])
    }

    pub fn name(&self) -> &'static str {
        match self {
            Intrinsic::JsHelper(i) => i.name(),
            Intrinsic::Conversion(i) => i.name(),
            Intrinsic::WebIdl(i) => i.name(),
            Intrinsic::String(i) => i.name(),
            Intrinsic::ErrCtx(i) => i.name(),
            Intrinsic::AsyncTask(i) => i.name(),
            Intrinsic::Waitable(i) => i.name(),
            Intrinsic::Resource(i) => i.name(),
            Intrinsic::Lift(i) => i.name(),
            Intrinsic::Lower(i) => i.name(),
            Intrinsic::AsyncStream(i) => i.name(),
            Intrinsic::AsyncFuture(i) => i.name(),
            Intrinsic::Component(i) => i.name(),
            Intrinsic::Host(i) => i.name(),

            Intrinsic::Base64Compile => "base64Compile",
            Intrinsic::ClampGuest => "clampGuest",
            Intrinsic::ComponentError => "ComponentError",
            Intrinsic::WebAssemblyRuntimeError => "WebAssemblyRuntimeError",
            Intrinsic::FactTrapMessages => "FACT_TRAP_MESSAGES",
            Intrinsic::FetchCompile => "fetchCompile",
            Intrinsic::FinalizationRegistryCreate => "finalizationRegistryCreate",
            Intrinsic::GetErrorPayload => "getErrorPayload",
            Intrinsic::GetErrorPayloadString => "getErrorPayloadString",
            Intrinsic::HandleTables => "HANDLE_TABLES",
            Intrinsic::HasOwnProperty => "hasOwnProperty",
            Intrinsic::InstantiateCore => "instantiateCore",
            Intrinsic::IsLE => "isLE",
            Intrinsic::ScopeId => "SCOPE_ID",

            Intrinsic::SymbolCabiDispose => "symbolCabiDispose",
            Intrinsic::SymbolCabiLower => "symbolCabiLower",
            Intrinsic::SymbolDispose => "symbolDispose",
            Intrinsic::SymbolAsyncIterator => "symbolAsyncIterator",
            Intrinsic::SymbolIterator => "symbolIterator",
            Intrinsic::SymbolResourceHandle => "symbolRscHandle",
            Intrinsic::SymbolResourceRep => "symbolRscRep",

            Intrinsic::ThrowInvalidBool => "throwInvalidBool",
            Intrinsic::ThrowUninitialized => "throwUninitialized",

            // Debugging
            Intrinsic::DebugLog => "_debugLog",
            Intrinsic::PromiseWithResolversPonyfill => "promiseWithResolvers",

            // Types
            Intrinsic::ConstantI32Min => "I32_MIN",
            Intrinsic::ConstantI32Max => "I32_MAX",
            Intrinsic::TypeCheckValidI32 => "_typeCheckValidI32",
            Intrinsic::TypeCheckAsyncFn => "_typeCheckAsyncFn",
            Intrinsic::AsyncFunctionCtor => "ASYNC_FN_CTOR",

            // Streams
            Intrinsic::PlatformReadableStreamClass => "_PlatformReadableStream",

            // Async
            Intrinsic::GlobalAsyncDeterminism => "ASYNC_DETERMINISM",
            Intrinsic::CoinFlip => "_coinFlip",

            // Global current task tracking machinery
            Self::GlobalCurrentTaskMeta => "CURRENT_TASK_META",
            Self::GetGlobalCurrentTaskMetaFn => "_getGlobalCurrentTaskMeta",
            Self::SetGlobalCurrentTaskMetaFn => "_setGlobalCurrentTaskMeta",
            Self::WithGlobalCurrentTaskMetaFn => "_withGlobalCurrentTaskMeta",
            Self::WithGlobalCurrentTaskMetaFnAsync => "_withGlobalCurrentTaskMetaAsync",
            Self::ClearGlobalCurrentTaskMetaFn => "_clearCurrentTask",
            Self::SuspendingImportWrapperFn => "_suspendingImport",
            Self::ConditionalSuspending1I32ToI32Fn => "_conditionalSuspending1I32ToI32",
            Self::ConditionalSuspending2I32ToI32Fn => "_conditionalSuspending2I32ToI32",
            Self::ConditionalSuspending3I32ToVoidFn => "_conditionalSuspending3I32ToVoid",

            // Iteratively saved metadata
            Intrinsic::GlobalComponentMemoryMap => "GLOBAL_COMPONENT_MEMORY_MAP",
            Intrinsic::RegisterGlobalMemoryForComponent => "registerGlobalMemoryForComponent",
            Intrinsic::LookupMemoriesForComponent => "lookupMemoriesForComponent",

            // Data structures
            Intrinsic::RepTableClass => "RepTable",

            // Buffers for managed/synchronized writing to/from component memory
            Intrinsic::ManagedBufferClass => "ManagedBuffer",
            Intrinsic::BufferManagerClass => "BufferManager",
            Intrinsic::GlobalBufferManager => "BUFFER_MGR",

            // Helpers for working with async state
            Intrinsic::AsyncEventCodeEnum => "ASYNC_EVENT_CODE",
        }
    }
}