js-component-bindgen 1.17.0

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
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::Write;
use std::mem;
use std::ops::Index;

use base64::Engine as _;
use base64::engine::general_purpose;
use heck::{ToKebabCase, ToLowerCamelCase, ToUpperCamelCase};
use semver::Version;
use wasmtime_environ::component::{
    CanonicalOptions, CanonicalOptionsDataModel, Component, ComponentTranslation, ComponentTypes,
    CoreDef, CoreExport, Export, ExportItem, FixedEncoding, GlobalInitializer, InstantiateModule,
    InterfaceType, LinearMemoryOptions, LoweredIndex, ResourceIndex, RuntimeComponentInstanceIndex,
    RuntimeImportIndex, RuntimeInstanceIndex, StaticModuleIndex, Trampoline, TrampolineIndex,
    TypeDef, TypeFuncIndex, TypeFutureTableIndex, TypeResourceTableIndex, TypeStreamTableIndex,
};
use wasmtime_environ::component::{
    ExtractCallback, NameMapNoIntern, Transcode, TypeComponentLocalErrorContextTableIndex,
};
use wasmtime_environ::{EntityIndex, PrimaryMap};
use wit_bindgen_core::abi::{self, LiftLower};
use wit_component::StringEncoding;
use wit_parser::abi::AbiVariant;
use wit_parser::{
    Function, FunctionKind, Handle, Resolve, Result_, SizeAlign, Type, TypeDefKind, TypeId,
    WorldId, WorldItem, WorldKey,
};

use crate::esm_bindgen::EsmBindgen;
use crate::files::Files;
use crate::function_bindgen::{
    ErrHandling, FunctionBindgen, PayloadTypeMetadata, ResourceData, ResourceExtraData,
    ResourceMap, ResourceTable,
};
use crate::intrinsics::component::ComponentIntrinsic;
use crate::intrinsics::js_helper::JsHelperIntrinsic;
use crate::intrinsics::lift::LiftIntrinsic;
use crate::intrinsics::lower::LowerIntrinsic;
use crate::intrinsics::p3::async_future::AsyncFutureIntrinsic;
use crate::intrinsics::p3::async_stream::AsyncStreamIntrinsic;
use crate::intrinsics::p3::async_task::AsyncTaskIntrinsic;
use crate::intrinsics::p3::error_context::ErrCtxIntrinsic;
use crate::intrinsics::p3::host::HostIntrinsic;
use crate::intrinsics::p3::waitable::WaitableIntrinsic;
use crate::intrinsics::resource::ResourceIntrinsic;
use crate::intrinsics::string::StringIntrinsic;
use crate::intrinsics::webidl::WebIdlIntrinsic;
use crate::intrinsics::{
    AsyncDeterminismProfile, Intrinsic, RenderIntrinsicsArgs, render_intrinsics,
};
use crate::names::{LocalNames, is_js_reserved_word, maybe_quote_id, maybe_quote_member};
use crate::{
    FunctionIdentifier, ManagesIntrinsics, core, get_thrown_type, is_async_fn,
    requires_async_porcelain, source, uwrite, uwriteln,
};

/// Number of flat parameters allowed before spilling over to memory
/// for an async function
///
/// See [`wit-bindgen-core`] and the Component Model spec
const MAX_ASYNC_FLAT_PARAMS: usize = 4;

#[derive(Debug, Default, Clone)]
pub struct TranspileOpts {
    pub name: String,
    /// Disables generation of `*.d.ts` files and instead only generates `*.js`
    /// source files.
    pub no_typescript: bool,
    /// Provide a custom JS instantiation API for the component instead
    /// of the direct importable native ESM output.
    pub instantiation: Option<InstantiationMode>,
    /// Configure how import bindings are provided, as high-level JS bindings,
    /// or as hybrid optimized bindings.
    pub import_bindings: Option<BindingsMode>,
    /// Comma-separated list of "from-specifier=./to-specifier.js" mappings of
    /// component import specifiers to JS import specifiers.
    pub map: Option<HashMap<String, String>>,
    /// Disables compatibility in Node.js without a fetch global.
    pub no_nodejs_compat: bool,
    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode
    /// (set to 0 to disable all base64 inlining)
    pub base64_cutoff: usize,
    /// Enables compatibility for JS environments without top-level await support
    /// via an async $init promise export to wait for instead.
    pub tla_compat: bool,
    /// Disable verification of component Wasm data structures when
    /// lifting as a production optimization
    pub valid_lifting_optimization: bool,
    /// Whether or not to emit `tracing` calls on function entry/exit.
    pub tracing: bool,
    /// Whether to generate namespaced exports like `foo as "local:package/foo"`.
    /// These exports can break typescript builds.
    pub no_namespaced_exports: bool,
    /// Whether to output core Wasm utilizing multi-memory or to polyfill
    /// this handling.
    pub multi_memory: bool,
    /// Whether to generate types for a guest module using module declarations.
    pub guest: bool,
    /// Configure whether to use `async` imports or exports with
    /// JavaScript Promise Integration (JSPI).
    pub async_mode: Option<AsyncMode>,
    /// Configure whether to generate code that includes strict type checks
    pub strict: bool,
    /// Whether the core module(s) to be wrapped were actually transpiled from Wasm to JS (asm.js) and thus need shimming for i64
    pub asmjs: bool,
}

#[derive(Default, Clone, Debug)]
pub enum AsyncMode {
    #[default]
    Sync,
    JavaScriptPromiseIntegration {
        imports: Vec<String>,
        exports: Vec<String>,
    },
}

#[derive(Default, Clone, Debug)]
pub enum InstantiationMode {
    #[default]
    Async,
    Sync,
}

/// Internal Bindgen calling convention
enum CallType {
    /// Standard calls - inner function is called directly with parameters
    Standard,
    /// Standard calls that are async (p3)
    AsyncStandard,
    /// Exported resource method calls - this is passed as the first argument
    FirstArgIsThis,
    /// Exported resource method calls that are async (p3)
    AsyncFirstArgIsThis,
    /// Imported resource method calls - callee is a member of the parameter
    CalleeResourceDispatch,
    /// Imported resource method calls that are async (p3)
    AsyncCalleeResourceDispatch,
}

#[derive(Default, Clone, Debug)]
pub enum BindingsMode {
    Hybrid,
    #[default]
    Js,
    Optimized,
    DirectOptimized,
}

struct JsBindgen<'a> {
    local_names: LocalNames,

    esm_bindgen: EsmBindgen,

    /// The source code for the "main" file that's going to be created for the
    /// component we're generating bindings for. This is incrementally added to
    /// over time and primarily contains the main `instantiate` function as well
    /// as a type-description of the input/output interfaces.
    src: Source,

    /// Core module count
    core_module_cnt: usize,

    /// Various options for code generation.
    opts: &'a TranspileOpts,

    /// List of all intrinsics emitted to `src` so far.
    all_intrinsics: BTreeSet<Intrinsic>,

    /// List of all core Wasm exported functions (and if is async) referenced in
    /// `src` so far.
    ///
    /// The second boolean is true when async procelain is required *or* if the
    /// export itself is async.
    all_core_exported_funcs: Vec<(String, bool)>,
}

/// Arguments provided to `JSBindgen::bindgen`, normally called to perform bindgen on a given function
struct JsFunctionBindgenArgs<'a> {
    /// Number of params that the function expects
    nparams: usize,
    /// Internal convention for function calls (ex. whether the first argument is known to be 'this')
    call_type: CallType,
    /// Interface name (if inside an interface)
    iface_name: Option<&'a str>,
    /// Callee of the function
    callee: &'a str,
    /// Canon opts provided for the functions
    opts: &'a CanonicalOptions,
    /// Parsed function metadata
    func: &'a Function,
    resource_map: &'a ResourceMap,
    /// ABI variant of the function
    abi: AbiVariant,
    /// Whether the function in question is a host async function (i.e. JSPI)
    requires_async_porcelain: bool,
    /// Whether the function in question is a guest async function (i.e. WASI P3)
    is_async: bool,
}

impl<'a> ManagesIntrinsics for JsBindgen<'a> {
    fn add_intrinsic(&mut self, intrinsic: Intrinsic) {
        self.intrinsic(intrinsic);
    }
}

#[allow(clippy::too_many_arguments)]
pub fn transpile_bindgen(
    name: &str,
    component: &ComponentTranslation,
    modules: &PrimaryMap<StaticModuleIndex, core::Translation<'_>>,
    types: &ComponentTypes,
    resolve: &Resolve,
    id: WorldId,
    opts: TranspileOpts,
    files: &mut Files,
) -> (Vec<String>, Vec<(String, Export)>) {
    let (async_imports, async_exports) = match opts.async_mode.clone() {
        None | Some(AsyncMode::Sync) => (Default::default(), Default::default()),
        Some(AsyncMode::JavaScriptPromiseIntegration { imports, exports }) => {
            (imports.into_iter().collect(), exports.into_iter().collect())
        }
    };

    let mut bindgen = JsBindgen {
        local_names: LocalNames::default(),
        src: Source::default(),
        esm_bindgen: EsmBindgen::default(),
        core_module_cnt: 0,
        opts: &opts,
        all_intrinsics: BTreeSet::new(),
        all_core_exported_funcs: Vec::new(),
    };
    bindgen.local_names.exclude_globals(
        &Intrinsic::get_global_names()
            .into_iter()
            .collect::<Vec<_>>(),
    );
    bindgen.core_module_cnt = modules.len();

    // Generate mapping of stream tables to components that are related
    let mut stream_tables = BTreeMap::new();
    for idx in 0..component.component.num_stream_tables {
        let stream_table_idx = TypeStreamTableIndex::from_u32(idx as u32);
        let stream_table_ty = &types[stream_table_idx];
        stream_tables.insert(stream_table_idx, stream_table_ty.instance);
    }

    // Generate mapping of future tables to components that are related
    let mut future_tables = BTreeMap::new();
    for idx in 0..component.component.num_future_tables {
        let future_table_idx = TypeFutureTableIndex::from_u32(idx as u32);
        let future_table_ty = &types[future_table_idx];
        future_tables.insert(future_table_idx, future_table_ty.instance);
    }

    // Generate mapping of err_ctx tables to components that are related
    let mut err_ctx_tables = BTreeMap::new();
    for idx in 0..component.component.num_error_context_tables {
        let err_ctx_table_idx = TypeComponentLocalErrorContextTableIndex::from_u32(idx as u32);
        let err_ctx_table_ty = &types[err_ctx_table_idx];
        err_ctx_tables.insert(err_ctx_table_idx, err_ctx_table_ty.instance);
    }

    // Bindings are generated when the `instantiate` method is called on the
    // Instantiator structure created below
    let mut instantiator = Instantiator {
        src: Source::default(),
        sizes: SizeAlign::default(),
        bindgen: &mut bindgen,
        modules,
        instances: Default::default(),
        error_context_component_initialized: (0..component
            .component
            .num_runtime_component_instances)
            .map(|_| false)
            .collect(),
        error_context_component_table_initialized: (0..component
            .component
            .num_error_context_tables)
            .map(|_| false)
            .collect(),
        resolve,
        world: id,
        translation: component,
        component: &component.component,
        types,
        async_imports,
        async_exports,
        imports: Default::default(),
        exports: Default::default(),
        lowering_options: Default::default(),
        used_instance_flags: Default::default(),
        defined_resource_classes: Default::default(),
        imports_resource_types: Default::default(),
        imports_resource_index_types: Default::default(),
        exports_resource_types: Default::default(),
        exports_resource_index_types: Default::default(),
        resource_exports: Default::default(),
        resource_imports: Default::default(),
        resources_initialized: BTreeMap::new(),
        resource_tables_initialized: BTreeMap::new(),
        stream_tables,
        future_tables,
        err_ctx_tables,
    };
    instantiator.sizes.fill(resolve);
    instantiator.initialize();
    instantiator.instantiate();

    let mut intrinsic_definitions = source::Source::default();

    instantiator.resource_definitions(&mut intrinsic_definitions);
    instantiator.instance_flags();

    instantiator.bindgen.src.js(&instantiator.src.js);
    instantiator.bindgen.src.js_init(&instantiator.src.js_init);

    instantiator
        .bindgen
        .finish_component(name, files, &opts, intrinsic_definitions);

    let exports = instantiator
        .bindgen
        .esm_bindgen
        .exports()
        .iter()
        .map(|(export_name, canon_export_name)| {
            let expected_export_name =
                if canon_export_name.contains(':') || canon_export_name.starts_with("[async]") {
                    canon_export_name.to_string()
                } else {
                    canon_export_name.to_kebab_case()
                };
            let export = instantiator
                .component
                .exports
                .get(&expected_export_name, &NameMapNoIntern)
                .unwrap_or_else(|| panic!("failed to find component export [{expected_export_name}] (original '{canon_export_name}')"));
            (
                export_name.to_string(),
                instantiator.component.export_items[*export].clone(),
            )
        })
        .collect();

    (bindgen.esm_bindgen.import_specifiers(), exports)
}

impl JsBindgen<'_> {
    fn finish_component(
        &mut self,
        name: &str,
        files: &mut Files,
        opts: &TranspileOpts,
        intrinsic_definitions: source::Source,
    ) {
        let mut output = source::Source::default();
        let mut compilation_promises = source::Source::default();
        let mut core_exported_funcs = source::Source::default();

        for (core_export_fn, is_async) in self.all_core_exported_funcs.iter() {
            let local_name = self.local_names.get(core_export_fn);
            if *is_async {
                uwriteln!(
                    core_exported_funcs,
                    "{local_name} = WebAssembly.promising({core_export_fn});",
                );
            } else {
                uwriteln!(core_exported_funcs, "{local_name} = {core_export_fn};",);
            }
        }

        // adds a default implementation of `getCoreModule`
        if matches!(self.opts.instantiation, Some(InstantiationMode::Async)) {
            uwriteln!(
                compilation_promises,
                "if (!getCoreModule) getCoreModule = (name) => {}(new URL(`./${{name}}`, import.meta.url));",
                self.intrinsic(Intrinsic::FetchCompile)
            );
        }

        // Setup the compilation data and compilation promises
        let mut removed = BTreeSet::new();
        for i in 0..self.core_module_cnt {
            let local_name = format!("module{i}");
            let mut name_idx = core_file_name(name, i as u32);
            if self.opts.instantiation.is_some() {
                uwriteln!(
                    compilation_promises,
                    "const {local_name} = getCoreModule('{name_idx}');"
                );
            } else if files.get_size(&name_idx).unwrap() < self.opts.base64_cutoff {
                assert!(removed.insert(i));
                let data = files.remove(&name_idx).unwrap();
                uwriteln!(
                    compilation_promises,
                    "const {local_name} = {}('{}');",
                    self.intrinsic(Intrinsic::Base64Compile),
                    general_purpose::STANDARD_NO_PAD.encode(&data),
                );
            } else {
                // Maintain numerical file orderings when a previous file was
                // inlined
                if let Some(&replacement) = removed.iter().next() {
                    assert!(removed.remove(&replacement) && removed.insert(i));
                    let data = files.remove(&name_idx).unwrap();
                    name_idx = core_file_name(name, replacement as u32);
                    files.push(&name_idx, &data);
                }
                uwriteln!(
                    compilation_promises,
                    "const {local_name} = {}(new URL('./{name_idx}', import.meta.url));",
                    self.intrinsic(Intrinsic::FetchCompile)
                );
            }
        }

        // Render the telemery directive
        uwriteln!(output, r#""use components";"#);

        let js_intrinsics = render_intrinsics(RenderIntrinsicsArgs {
            intrinsics: &mut self.all_intrinsics,
            no_nodejs_compat: self.opts.no_nodejs_compat,
            instantiation: self.opts.instantiation.is_some(),
            determinism: AsyncDeterminismProfile::default(),
            transpile_opts: opts,
        });

        if let Some(instantiation) = &self.opts.instantiation {
            uwrite!(
                output,
                "\
                    export function instantiate(getCoreModule, imports, instantiateCore = {}) {{
                        {}
                        {}
                        {}
                ",
                match instantiation {
                    InstantiationMode::Async => "WebAssembly.instantiate",
                    InstantiationMode::Sync =>
                        "(module, importObject) => new WebAssembly.Instance(module, importObject)",
                },
                &js_intrinsics as &str,
                &intrinsic_definitions as &str,
                &compilation_promises as &str,
            );
        }

        // Render all imports
        let imports_object = if self.opts.instantiation.is_some() {
            Some("imports")
        } else {
            None
        };
        self.esm_bindgen
            .render_imports(&mut output, imports_object, &mut self.local_names);

        // Create instantiation code
        if self.opts.instantiation.is_some() {
            uwrite!(&mut self.src.js, "{}", &core_exported_funcs as &str);
            self.esm_bindgen.render_exports(
                &mut self.src.js,
                self.opts.instantiation.is_some(),
                &mut self.local_names,
                opts,
            );
            uwrite!(
                output,
                "\
                        let gen = (function* _initGenerator () {{
                            {}\
                            {};
                        }})();
                        let promise, resolve, reject;
                        function runNext (value) {{
                            try {{
                                let done;
                                do {{
                                    ({{ value, done }} = gen.next(value));
                                }} while (!(value instanceof Promise) && !done);
                                if (done) {{
                                    if (resolve) return resolve(value);
                                    else return value;
                                }}
                                if (!promise) promise = new Promise((_resolve, _reject) => (resolve = _resolve, reject = _reject));
                                value.then(nextVal => done ? resolve() : runNext(nextVal), reject);
                            }}
                            catch (e) {{
                                if (reject) reject(e);
                                else throw e;
                            }}
                        }}
                        const maybeSyncReturn = runNext(null);
                        return promise || maybeSyncReturn;
                    }};
                ",
                &self.src.js_init as &str,
                &self.src.js as &str,
            );
        } else {
            let (maybe_init_export, maybe_init) =
                if self.opts.tla_compat && opts.instantiation.is_none() {
                    uwriteln!(self.src.js_init, "_initialized = true;");
                    (
                        "\
                        let _initialized = false;
                        export ",
                        "",
                    )
                } else {
                    (
                        "",
                        "
                        await $init;
                    ",
                    )
                };

            uwrite!(
                output,
                "\
                    {}
                    {}
                    {}
                    {maybe_init_export}const $init = (() => {{
                        let gen = (function* _initGenerator () {{
                            {}\
                            {}\
                            {}\
                        }})();
                        let promise, resolve, reject;
                        function runNext (value) {{
                            try {{
                                let done;
                                do {{
                                    ({{ value, done }} = gen.next(value));
                                }} while (!(value instanceof Promise) && !done);
                                if (done) {{
                                    if (resolve) resolve(value);
                                    else return value;
                                }}
                                if (!promise) promise = new Promise((_resolve, _reject) => (resolve = _resolve, reject = _reject));
                                value.then(runNext, reject);
                            }}
                            catch (e) {{
                                if (reject) reject(e);
                                else throw e;
                            }}
                        }}
                        const maybeSyncReturn = runNext(null);
                        return promise || maybeSyncReturn;
                    }})();
                    {maybe_init}\
                ",
                &js_intrinsics as &str,
                &intrinsic_definitions as &str,
                &self.src.js as &str,
                &compilation_promises as &str,
                &self.src.js_init as &str,
                &core_exported_funcs as &str,
            );

            self.esm_bindgen.render_exports(
                &mut output,
                self.opts.instantiation.is_some(),
                &mut self.local_names,
                opts,
            );
        }

        let mut bytes = output.as_bytes();
        // strip leading newline
        if bytes[0] == b'\n' {
            bytes = &bytes[1..];
        }
        files.push(&format!("{name}.js"), bytes);
    }

    fn intrinsic(&mut self, intrinsic: Intrinsic) -> String {
        self.all_intrinsics.insert(intrinsic);
        intrinsic.name().to_string()
    }
}

/// Helper structure used to generate the `instantiate` method of a component.
///
/// This is the main structure for parsing the output of Wasmtime.
pub(crate) struct Instantiator<'a, 'b> {
    src: Source,
    bindgen: &'a mut JsBindgen<'b>,
    modules: &'a PrimaryMap<StaticModuleIndex, core::Translation<'a>>,
    instances: PrimaryMap<RuntimeInstanceIndex, StaticModuleIndex>,
    types: &'a ComponentTypes,
    resolve: &'a Resolve,
    world: WorldId,
    sizes: SizeAlign,
    component: &'a Component,

    /// Map of error contexts tables for a given component & error context index pair
    /// that have been initialized
    error_context_component_initialized: PrimaryMap<RuntimeComponentInstanceIndex, bool>,
    error_context_component_table_initialized:
        PrimaryMap<TypeComponentLocalErrorContextTableIndex, bool>,

    /// Component-level translation information, including trampolines
    translation: &'a ComponentTranslation,

    /// Lookup of exported types to resource indices
    exports_resource_types: BTreeMap<TypeId, ResourceIndex>,
    /// Lookup of resource indices to exported types
    exports_resource_index_types: BTreeMap<ResourceIndex, TypeId>,

    /// Lookup of imported types to resource indices
    imports_resource_types: BTreeMap<TypeId, ResourceIndex>,
    /// Lookup of resource indices to imported types
    #[allow(unused)]
    imports_resource_index_types: BTreeMap<ResourceIndex, TypeId>,

    resources_initialized: BTreeMap<ResourceIndex, bool>,
    resource_tables_initialized: BTreeMap<TypeResourceTableIndex, bool>,

    exports: BTreeMap<String, WorldKey>,
    imports: BTreeMap<String, WorldKey>,
    /// Instance flags which references have been emitted externally at least once.
    used_instance_flags: RefCell<BTreeSet<RuntimeComponentInstanceIndex>>,
    defined_resource_classes: BTreeSet<String>,
    async_imports: HashSet<String>,
    async_exports: HashSet<String>,
    lowering_options:
        PrimaryMap<LoweredIndex, (&'a CanonicalOptions, TrampolineIndex, TypeFuncIndex)>,

    /// Mapping of stream table indices to component indices
    stream_tables: BTreeMap<TypeStreamTableIndex, RuntimeComponentInstanceIndex>,

    /// Mapping of future table indices to component indices
    future_tables: BTreeMap<TypeFutureTableIndex, RuntimeComponentInstanceIndex>,

    /// Mapping of err ctx indices to component indices
    err_ctx_tables:
        BTreeMap<TypeComponentLocalErrorContextTableIndex, RuntimeComponentInstanceIndex>,

    /// Map of exported resources built during export bindgen
    resource_exports: ResourceMap,
    /// Map of imported resources built during export bindgen
    resource_imports: ResourceMap,
}

impl<'a> ManagesIntrinsics for Instantiator<'a, '_> {
    fn add_intrinsic(&mut self, intrinsic: Intrinsic) {
        self.bindgen.intrinsic(intrinsic);
    }
}

impl<'a> Instantiator<'a, '_> {
    fn initialize(&mut self) {
        // Populate reverse map from import and export names to world items
        for (key, _) in &self.resolve.worlds[self.world].imports {
            let name = &self.resolve.name_world_key(key);
            self.imports.insert(name.to_string(), key.clone());
        }
        for (key, _) in &self.resolve.worlds[self.world].exports {
            let name = &self.resolve.name_world_key(key);
            self.exports.insert(name.to_string(), key.clone());
        }

        // Populate reverse map from TypeId to ResourceIndex
        // Populate the resource type to resource index map
        for (key, item) in &self.resolve.worlds[self.world].imports {
            let name = &self.resolve.name_world_key(key);
            let Some((_, (_, import))) = self
                .component
                .import_types
                .iter()
                .find(|(_, (impt_name, _))| impt_name == name)
            else {
                match item {
                    WorldItem::Interface { .. } => {
                        unreachable!("unexpected interface in import types during initialization")
                    }
                    WorldItem::Function(_) => {
                        unreachable!("unexpected function in import types during initialization")
                    }
                    WorldItem::Type { id, .. } => {
                        assert!(!matches!(
                            self.resolve.types[*id].kind,
                            TypeDefKind::Resource
                        ))
                    }
                }
                continue;
            };
            match item {
                WorldItem::Interface { id, .. } => {
                    let TypeDef::ComponentInstance(instance) = import else {
                        unreachable!("unexpectedly non-component instance import in interface")
                    };
                    let import_ty = &self.types[*instance];
                    let iface = &self.resolve.interfaces[*id];
                    for (ty_name, ty) in &iface.types {
                        match &import_ty.exports.get(ty_name) {
                            Some(TypeDef::Resource(resource_table_idx)) => {
                                let ty = crate::dealias(self.resolve, *ty);
                                let resource_table_ty = &self.types[*resource_table_idx];
                                self.imports_resource_types
                                    .insert(ty, resource_table_ty.unwrap_concrete_ty());
                            }
                            Some(TypeDef::Interface(_)) | None => {}
                            Some(_) => unreachable!("unexpected type in interface"),
                        }
                    }
                }
                WorldItem::Function(_) => {}
                WorldItem::Type { id, .. } => match import {
                    TypeDef::Resource(resource) => {
                        let ty = crate::dealias(self.resolve, *id);
                        let resource_table_ty = &self.types[*resource];
                        self.imports_resource_types
                            .insert(ty, resource_table_ty.unwrap_concrete_ty());
                    }
                    TypeDef::Interface(_) => {}
                    _ => unreachable!("unexpected type in import world item"),
                },
            }
        }
        self.exports_resource_types = self.imports_resource_types.clone();

        for (key, item) in &self.resolve.worlds[self.world].exports {
            let name = &self.resolve.name_world_key(key);
            let (_, export_idx) = self
                .component
                .exports
                .raw_iter()
                .find(|(expt_name, _)| *expt_name == name)
                .unwrap();
            let export = &self.component.export_items[*export_idx];
            match item {
                WorldItem::Interface { id, .. } => {
                    let iface = &self.resolve.interfaces[*id];
                    let Export::Instance { exports, .. } = &export else {
                        unreachable!("unexpectedly non export instance item")
                    };
                    for (ty_name, ty) in &iface.types {
                        match self.component.export_items
                            [*exports.get(ty_name, &NameMapNoIntern).unwrap()]
                        {
                            Export::Type(TypeDef::Resource(resource)) => {
                                let ty = crate::dealias(self.resolve, *ty);
                                let resource_table_ty = &self.types[resource];
                                let concrete_ty = resource_table_ty.unwrap_concrete_ty();
                                self.exports_resource_types.insert(ty, concrete_ty);
                                self.exports_resource_index_types.insert(concrete_ty, ty);
                            }
                            Export::Type(_) => {}
                            _ => unreachable!(
                                "unexpected type in component export items on iface [{iface_name}]",
                                iface_name = iface.name.as_deref().unwrap_or("<unknown>"),
                            ),
                        }
                    }
                }
                WorldItem::Function(_) => {}
                WorldItem::Type { .. } => unreachable!("unexpected exported world item type"),
            }
        }
    }

    fn instantiate(&mut self) {
        // Handle all built in trampolines
        for (i, trampoline) in self.translation.trampolines.iter() {
            let Trampoline::LowerImport {
                index,
                lower_ty,
                options,
            } = trampoline
            else {
                continue;
            };

            let options = self
                .component
                .options
                .get(*options)
                .expect("failed to find canon options");

            let i = self.lowering_options.push((options, i, *lower_ty));
            assert_eq!(i, *index);
        }

        if let Some(InstantiationMode::Async) = self.bindgen.opts.instantiation {
            // To avoid uncaught promise rejection errors, we attach an intermediate
            // Promise.all with a rejection handler, if there are multiple promises.
            if self.modules.len() > 1 {
                self.src.js_init.push_str("Promise.all([");
                for i in 0..self.modules.len() {
                    if i > 0 {
                        self.src.js_init.push_str(", ");
                    }
                    self.src.js_init.push_str(&format!("module{i}"));
                }
                uwriteln!(self.src.js_init, "]).catch(() => {{}});");
            }
        }

        // Set up global stream map, which is used by intrinsics like stream.transfer
        let global_stream_table_map =
            Intrinsic::AsyncStream(AsyncStreamIntrinsic::GlobalStreamTableMap).name();
        let rep_table_class = Intrinsic::RepTableClass.name();
        for (table_idx, component_idx) in self.stream_tables.iter() {
            self.src.js.push_str(&format!(
                "{global_stream_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
                table_idx.as_u32(),
                component_idx.as_u32(),
            ));
        }

        // Set up global future map, which is used by intrinsics like future.transfer
        let global_future_table_map =
            Intrinsic::AsyncFuture(AsyncFutureIntrinsic::GlobalFutureTableMap).name();
        let rep_table_class = Intrinsic::RepTableClass.name();
        for (table_idx, component_idx) in self.future_tables.iter() {
            self.src.js.push_str(&format!(
                "{global_future_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
                table_idx.as_u32(),
                component_idx.as_u32(),
            ));
        }

        // Set up global error context map, which is used by intrinsics like err_ctx.transfer
        let global_err_ctx_table_map =
            Intrinsic::ErrCtx(ErrCtxIntrinsic::GlobalErrCtxTableMap).name();
        let rep_table_class = Intrinsic::RepTableClass.name();
        for (table_idx, component_idx) in self.err_ctx_tables.iter() {
            self.src.js.push_str(&format!(
                "{global_err_ctx_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
                table_idx.as_u32(),
                component_idx.as_u32(),
            ));
        }

        // Process global initializers
        //
        // The order of initialization is unfortunately quite fragile.
        //
        // We take care in processing module instantiations because we must ensure that
        // $wit-component.fixups must be instantiated directly after $wit-component.shim
        //
        let mut lower_import_initializers = Vec::new();

        // Process first n lower import initializers until the first instantiate module initializer
        for init in self.component.initializers.iter() {
            match init {
                GlobalInitializer::InstantiateModule(_m, _maybe_idx) => {
                    // Ensure lower import initializers are processed before the first module instantiation
                    for lower_import_init in lower_import_initializers.drain(..) {
                        self.instantiation_global_initializer(lower_import_init);
                    }
                }

                // We push lower import initializers down to right before instantiate, so that the
                // memory, realloc and postReturn functions are available to the import lowerings
                // for optimized bindgen
                GlobalInitializer::LowerImport { .. } => {
                    lower_import_initializers.push(init);
                    continue;
                }
                _ => {}
            }

            self.instantiation_global_initializer(init);
        }

        // Process lower import initializers that were discovered after the last module instantiation
        for init in lower_import_initializers.drain(..) {
            self.instantiation_global_initializer(init);
        }

        // Process imports and build mappings
        self.process_imports();

        // Process exports and build mappings
        self.process_exports();

        // Some trampolines that correspond to host-provided imports need to be defined before the
        // instantiation bits since they are referred to.
        for (i, trampoline) in self
            .translation
            .trampolines
            .iter()
            .filter(|(_, t)| Instantiator::is_early_trampoline(t))
        {
            self.trampoline(i, trampoline);
        }

        if self.bindgen.opts.instantiation.is_some() {
            let js_init = mem::take(&mut self.src.js_init);
            self.src.js.push_str(&js_init);
        }

        // Trampolines here so we have static module indices, and resource maps populated
        // (both imports and exports may still be populting resource map)
        for (i, trampoline) in self
            .translation
            .trampolines
            .iter()
            .filter(|(_, t)| !Instantiator::is_early_trampoline(t))
        {
            self.trampoline(i, trampoline);
        }
    }

    fn ensure_local_resource_class(&mut self, local_name: String) {
        if !self.defined_resource_classes.contains(&local_name) {
            uwriteln!(
                self.src.js,
                "\nclass {local_name} {{
                constructor () {{
                    throw new Error('\"{local_name}\" resource does not define a constructor');
                }}
            }}"
            );
            self.defined_resource_classes.insert(local_name.to_string());
        }
    }

    fn resource_definitions(&mut self, definitions: &mut source::Source) {
        // It is theoretically possible for locally defined resources used in no functions
        // to still be exported
        for resource in 0..self.component.num_resources {
            let resource = ResourceIndex::from_u32(resource);
            let is_imported = self.component.defined_resource_index(resource).is_none();
            if is_imported {
                continue;
            }
            if let Some(local_name) = self.bindgen.local_names.try_get(resource) {
                self.ensure_local_resource_class(local_name.to_string());
            }
        }

        // Write out the defined resource table indices for the runtime
        if self.bindgen.all_intrinsics.contains(&Intrinsic::Resource(
            ResourceIntrinsic::ResourceTransferBorrow,
        )) || self.bindgen.all_intrinsics.contains(&Intrinsic::Resource(
            ResourceIntrinsic::ResourceTransferBorrowValidLifting,
        )) {
            let defined_resource_tables = Intrinsic::DefinedResourceTables.name();
            uwrite!(definitions, "const {defined_resource_tables} = [");
            // Table per-resource
            for tidx in 0..self.component.num_resources {
                let tid = TypeResourceTableIndex::from_u32(tidx);
                let resource_table_ty = &self.types[tid];
                let rid = resource_table_ty.unwrap_concrete_ty();
                if let Some(defined_index) = self.component.defined_resource_index(rid) {
                    let instance_idx = resource_table_ty.unwrap_concrete_instance();
                    if instance_idx == self.component.defined_resource_instances[defined_index] {
                        uwrite!(definitions, "true,");
                    }
                } else {
                    uwrite!(definitions, ",");
                };
            }
            uwrite!(definitions, "];\n");
        }
    }

    /// Ensure a component-local `error-context` table has been created
    ///
    /// # Arguments
    ///
    /// * `component_idx` - component index
    /// * `err_ctx_tbl_idx` - The component-local error-context table index
    ///
    fn ensure_error_context_local_table(
        &mut self,
        component_idx: RuntimeComponentInstanceIndex,
        err_ctx_tbl_idx: TypeComponentLocalErrorContextTableIndex,
    ) {
        if self.error_context_component_initialized[component_idx]
            && self.error_context_component_table_initialized[err_ctx_tbl_idx]
        {
            return;
        }
        let err_ctx_local_tables = self
            .bindgen
            .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ComponentLocalTable));
        let rep_table_class = Intrinsic::RepTableClass.name();
        let c = component_idx.as_u32();
        if !self.error_context_component_initialized[component_idx] {
            uwriteln!(self.src.js, "{err_ctx_local_tables}.set({c}, new Map());");
            self.error_context_component_initialized[component_idx] = true;
        }
        if !self.error_context_component_table_initialized[err_ctx_tbl_idx] {
            let t = err_ctx_tbl_idx.as_u32();
            uwriteln!(
                self.src.js,
                "{err_ctx_local_tables}.get({c}).set({t}, new {rep_table_class}({{ target: `component [{c}] local error ctx table [{t}]` }}));"
            );
            self.error_context_component_table_initialized[err_ctx_tbl_idx] = true;
        }
    }

    /// Ensure that a resource table has been initialized
    ///
    /// For the relevant resource table, this function will generate initialization
    /// blocks, exactly once.
    ///
    /// This is not done for *all* resources, but instead for those that are explicitly used.
    fn ensure_resource_table(&mut self, resource_table_idx: TypeResourceTableIndex) {
        if self
            .resource_tables_initialized
            .contains_key(&resource_table_idx)
        {
            return;
        }

        let resource_table_ty = &self.types[resource_table_idx];
        let resource_idx = resource_table_ty.unwrap_concrete_ty();

        let (is_imported, maybe_dtor) =
            if let Some(resource_idx) = self.component.defined_resource_index(resource_idx) {
                let resource_def = self
                    .component
                    .initializers
                    .iter()
                    .find_map(|i| match i {
                        GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
                        _ => None,
                    })
                    .unwrap();

                if let Some(dtor) = &resource_def.dtor {
                    (false, format!("\n{}(rep);", self.core_def(dtor)))
                } else {
                    (false, "".into())
                }
            } else {
                (true, "".into())
            };

        let handle_tables = self.bindgen.intrinsic(Intrinsic::HandleTables);
        let rsc_table_flag = self
            .bindgen
            .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
        let rsc_table_remove = self
            .bindgen
            .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));

        let rtid = resource_table_idx.as_u32();
        if is_imported {
            uwriteln!(
                self.src.js,
                "const handleTable{rtid} = [{rsc_table_flag}, 0];",
            );
            if !self.resources_initialized.contains_key(&resource_idx) {
                let ridx = resource_idx.as_u32();
                uwriteln!(
                    self.src.js,
                    "const captureTable{ridx} = new Map();
                    let captureCnt{ridx} = 0;"
                );
                self.resources_initialized.insert(resource_idx, true);
            }
        } else {
            let finalization_registry_create = self
                .bindgen
                .intrinsic(Intrinsic::FinalizationRegistryCreate);
            uwriteln!(
                self.src.js,
                "const handleTable{rtid} = [{rsc_table_flag}, 0];
                const finalizationRegistry{rtid} = {finalization_registry_create}((handle) => {{
                    const {{ rep }} = {rsc_table_remove}(handleTable{rtid}, handle);{maybe_dtor}
                }});
                ",
            );
        }
        uwriteln!(self.src.js, "{handle_tables}[{rtid}] = handleTable{rtid};");
        self.resource_tables_initialized
            .insert(resource_table_idx, true);
    }

    fn instance_flags(&mut self) {
        // SAFETY: short-lived borrow, and the refcell isn't mutably borrowed in the loop's body.
        let mut instance_flag_defs = String::new();
        for used in self.used_instance_flags.borrow().iter() {
            let i = used.as_u32();
            uwriteln!(
                &mut instance_flag_defs,
                "const instanceFlags{i} = new WebAssembly.Global({{ value: \"i32\", mutable: true }}, {});",
                wasmtime_environ::component::FLAG_MAY_LEAVE
            );
        }
        self.src.js_init.prepend_str(&instance_flag_defs);
    }

    // Trampolines defined in is_early_trampoline() below that use:
    //   const trampoline{} = ...
    // require early initialization since their bindings aren't auto-hoisted
    // like JS functions are in the JS runtime.
    fn is_early_trampoline(trampoline: &Trampoline) -> bool {
        matches!(
            trampoline,
            Trampoline::AsyncStartCall { .. }
                | Trampoline::BackpressureDec { .. }
                | Trampoline::BackpressureInc { .. }
                | Trampoline::ContextGet { .. }
                | Trampoline::ContextSet { .. }
                | Trampoline::EnterSyncCall
                | Trampoline::ErrorContextDebugMessage { .. }
                | Trampoline::ErrorContextDrop { .. }
                | Trampoline::ErrorContextNew { .. }
                | Trampoline::ErrorContextTransfer
                | Trampoline::ExitSyncCall
                | Trampoline::FutureCancelRead { .. }
                | Trampoline::FutureCancelWrite { .. }
                | Trampoline::FutureDropReadable { .. }
                | Trampoline::FutureDropWritable { .. }
                | Trampoline::FutureRead { .. }
                | Trampoline::FutureWrite { .. }
                | Trampoline::FutureNew { .. }
                | Trampoline::LowerImport { .. }
                | Trampoline::PrepareCall { .. }
                | Trampoline::ResourceDrop { .. }
                | Trampoline::ResourceNew { .. }
                | Trampoline::ResourceRep { .. }
                | Trampoline::ResourceTransferBorrow
                | Trampoline::ResourceTransferOwn
                | Trampoline::StreamCancelRead { .. }
                | Trampoline::StreamCancelWrite { .. }
                | Trampoline::StreamDropReadable { .. }
                | Trampoline::StreamDropWritable { .. }
                | Trampoline::StreamNew { .. }
                | Trampoline::StreamRead { .. }
                | Trampoline::StreamTransfer
                | Trampoline::StreamWrite { .. }
                | Trampoline::SubtaskCancel { .. }
                | Trampoline::SubtaskDrop { .. }
                | Trampoline::SyncStartCall { .. }
                | Trampoline::TaskCancel { .. }
                | Trampoline::TaskReturn { .. }
                | Trampoline::WaitableJoin { .. }
                | Trampoline::WaitableSetDrop { .. }
                | Trampoline::WaitableSetNew { .. }
                | Trampoline::WaitableSetPoll { .. }
                | Trampoline::WaitableSetWait { .. }
        )
    }

    fn trampoline(&mut self, i: TrampolineIndex, trampoline: &'a Trampoline) {
        let i = i.as_u32();
        match trampoline {
            Trampoline::TaskCancel { instance } => {
                let task_cancel_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::TaskCancel));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {task_cancel_fn}.bind(null, {instance_idx});\n",
                    instance_idx = instance.as_u32(),
                );
            }

            Trampoline::SubtaskCancel { instance, async_ } => {
                let task_cancel_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::SubtaskCancel));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {task_cancel_fn}.bind(null, {instance_idx}, {async_});\n",
                    instance_idx = instance.as_u32(),
                );
            }

            Trampoline::SubtaskDrop { instance } => {
                let component_idx = instance.as_u32();
                let subtask_drop_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::SubtaskDrop));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {subtask_drop_fn}.bind(
                         null,
                         {component_idx},
                     );"
                );
            }

            Trampoline::WaitableSetNew { instance } => {
                let waitable_set_new_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetNew));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {waitable_set_new_fn}.bind(null, {});\n",
                    instance.as_u32(),
                );
            }

            Trampoline::WaitableSetWait { instance, options } => {
                let options = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options");
                assert_eq!(
                    instance.as_u32(),
                    options.instance.as_u32(),
                    "options index instance must match trampoline"
                );

                let CanonicalOptions {
                    instance,
                    async_,
                    data_model:
                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
                    ..
                } = options
                else {
                    panic!("unexpected/missing memory data model during waitable-set.wait");
                };

                let instance_idx = instance.as_u32();
                let memory_idx = memory
                    .expect("missing memory idx for waitable-set.wait")
                    .as_u32();
                let waitable_set_wait_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetWait));

                uwriteln!(
                    self.src.js,
                    r#"
                    const trampoline{i} = new WebAssembly.Suspending({waitable_set_wait_fn}.bind(null, {{
                        componentIdx: {instance_idx},
                        isAsync: {async_},
                        memoryIdx: {memory_idx},
                        getMemoryFn: () => memory{memory_idx},
                    }}));
                    "#,
                );
            }

            Trampoline::WaitableSetPoll { options, .. } => {
                let CanonicalOptions {
                    instance,
                    async_,
                    data_model:
                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
                    cancellable,
                    ..
                } = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options")
                else {
                    panic!("unexpected memory data model during waitable-set.poll");
                };

                let instance_idx = instance.as_u32();
                let memory_idx = memory
                    .expect("missing memory idx for waitable-set.poll")
                    .as_u32();
                let waitable_set_poll_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetPoll));

                uwriteln!(
                    self.src.js,
                    r#"
                    const trampoline{i} = {waitable_set_poll_fn}.bind(
                        null,
                        {{
                            componentIdx: {instance_idx},
                            isAsync: {async_},
                            isCancellable: {cancellable},
                            memoryIdx: {memory_idx},
                            getMemoryFn: () => memory{memory_idx},
                        }}
                    );
                    "#,
                );
            }

            Trampoline::WaitableSetDrop { instance } => {
                let waitable_set_drop_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetDrop));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {waitable_set_drop_fn}.bind(null, {instance_idx});\n",
                    instance_idx = instance.as_u32(),
                );
            }

            Trampoline::WaitableJoin { instance } => {
                let waitable_join_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableJoin));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {waitable_join_fn}.bind(null, {instance_idx});\n",
                    instance_idx = instance.as_u32(),
                );
            }

            Trampoline::StreamNew { ty, instance } => {
                let stream_new_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamNew));
                let instance_idx = instance.as_u32();
                let stream_table_idx = ty.as_u32();

                // Get to the payload type for the given stream table idx
                let table_ty = &self.types[*ty];
                let stream_ty_idx = table_ty.ty;
                let stream_ty = &self.types[stream_ty_idx];

                // TODO(???): do we have no way to go from interface type to in-component type idx?
                // TODO(???): does this work under type aliases?? we need the type def?
                // TODO(???): can the stream type be treated as a unique indicator of the payload type? maybe not?
                // need a way to go from iface type + stream type -> payload type idx?
                let payload_ty_name_js = stream_ty
                    .payload
                    .map(|iface_ty| format!("'{iface_ty:?}'"))
                    .unwrap_or_else(|| "null".into());

                // Gather type metadata
                let (
                    align_32_js,
                    size_32_js,
                    flat_count_js,
                    lift_fn_js,
                    lower_fn_js,
                    is_none_js,
                    is_numeric_type_js,
                    is_borrow_js,
                    is_async_value_js,
                ) = match stream_ty.payload {
                    // If there is no payload for the stream, we know the values
                    None => (
                        "0".into(),
                        "0".into(),
                        "0".into(),
                        "null".into(),
                        "null".into(),
                        "true",
                        "false".into(),
                        "false".into(),
                        "false".into(),
                    ),
                    // If there is a payload, generate relevant lift/lower and other metadata
                    Some(ty) => (
                        self.types.canonical_abi(&ty).align32.to_string(),
                        self.types.canonical_abi(&ty).size32.to_string(),
                        self.types
                            .canonical_abi(&ty)
                            .flat_count
                            .map(|v| v.to_string())
                            .unwrap_or_else(|| "null".into()),
                        gen_flat_lift_fn_js_expr(self, &ty, &None),
                        gen_flat_lower_fn_js_expr(self, &ty, &None),
                        "false",
                        format!(
                            "{}",
                            matches!(
                                ty,
                                InterfaceType::U8
                                    | InterfaceType::U16
                                    | InterfaceType::U32
                                    | InterfaceType::U64
                                    | InterfaceType::S8
                                    | InterfaceType::S16
                                    | InterfaceType::S32
                                    | InterfaceType::S64
                                    | InterfaceType::Float32
                                    | InterfaceType::Float64
                            )
                        ),
                        format!("{}", matches!(ty, InterfaceType::Borrow(_))),
                        format!(
                            "{}",
                            matches!(ty, InterfaceType::Stream(_) | InterfaceType::Future(_))
                        ),
                    ),
                };

                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {stream_new_fn}.bind(null, {{
                        streamTableIdx: {stream_table_idx},
                        callerComponentIdx: {instance_idx},
                        elemMeta: {{
                            liftFn: {lift_fn_js},
                            lowerFn: {lower_fn_js},
                            payloadTypeName: {payload_ty_name_js},
                            isNone: {is_none_js},
                            isNumeric: {is_numeric_type_js},
                            isBorrowed: {is_borrow_js},
                            isAsyncValue: {is_async_value_js},
                            flatCount: {flat_count_js},
                            align32: {align_32_js},
                            size32: {size_32_js},
                        }},
                    }});\n",
                );
            }

            Trampoline::StreamRead {
                instance,
                ty,
                options,
            } => {
                let options = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options");
                assert_eq!(
                    instance.as_u32(),
                    options.instance.as_u32(),
                    "options index instance must match trampoline"
                );

                let CanonicalOptions {
                    instance,
                    string_encoding,
                    async_,
                    data_model:
                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
                    ..
                } = options
                else {
                    unreachable!("missing/invalid data model for options during stream.read")
                };
                let memory_idx = memory.expect("missing memory idx for stream.read").as_u32();
                let (realloc_idx, get_realloc_fn_js) = match realloc {
                    Some(v) => {
                        let v = v.as_u32().to_string();
                        (v.to_string(), format!("() => realloc{v}"))
                    }
                    None => ("null".into(), "() => null".into()),
                };

                let component_instance_id = instance.as_u32();
                let string_encoding = string_encoding_js_literal(string_encoding);
                let stream_table_idx = ty.as_u32();
                let stream_read_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamRead));

                // PrepareCall for an async call is sometimes missing memories,
                // so we augment and save here, knowing that any stream.write/read operation
                // that uses a memory is indicative of that component's memory
                //
                let register_global_memory_for_component_fn =
                    Intrinsic::RegisterGlobalMemoryForComponent.name();
                uwriteln!(
                    self.src.js_init,
                    r#"{register_global_memory_for_component_fn}({{
                         componentIdx: {component_instance_id},
                         memoryIdx: {memory_idx},
                         memory: memory{memory_idx},
                     }});"#
                );

                uwriteln!(
                    self.src.js,
                    r#"const trampoline{i} = new WebAssembly.Suspending({stream_read_fn}.bind(
                         null,
                         {{
                             componentIdx: {component_instance_id},
                             memoryIdx: {memory_idx},
                             getMemoryFn: () => memory{memory_idx},
                             reallocIdx: {realloc_idx},
                             getReallocFn: {get_realloc_fn_js},
                             stringEncoding: {string_encoding},
                             isAsync: {async_},
                             streamTableIdx: {stream_table_idx},
                         }}
                     ));
                    "#,
                );
            }

            Trampoline::StreamWrite {
                instance,
                ty,
                options,
            } => {
                let options = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options");
                assert_eq!(
                    instance.as_u32(),
                    options.instance.as_u32(),
                    "options index instance must match trampoline"
                );

                let CanonicalOptions {
                    instance,
                    string_encoding,
                    async_,
                    data_model:
                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
                    ..
                } = options
                else {
                    unreachable!("unexpected memory data model during stream.write");
                };
                let component_instance_id = instance.as_u32();
                let memory_idx = memory
                    .expect("missing memory idx for stream.write")
                    .as_u32();
                let (realloc_idx, get_realloc_fn_js) = match realloc {
                    Some(v) => {
                        let v = v.as_u32().to_string();
                        (v.to_string(), format!("() => realloc{v}"))
                    }
                    None => ("null".into(), "() => null".into()),
                };

                let string_encoding = string_encoding_js_literal(string_encoding);
                let stream_table_idx = ty.as_u32();
                let stream_write_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamWrite));

                // PrepareCall for an async call is sometimes missing memories,
                // so we augment and save here, knowing that any stream.write/read operation
                // that uses a memory is indicative of that component's memory
                let register_global_memory_for_component_fn =
                    Intrinsic::RegisterGlobalMemoryForComponent.name();
                uwriteln!(
                    self.src.js_init,
                    r#"{register_global_memory_for_component_fn}({{
                         componentIdx: {component_instance_id},
                         memoryIdx: {memory_idx},
                         memory: memory{memory_idx},
                     }});"#
                );

                uwriteln!(
                    self.src.js,
                    r#"
                     const trampoline{i} = new WebAssembly.Suspending({stream_write_fn}.bind(
                         null,
                         {{
                             componentIdx: {component_instance_id},
                             memoryIdx: {memory_idx},
                             getMemoryFn: () => memory{memory_idx},
                             reallocIdx: {realloc_idx},
                             getReallocFn: {get_realloc_fn_js},
                             stringEncoding: {string_encoding},
                             isAsync: {async_},
                             streamTableIdx: {stream_table_idx},
                         }}
                     ));
                    "#,
                );
            }

            Trampoline::StreamCancelRead {
                instance,
                ty,
                async_,
            }
            | Trampoline::StreamCancelWrite {
                instance,
                ty,
                async_,
            } => {
                let stream_cancel_fn = match trampoline {
                    Trampoline::StreamCancelRead { .. } => self.bindgen.intrinsic(
                        Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamCancelRead),
                    ),
                    Trampoline::StreamCancelWrite { .. } => self.bindgen.intrinsic(
                        Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamCancelWrite),
                    ),
                    _ => unreachable!("unexpected trampoline"),
                };

                let stream_table_idx = ty.as_u32();
                let component_idx = instance.as_u32();
                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = new WebAssembly.Suspending({stream_cancel_fn}.bind(null, {{
                          streamTableIdx: {stream_table_idx},
                          isAsync: {async_},
                          componentIdx: {component_idx},
                      }}));
                    "#,
                );
            }

            Trampoline::StreamDropReadable { ty, instance }
            | Trampoline::StreamDropWritable { ty, instance } => {
                let intrinsic_fn = match trampoline {
                    Trampoline::StreamDropReadable { .. } => self.bindgen.intrinsic(
                        Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamDropReadable),
                    ),
                    Trampoline::StreamDropWritable { .. } => self.bindgen.intrinsic(
                        Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamDropWritable),
                    ),
                    _ => unreachable!("unexpected trampoline"),
                };
                let stream_idx = ty.as_u32();
                let instance_idx = instance.as_u32();
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {intrinsic_fn}.bind(null, {{
                        streamTableIdx: {stream_idx},
                        componentIdx: {instance_idx},
                    }});\n",
                );
            }

            Trampoline::StreamTransfer => {
                let stream_transfer_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamTransfer));
                uwriteln!(self.src.js, "const trampoline{i} = {stream_transfer_fn};\n",);
            }

            Trampoline::FutureNew { instance, ty } => {
                let future_new_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureNew));
                let future_table_idx = ty.as_u32();
                let component_idx = instance.as_u32();

                // Build element metadata
                let future_table_ty = &self.types[*ty];
                let future_ty = &self.types[future_table_ty.ty];
                let (
                    payload_size32,
                    payload_align32,
                    payload_flat_count_js,
                    payload_lift_fn_js,
                    payload_lower_fn_js,
                    is_borrowed,
                    is_none_type,
                    is_numeric_type,
                    is_async_value,
                ) = match future_ty.payload {
                    None => (
                        0,
                        0,
                        "0".into(),
                        "() => {{ throw new Error('empty future payload'); }}".into(),
                        "() => {{ throw new Error('empty future payload'); }}".into(),
                        false,
                        true,
                        false,
                        false,
                    ),
                    Some(payload_ty) => {
                        let cabi = self.types.canonical_abi(&payload_ty);
                        (
                            cabi.size32,
                            cabi.align32,
                            cabi.flat_count
                                .map(|v| format!("{v}"))
                                .unwrap_or_else(|| "null".into()),
                            gen_flat_lift_fn_js_expr(self, &payload_ty, &None),
                            gen_flat_lower_fn_js_expr(self, &payload_ty, &None),
                            matches!(payload_ty, InterfaceType::Borrow(_)),
                            false,
                            matches!(
                                payload_ty,
                                InterfaceType::U8
                                    | InterfaceType::U16
                                    | InterfaceType::U32
                                    | InterfaceType::U64
                                    | InterfaceType::S8
                                    | InterfaceType::S16
                                    | InterfaceType::S32
                                    | InterfaceType::S64
                                    | InterfaceType::Float32
                                    | InterfaceType::Float64
                            ),
                            matches!(
                                payload_ty,
                                InterfaceType::Stream(_) | InterfaceType::Future(_)
                            ),
                        )
                    }
                };
                let payload_ty_name_js = future_ty
                    .payload
                    .map(|iface_ty| format!("'{iface_ty:?}'"))
                    .unwrap_or_else(|| "null".into());

                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = {future_new_fn}.bind(null, {{
                          componentIdx: {component_idx},
                          futureTableIdx: {future_table_idx},
                          elemMeta: {{
                              liftFn: {payload_lift_fn_js},
                              lowerFn: {payload_lower_fn_js},
                              payloadTypeName: {payload_ty_name_js},
                              isNone: {is_none_type},
                              isNumeric: {is_numeric_type},
                              isBorrowed: {is_borrowed},
                              isAsyncValue: {is_async_value},
                              flatCount: {payload_flat_count_js},
                              align32: {payload_align32},
                              size32: {payload_size32},
                          }},
                      }});
                    "#,
                );
            }

            Trampoline::FutureWrite {
                instance,
                ty,
                options,
            }
            | Trampoline::FutureRead {
                instance,
                ty,
                options,
            } => {
                let intrinsic_fn = match trampoline {
                    Trampoline::FutureRead { .. } => self
                        .bindgen
                        .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureRead)),
                    Trampoline::FutureWrite { .. } => self
                        .bindgen
                        .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureWrite)),
                    _ => unreachable!("invalid trampoline"),
                };

                let options = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options");
                let CanonicalOptions {
                    async_,
                    string_encoding,
                    callback,
                    post_return,
                    data_model:
                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
                    ..
                } = options
                else {
                    unreachable!("unexpected memory data model during future intrinsic");
                };

                assert_eq!(
                    *instance, options.instance,
                    "component instances should match"
                );
                assert!(
                    callback.is_none(),
                    "callback should not be present for future intrinsic"
                );
                assert!(
                    post_return.is_none(),
                    "post_return should not be present for future intrinsic"
                );

                let future_table_idx = ty.as_u32();
                let component_idx = instance.as_u32();
                let memory_idx = memory
                    .expect("missing memory idx for future intrinsic")
                    .as_u32();
                let (realloc_idx, get_realloc_fn_js) = match realloc {
                    Some(idx) => (
                        idx.as_u32().to_string(),
                        format!("() => realloc{}", idx.as_u32()),
                    ),
                    None => ("null".into(), "() => null".to_string()),
                };
                let string_encoding = string_encoding_js_literal(string_encoding);

                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = new WebAssembly.Suspending({intrinsic_fn}.bind(
                          null,
                          {{
                              componentIdx: {component_idx},
                              memoryIdx: {memory_idx},
                              getMemoryFn: () => memory{memory_idx},
                              reallocIdx: {realloc_idx},
                              getReallocFn: {get_realloc_fn_js},
                              stringEncoding: {string_encoding},
                              futureTableIdx: {future_table_idx},
                              isAsync: {async_},
                          }},
                      ));
                    "#,
                );
            }

            Trampoline::FutureCancelRead {
                instance,
                ty,
                async_,
            }
            | Trampoline::FutureCancelWrite {
                instance,
                ty,
                async_,
            } => {
                let future_cancel_op_fn = match trampoline {
                    Trampoline::FutureCancelRead { .. } => self.bindgen.intrinsic(
                        Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureCancelRead),
                    ),
                    Trampoline::FutureCancelWrite { .. } => self.bindgen.intrinsic(
                        Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureCancelWrite),
                    ),
                    _ => unreachable!(),
                };

                let component_idx = instance.as_u32();
                let future_table_idx = ty.as_u32();

                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = new WebAssembly.Suspending({future_cancel_op_fn}.bind(
                          null,
                          {{
                              futureTableIdx: {future_table_idx},
                              componentIdx: {component_idx},
                              isAsync: {async_},
                          }},
                      ));
                    "#,
                );
            }

            Trampoline::FutureDropReadable { instance, ty }
            | Trampoline::FutureDropWritable { instance, ty } => {
                let future_drop_op_fn = match trampoline {
                    Trampoline::FutureDropReadable { .. } => self.bindgen.intrinsic(
                        Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureDropReadable),
                    ),
                    Trampoline::FutureDropWritable { .. } => self.bindgen.intrinsic(
                        Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureDropWritable),
                    ),
                    _ => unreachable!(),
                };

                let component_idx = instance.as_u32();
                let future_table_idx = ty.as_u32();

                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = new WebAssembly.Suspending({future_drop_op_fn}.bind(
                          null,
                          {{
                              futureTableIdx: {future_table_idx},
                              componentIdx: {component_idx},
                          }},
                      ));
                "#
                );
            }

            Trampoline::FutureTransfer => {
                let future_drop_writable_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureTransfer));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {future_drop_writable_fn};"
                );
            }

            Trampoline::ErrorContextNew { ty, options, .. } => {
                let CanonicalOptions {
                    instance,
                    string_encoding,
                    data_model:
                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
                    ..
                } = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options")
                else {
                    panic!("unexpected memory data model during error-context.new");
                };

                self.ensure_error_context_local_table(*instance, *ty);

                let local_err_tbl_idx = ty.as_u32();
                let component_idx = instance.as_u32();

                let memory_idx = memory
                    .expect("missing realloc fn idx for error-context.debug-message")
                    .as_u32();

                // Generate a string decoding function to match this trampoline that does appropriate encoding
                let decoder = match string_encoding {
                    wasmtime_environ::component::StringEncoding::Utf8 => self
                        .bindgen
                        .intrinsic(Intrinsic::String(StringIntrinsic::GlobalTextDecoderUtf8)),
                    wasmtime_environ::component::StringEncoding::Utf16 => self
                        .bindgen
                        .intrinsic(Intrinsic::String(StringIntrinsic::Utf16Decoder)),
                    enc => panic!(
                        "unsupported string encoding [{enc:?}] for error-context.debug-message"
                    ),
                };
                uwriteln!(
                    self.src.js,
                    "function trampoline{i}InputStr(ptr, len) {{
                         return {decoder}.decode(new DataView(memory{memory_idx}.buffer, ptr, len));
                    }}"
                );

                let err_ctx_new_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextNew));
                // Store the options associated with this new error context for later use in the global array
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {err_ctx_new_fn}.bind(
                         null,
                         {{
                             componentIdx: {component_idx},
                             localTableIdx: {local_err_tbl_idx},
                             readStrFn: trampoline{i}InputStr,
                         }}
                     );
                    "
                );
            }

            Trampoline::ErrorContextDebugMessage {
                instance, options, ..
            } => {
                let CanonicalOptions {
                    async_,
                    callback,
                    post_return,
                    string_encoding,
                    data_model:
                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
                    ..
                } = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options")
                else {
                    panic!("unexpected memory data model during error-context.debug-message");
                };

                let debug_message_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextDebugMessage));

                let realloc_fn_idx = realloc
                    .expect("missing realloc fn idx for error-context.debug-message")
                    .as_u32();
                let memory_idx = memory
                    .expect("missing realloc fn idx for error-context.debug-message")
                    .as_u32();

                // Generate a string encoding function to match this trampoline that does appropriate encoding
                match string_encoding {
                    wasmtime_environ::component::StringEncoding::Utf8 => {
                        let encode_fn = self
                            .bindgen
                            .intrinsic(Intrinsic::String(StringIntrinsic::Utf8Encode));
                        uwriteln!(
                            self.src.js,
                            "function trampoline{i}OutputStr(s, outputPtr) {{
                                 const memory = memory{memory_idx};
                                 const reallocFn = realloc{realloc_fn_idx};
                                 let {{ ptr, len }} = {encode_fn}(s, reallocFn, memory);
                                 new DataView(memory.buffer).setUint32(outputPtr, ptr, true)
                                 new DataView(memory.buffer).setUint32(outputPtr + 4, len, true)
                             }}"
                        );
                    }
                    wasmtime_environ::component::StringEncoding::Utf16 => {
                        let encode_fn = self
                            .bindgen
                            .intrinsic(Intrinsic::String(StringIntrinsic::Utf16Encode));
                        uwriteln!(
                            self.src.js,
                            "function trampoline{i}OutputStr(s, outputPtr) {{
                                 const memory = memory{memory_idx};
                                 const reallocFn = realloc{realloc_fn_idx};
                                 let ptr = {encode_fn}(s, reallocFn, memory);
                                 let len = s.length;
                                 new DataView(memory.buffer).setUint32(outputPtr, ptr, true)
                                 new DataView(memory.buffer).setUint32(outputPtr + 4, len, true)
                             }}"
                        );
                    }
                    enc => panic!(
                        "unsupported string encoding [{enc:?}] for error-context.debug-message"
                    ),
                };

                let options_obj = format!(
                    "{{callback:{callback}, postReturn: {post_return}, async: {async_}}}",
                    callback = callback
                        .map(|v| v.as_u32().to_string())
                        .unwrap_or_else(|| "null".into()),
                    post_return = post_return
                        .map(|v| v.as_u32().to_string())
                        .unwrap_or_else(|| "null".into()),
                );

                let component_idx = instance.as_u32();
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {debug_message_fn}.bind(
                         null,
                         {{
                             componentIdx: {component_idx},
                             options: {options_obj},
                             writeStrFn: trampoline{i}OutputStr,
                         }}
                     );"
                );
            }

            Trampoline::ErrorContextDrop { instance, ty } => {
                let drop_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextDrop));
                let local_err_tbl_idx = ty.as_u32();
                let component_idx = instance.as_u32();
                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = {drop_fn}.bind(
                          null,
                          {{ componentIdx: {component_idx}, localTableIdx: {local_err_tbl_idx} }},
                      );
                    "#
                );
            }

            Trampoline::ErrorContextTransfer => {
                let transfer_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextTransfer));
                uwriteln!(self.src.js, "const trampoline{i} = {transfer_fn};");
            }

            // This sets up a subtask (sets parent, etc) for guest -> guest calls
            Trampoline::PrepareCall { memory } => {
                let prepare_call_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Host(HostIntrinsic::PrepareCall));
                let (memory_idx_js, memory_fn_js) = memory
                    .map(|v| {
                        (
                            v.as_u32().to_string(),
                            format!("() => memory{}", v.as_u32()),
                        )
                    })
                    .unwrap_or_else(|| ("null".into(), "() => null".into()));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {prepare_call_fn}.bind(null, {memory_idx_js}, {memory_fn_js});",
                )
            }

            Trampoline::SyncStartCall { callback } => {
                let sync_start_call_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Host(HostIntrinsic::SyncStartCall));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {sync_start_call_fn}.bind(null, {});",
                    callback
                        .map(|v| v.as_u32().to_string())
                        .unwrap_or_else(|| "null".into()),
                );
            }

            // This actually starts a Task (whose parent is a subtask generated during PrepareCall)
            // for a from-component async import call
            Trampoline::AsyncStartCall {
                callback,
                post_return,
            } => {
                let async_start_call_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Host(HostIntrinsic::AsyncStartCall));
                let (callback_idx, callback_fn) = callback
                    .map(|v| (v.as_u32().to_string(), format!("callback_{}", v.as_u32())))
                    .unwrap_or_else(|| ("null".into(), "null".into()));
                let (post_return_idx, post_return_fn) = post_return
                    .map(|v| (v.as_u32().to_string(), format!("postReturn{}", v.as_u32())))
                    .unwrap_or_else(|| ("null".into(), "null".into()));

                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {async_start_call_fn}.bind(
                         null,
                         {{
                             postReturnIdx: {post_return_idx},
                             getPostReturnFn: () => {post_return_fn},
                             callbackIdx: {callback_idx},
                             getCallbackFn: () => {callback_fn},
                         }},
                     );",
                );
            }

            Trampoline::LowerImport {
                index: _,
                lower_ty,
                options,
            } => {
                let canon_opts = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options");

                // TODO(fix): remove Global lowers, should enable using just exports[x] to export[y] call
                // TODO(fix): promising for the run (*as well as exports*)
                // TODO(fix): delete all asyncImports/exports
                // TODO(opt): opt-in sync import

                let component_idx = canon_opts.instance.as_u32();
                let is_async = canon_opts.async_;

                let cancellable = canon_opts.cancellable;

                let func_ty = self.types.index(*lower_ty);

                // Build list of lift functions for the params of the lowered import
                let param_types = &self.types.index(func_ty.params).types;
                let param_lift_fns_js =
                    gen_flat_lift_fn_list_js_expr(self, param_types.iter().as_slice(), &None);

                // Build list of lower functions for the results of the lowered import
                let result_types = &self.types.index(func_ty.results).types;
                let result_lower_fns_js =
                    gen_flat_lower_fn_list_js_expr(self, result_types.iter().as_slice(), &None);

                let get_callback_fn_js = canon_opts
                    .callback
                    .map(|idx| format!("() => callback_{}", idx.as_u32()))
                    .unwrap_or_else(|| "() => null".into());
                let get_post_return_fn_js = canon_opts
                    .post_return
                    .map(|idx| format!("() => postReturn{}", idx.as_u32()))
                    .unwrap_or_else(|| "() => null".into());

                // Build the memory and realloc js expressions, retrieving the memory index and getter functions
                let (memory_exprs, realloc_expr_js) =
                    if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
                        memory,
                        realloc,
                    }) = canon_opts.data_model
                    {
                        (
                            memory.map(|idx| {
                                (
                                    idx.as_u32().to_string(),
                                    format!("() => memory{}", idx.as_u32()),
                                )
                            }),
                            realloc.map(|idx| format!("() => realloc{}", idx.as_u32())),
                        )
                    } else {
                        (None, None)
                    };
                let (memory_idx_js, memory_expr_js) =
                    memory_exprs.unwrap_or_else(|| ("null".into(), "() => null".into()));
                let realloc_expr_js = realloc_expr_js.unwrap_or_else(|| "() => null".into());
                let string_encoding_js = string_encoding_js_literal(&canon_opts.string_encoding);

                // Build the lower import call that will wrap the actual trampoline
                let func_ty_async = func_ty.async_;
                let call = format!(
                    r#"{lower_import_intrinsic}.bind(
                        null,
                        {{
                            trampolineIdx: {i},
                            componentIdx: {component_idx},
                            isAsync: {is_async},
                            isManualAsync: _trampoline{i}.manuallyAsync,
                            paramLiftFns: {param_lift_fns_js},
                            resultLowerFns: {result_lower_fns_js},
                            funcTypeIsAsync: {func_ty_async},
                            getCallbackFn: {get_callback_fn_js},
                            getPostReturnFn: {get_post_return_fn_js},
                            isCancellable: {cancellable},
                            memoryIdx: {memory_idx_js},
                            stringEncoding: {string_encoding_js},
                            getMemoryFn: {memory_expr_js},
                            getReallocFn: {realloc_expr_js},
                            importFn: _trampoline{i},
                        }},
                    )"#,
                    lower_import_intrinsic = if is_async || func_ty_async {
                        self.bindgen
                            .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::LowerImport))
                    } else {
                        self.bindgen.intrinsic(Intrinsic::AsyncTask(
                            AsyncTaskIntrinsic::LowerImportBackwardsCompat,
                        ))
                    }
                );

                // NOTE: For Trampoline::LowerImport, the trampoline index is actually already defined,
                // but we *redefine* it to call the lower import function first.
                if is_async || func_ty_async {
                    uwriteln!(
                        self.src.js,
                        "let trampoline{i} = new WebAssembly.Suspending({call});"
                    );
                } else {
                    // TODO(breaking): once manually specifying async imports is removed,
                    // we can avoid the second check below.
                    uwriteln!(
                        self.src.js,
                        "let trampoline{i} = _trampoline{i}.manuallyAsync ? new WebAssembly.Suspending({call}) : {call};"
                    );
                }
            }

            Trampoline::Transcoder {
                op,
                from,
                from64,
                to,
                to64,
            } => {
                if *from64 || *to64 {
                    unimplemented!("memory 64 transcoder");
                }
                let from = from.as_u32();
                let to = to.as_u32();
                match op {
                    Transcode::Copy(FixedEncoding::Utf8) => {
                        uwriteln!(
                            self.src.js,
                            r#"
                              function trampoline{i} (from_ptr, len, to_ptr) {{
                                  new Uint8Array(memory{to}.buffer, to_ptr, len).set(new Uint8Array(memory{from}.buffer, from_ptr, len));
                              }}
                            "#
                        );
                    }
                    Transcode::Copy(FixedEncoding::Utf16) => unimplemented!("utf16 copier"),
                    Transcode::Copy(FixedEncoding::Latin1) => unimplemented!("latin1 copier"),
                    Transcode::Latin1ToUtf16 => unimplemented!("latin to utf16 transcoder"),
                    Transcode::Latin1ToUtf8 => unimplemented!("latin to utf8 transcoder"),
                    Transcode::Utf16ToCompactProbablyUtf16 => {
                        unimplemented!("utf16 to compact wtf16 transcoder")
                    }
                    Transcode::Utf16ToCompactUtf16 => {
                        unimplemented!("utf16 to compact utf16 transcoder")
                    }
                    Transcode::Utf16ToLatin1 => unimplemented!("utf16 to latin1 transcoder"),
                    Transcode::Utf16ToUtf8 => {
                        uwriteln!(
                            self.src.js,
                            r#"
                              function trampoline{i} (src, src_len, dst, dst_len) {{
                                  const encoder = new TextEncoder();
                                  const {{ read, written }} = encoder.encodeInto(String.fromCharCode.apply(null, new Uint16Array(memory{from}.buffer, src, src_len)), new Uint8Array(memory{to}.buffer, dst, dst_len));
                                  return [read, written];
                              }}
                            "#,
                        );
                    }
                    Transcode::Utf8ToCompactUtf16 => {
                        unimplemented!("utf8 to compact utf16 transcoder")
                    }
                    Transcode::Utf8ToLatin1 => unimplemented!("utf8 to latin1 transcoder"),
                    Transcode::Utf8ToUtf16 => {
                        uwriteln!(
                            self.src.js,
                            r#"
                              function trampoline{i} (from_ptr, len, to_ptr) {{
                                  const decoder = new TextDecoder();
                                  const content = decoder.decode(new Uint8Array(memory{from}.buffer, from_ptr, len));
                                  const strlen = content.length
                                  const view = new Uint16Array(memory{to}.buffer, to_ptr, strlen * 2)
                                  for (var i = 0; i < strlen; i++) {{
                                      view[i] = content.charCodeAt(i);
                                  }}
                                  return strlen;
                              }}
                            "#,
                        );
                    }
                };
            }

            Trampoline::ResourceNew {
                ty: resource_ty_idx,
                ..
            } => {
                self.ensure_resource_table(*resource_ty_idx);
                let rid = resource_ty_idx.as_u32();
                let rsc_table_create_own = self.bindgen.intrinsic(Intrinsic::Resource(
                    ResourceIntrinsic::ResourceTableCreateOwn,
                ));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {rsc_table_create_own}.bind(null, handleTable{rid});"
                );
            }

            Trampoline::ResourceRep {
                ty: resource_ty_idx,
                ..
            } => {
                self.ensure_resource_table(*resource_ty_idx);
                let rid = resource_ty_idx.as_u32();
                let rsc_flag = self
                    .bindgen
                    .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
                uwriteln!(
                    self.src.js,
                    "function trampoline{i} (handle) {{
                        return handleTable{rid}[(handle << 1) + 1] & ~{rsc_flag};
                    }}"
                );
            }

            Trampoline::ResourceDrop {
                ty: resource_table_ty_idx,
                ..
            } => {
                self.ensure_resource_table(*resource_table_ty_idx);
                let tid = resource_table_ty_idx.as_u32();
                let resource_table_ty = &self.types[*resource_table_ty_idx];
                let resource_ty = resource_table_ty.unwrap_concrete_ty();
                let rid = resource_ty.as_u32();

                // Build the code fragment that encapsulates calling the destructor
                let dtor = if let Some(resource_idx) =
                    self.component.defined_resource_index(resource_ty)
                {
                    let resource_def = self
                        .component
                        .initializers
                        .iter()
                        .find_map(|i| match i {
                            GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
                            _ => None,
                        })
                        .unwrap();

                    // If a destructor index is defined for the resource, call it
                    if let Some(dtor) = &resource_def.dtor {
                        format!(
                            "
                            {}(handleEntry.rep);",
                            self.core_def(dtor)
                        )
                    } else {
                        "".into()
                    }
                } else {
                    // Imported resource is one without a defined resource index.
                    // If it is a captured instance (class instance was created externally so had to
                    // be assigned a rep), and there is a Symbol.dispose handler, call it explicitly
                    // for imported resources when the resource is dropped.
                    // Otherwise if it is an instance without a captured class definition, then
                    // call the low-level bindgen destructor.
                    let symbol_dispose = self.bindgen.intrinsic(Intrinsic::SymbolDispose);
                    let symbol_cabi_dispose = self.bindgen.intrinsic(Intrinsic::SymbolCabiDispose);

                    // previous imports walk should define all imported resources which are accessible
                    if let Some(imported_resource_local_name) =
                        self.bindgen.local_names.try_get(resource_ty)
                    {
                        format!(
                                            "
                            const rsc = captureTable{rid}.get(handleEntry.rep);
                            if (rsc) {{
                                if (rsc[{symbol_dispose}]) rsc[{symbol_dispose}]();
                                captureTable{rid}.delete(handleEntry.rep);
                            }} else if ({imported_resource_local_name}[{symbol_cabi_dispose}]) {{
                                {imported_resource_local_name}[{symbol_cabi_dispose}](handleEntry.rep);
                            }}"
                                        )
                    } else {
                        // If not, then capture / disposal paths are never called
                        format!(
                            "throw new TypeError('unreachable trampoline for resource [{:?}]')",
                            resource_ty
                        )
                    }
                };

                let rsc_table_remove = self
                    .bindgen
                    .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
                uwrite!(
                    self.src.js,
                    "function trampoline{i}(handle) {{
                        const handleEntry = {rsc_table_remove}(handleTable{tid}, handle);
                        if (handleEntry.own) {{
                            {dtor}
                        }}
                    }}
                    ",
                );
            }

            Trampoline::ResourceTransferOwn => {
                let resource_transfer = self
                    .bindgen
                    .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTransferOwn));
                uwriteln!(self.src.js, "const trampoline{i} = {resource_transfer};");
            }

            Trampoline::ResourceTransferBorrow => {
                let resource_transfer =
                    self.bindgen
                        .intrinsic(if self.bindgen.opts.valid_lifting_optimization {
                            Intrinsic::Resource(
                                ResourceIntrinsic::ResourceTransferBorrowValidLifting,
                            )
                        } else {
                            Intrinsic::Resource(ResourceIntrinsic::ResourceTransferBorrow)
                        });
                uwriteln!(self.src.js, "const trampoline{i} = {resource_transfer};");
            }

            Trampoline::ContextSet { instance, slot, .. } => {
                let context_set_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::ContextSet));
                let component_idx = instance.as_u32();
                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = {context_set_fn}.bind(null, {{
                          componentIdx: {component_idx},
                          slot: {slot},
                      }});
                    "#
                );
            }

            Trampoline::ContextGet { instance, slot } => {
                let context_get_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::ContextGet));
                let component_idx = instance.as_u32();
                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = {context_get_fn}.bind(null, {{
                          componentIdx: {component_idx},
                          slot: {slot},
                      }});
                    "#
                );
            }

            Trampoline::TaskReturn {
                results, options, ..
            } => {
                let canon_opts = self
                    .component
                    .options
                    .get(*options)
                    .expect("failed to find options");
                let CanonicalOptions {
                    instance,
                    async_,
                    data_model:
                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
                    callback,
                    post_return,
                    string_encoding,
                    ..
                } = canon_opts
                else {
                    unreachable!("unexpected memory data model during task.return");
                };

                // Validate canonopts
                if realloc.is_some() && memory.is_none() {
                    panic!("memory must be present if realloc is");
                }
                if *async_ && post_return.is_some() {
                    panic!("async and post return must not be specified together");
                }
                if *async_ && callback.is_none() {
                    panic!("callback must be specified for async");
                }
                if let Some(cb_idx) = callback {
                    let cb_fn = &self.types[TypeFuncIndex::from_u32(cb_idx.as_u32())];
                    match self.types[cb_fn.params].types[..] {
                        [InterfaceType::S32, InterfaceType::S32, InterfaceType::S32] => {}
                        _ => panic!("unexpected params for async callback fn"),
                    }
                    match self.types[cb_fn.results].types[..] {
                        [InterfaceType::S32] => {}
                        _ => panic!("unexpected results for async callback fn"),
                    }
                }

                let result_types = &self.types[*results].types;

                // Calculate the number of parameters required to represent the results,
                // and whether they'll be stored in memory
                let result_flat_param_total: usize = result_types
                    .iter()
                    .map(|t| {
                        self.types
                            .canonical_abi(t)
                            .flat_count
                            .map(usize::from)
                            .unwrap_or(0)
                    })
                    .sum();
                let use_direct_params = result_flat_param_total < MAX_ASYNC_FLAT_PARAMS;

                // Build up a list of all the lifting functions that will be needed for the types
                // that are actually being passed through task.return
                let mut lift_fns: Vec<String> = Vec::with_capacity(result_types.len());
                for result_ty in result_types {
                    lift_fns.push(gen_flat_lift_fn_js_expr(self, result_ty, &None));
                }
                let lift_fns_js = format!("[{}]", lift_fns.join(","));

                // Build up a list of all the lowering functions that will be needed for the types
                // that are actually being passed through task.return
                //
                // This is usually only necessary if this task is part of a guest->guest async call
                // (i.e. via prepare & async start call)
                let mut lower_fns: Vec<String> = Vec::with_capacity(result_types.len());
                for result_ty in result_types {
                    lower_fns.push(gen_flat_lower_fn_js_expr(self, result_ty, &None));
                }
                let lower_fns_js = format!("[{}]", lower_fns.join(","));

                let get_memory_fn_js = memory
                    .map(|idx| format!("() => memory{}", idx.as_u32()))
                    .unwrap_or_else(|| "() => null".into());
                let memory_idx_js = memory
                    .map(|idx| idx.as_u32().to_string())
                    .unwrap_or_else(|| "null".into());
                let component_idx = instance.as_u32();
                let task_return_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::TaskReturn));
                let callback_fn_idx = callback
                    .map(|v| v.as_u32().to_string())
                    .unwrap_or_else(|| "null".into());
                let string_encoding_js = string_encoding_js_literal(string_encoding);

                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {task_return_fn}.bind(
                         null,
                         {{
                             componentIdx: {component_idx},
                             useDirectParams: {use_direct_params},
                             getMemoryFn: {get_memory_fn_js},
                             memoryIdx: {memory_idx_js},
                             callbackFnIdx: {callback_fn_idx},
                             liftFns: {lift_fns_js},
                             lowerFns: {lower_fns_js},
                             stringEncoding: {string_encoding_js},
                         }},
                     );",
                );
            }

            Trampoline::BackpressureInc { instance } => {
                let backpressure_inc_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Component(ComponentIntrinsic::BackpressureInc));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {backpressure_inc_fn}.bind(null, {instance});\n",
                    instance = instance.as_u32(),
                );
            }

            Trampoline::BackpressureDec { instance } => {
                let backpressure_dec_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::Component(ComponentIntrinsic::BackpressureDec));
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {backpressure_dec_fn}.bind(null, {instance});\n",
                    instance = instance.as_u32(),
                );
            }

            Trampoline::ThreadYield {
                cancellable,
                instance,
            } => {
                let yield_fn = self
                    .bindgen
                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::Yield));
                let component_instance_idx = instance.as_u32();
                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = {yield_fn}.bind(null, {{
                          isCancellable: {cancellable},
                          componentIdx: {component_instance_idx},
                      }});
                    "#,
                );
            }
            Trampoline::ThreadIndex => todo!("Trampoline::ThreadIndex"),
            Trampoline::ThreadNewIndirect { .. } => todo!("Trampoline::ThreadNewIndirect"),
            Trampoline::ThreadSuspend { .. } => todo!("Trampoline::ThreadSuspend"),
            Trampoline::ThreadSuspendTo { .. } => todo!("Trampoline::ThreadSuspendTo"),
            Trampoline::ThreadUnsuspend { .. } => todo!("Trampoline::ThreadUnsuspend"),
            Trampoline::ThreadYieldToSuspended { .. } => {
                todo!("Trampoline::ThreadYieldToSuspended")
            }
            Trampoline::ThreadSuspendToSuspended { .. } => {
                todo!("Trampoline::ThreadYieldToSuspended")
            }

            Trampoline::Trap => {
                uwriteln!(
                    self.src.js,
                    "function trampoline{i}(rep) {{ throw new TypeError('Trap'); }}"
                );
            }

            Trampoline::EnterSyncCall => {
                let enter_symmetric_sync_guest_call_fn = self.bindgen.intrinsic(
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::EnterSymmetricSyncGuestCall),
                );
                uwriteln!(
                    self.src.js,
                    r#"
                      const trampoline{i} = {enter_symmetric_sync_guest_call_fn};
                    "#,
                );
            }

            Trampoline::ExitSyncCall => {
                let exit_symmetric_sync_guest_call_fn = self.bindgen.intrinsic(
                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::ExitSymmetricSyncGuestCall),
                );
                uwriteln!(
                    self.src.js,
                    "const trampoline{i} = {exit_symmetric_sync_guest_call_fn};\n",
                );
            }
        }
    }

    fn instantiation_global_initializer(&mut self, init: &GlobalInitializer) {
        match init {
            // Extracting callbacks is a part of the async support for hosts -- it ensures that
            // a given core export can be turned into a callback function that will be used
            // later.
            //
            // Generally what we have to do here is to create a callback that can be called upon re-entrance
            // into the component after a related suspension.
            GlobalInitializer::ExtractCallback(ExtractCallback { index, def }) => {
                let callback_idx = index.as_u32();
                let core_def = self.core_def(def);

                uwriteln!(self.src.js, "let callback_{callback_idx};",);

                // If the function returns an async value like a stream or future,
                // the callback that is executed in the the event loop (`AsyncTaskIntrinsic::DriverLoop`)
                // may attempt to wait due to calling necessarily async host imports like {stream, future}.{write, read}.
                //
                // Here, we mark the task with an indicator that denotes whether the callback should be run this way.
                //
                // TODO: can we be more selective here rather than wrapping every callback in WebAssembly.promising?
                // every callback *could* do stream.write, but many may not.
                uwriteln!(
                    self.src.js_init,
                    r#"
                      callback_{callback_idx} = WebAssembly.promising({core_def});
                      callback_{callback_idx}.fnName = "{core_def}";
                    "#
                );
            }

            GlobalInitializer::InstantiateModule(m, instance) => match m {
                InstantiateModule::Static(idx, args) => {
                    self.instantiate_static_module(*idx, args, *instance);
                }
                // This is only needed when instantiating an imported core wasm
                // module which while easy to implement here is not possible to
                // test at this time so it's left unimplemented.
                InstantiateModule::Import(..) => unimplemented!(),
            },

            GlobalInitializer::LowerImport { index, import } => {
                self.lower_import(*index, *import);
            }

            GlobalInitializer::ExtractMemory(m) => {
                let def = self.core_export_var_name(&m.export);
                let idx = m.index.as_u32();
                uwriteln!(self.src.js, "let memory{idx};");
                uwriteln!(self.src.js_init, "memory{idx} = {def};");
            }

            GlobalInitializer::ExtractRealloc(r) => {
                let def = self.core_def(&r.def);
                let idx = r.index.as_u32();
                uwriteln!(self.src.js, "let realloc{idx};");
                uwriteln!(self.src.js, "let realloc{idx}Async;");
                uwriteln!(self.src.js_init, "realloc{idx} = {def};",);
                // NOTE: sometimes we may be fed a realloc that isn't a webassembly function at all
                // but has instead been converted to JS (see 'flavorful' test in test/runtime.js')
                uwriteln!(
                    self.src.js_init,
                    r#"
                      try {{
                          realloc{idx}Async = WebAssembly.promising({def});
                      }} catch(err) {{
                          realloc{idx}Async = {def};
                      }}
                    "#
                );
            }

            GlobalInitializer::ExtractPostReturn(p) => {
                let def = self.core_def(&p.def);
                let idx = p.index.as_u32();
                uwriteln!(self.src.js, "let postReturn{idx};");
                uwriteln!(self.src.js, "let postReturn{idx}Async;");
                uwriteln!(self.src.js_init, "postReturn{idx} = {def};");
                // NOTE: sometimes we may be fed a post return fn that isn't a webassembly function
                // at all but has instead been converted to JS (see 'flavorful' test in test/runtime.js)
                uwriteln!(
                    self.src.js_init,
                    r#"
                      try {{
                          postReturn{idx}Async = WebAssembly.promising({def});
                      }} catch(err) {{
                          postReturn{idx}Async = {def};
                      }}
                    "#
                );
            }

            GlobalInitializer::Resource(_) => {}

            GlobalInitializer::ExtractTable(_) => {}
        }
    }

    fn instantiate_static_module(
        &mut self,
        module_idx: StaticModuleIndex,
        args: &[CoreDef],
        instance: Option<RuntimeComponentInstanceIndex>,
    ) {
        // Build a JS "import object" which represents `args`. The `args` is a
        // flat representation which needs to be zip'd with the list of names to
        // correspond to the JS wasm embedding API. This is one of the major
        // differences between Wasmtime's and JS's embedding API.
        let mut import_obj = BTreeMap::new();
        for (module, name, arg) in self.modules[module_idx].imports(args) {
            let def = self.augmented_import_def(&arg);
            let dst = import_obj.entry(module).or_insert(BTreeMap::new());
            let prev = dst.insert(name, def);
            assert!(
                prev.is_none(),
                "unsupported duplicate import of `{module}::{name}`"
            );
            assert!(prev.is_none());
        }

        if self.bindgen.opts.asmjs {
            let component_instance_idx = instance
                .expect("missing runtime component index during static module instantiation")
                .as_u32();

            self.add_intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask));
            self.add_intrinsic(Intrinsic::GetGlobalCurrentTaskMetaFn);
            let current_task_get_fn =
                Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask).name();
            let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();

            let dst = import_obj.entry("env").or_insert(BTreeMap::new());
            let prev = dst.insert(
                "setTempRet0",
                format!(
                    "(x) => {{
                const {{ taskID }} = {get_global_current_task_meta_fn}({component_instance_idx});

                const taskMeta = {current_task_get_fn}({component_instance_idx}, taskID);
                if (!taskMeta) {{ throw new Error('invalid/missing async task meta'); }}

                const task = taskMeta.task;
                if (!task) {{ throw new Error('invalid/missing async task'); }}

                task.tmpRetI64HighBits = x|0;
            }}"
                ),
            );
            assert!(
                prev.is_none(),
                "unsupported duplicate import of `env::setTempRet0`"
            );
            assert!(prev.is_none());
        }

        // Build list of imports
        let mut imports = String::new();
        if !import_obj.is_empty() {
            imports.push_str(", {\n");
            for (module, names) in import_obj {
                imports.push_str(&maybe_quote_id(module));
                imports.push_str(": {\n");
                for (name, val) in names {
                    imports.push_str(&maybe_quote_id(name));
                    uwriteln!(imports, ": {val},");
                }
                imports.push_str("},\n");
            }
            imports.push('}');
        }

        let i = self.instances.push(module_idx);
        let iu32 = i.as_u32();
        let instantiate = self.bindgen.intrinsic(Intrinsic::InstantiateCore);
        uwriteln!(self.src.js, "let exports{iu32};");

        match self.bindgen.opts.instantiation {
            Some(InstantiationMode::Async) | None => {
                uwriteln!(
                    self.src.js_init,
                    "({{ exports: exports{iu32} }} = yield {instantiate}(yield module{}{imports}));",
                    module_idx.as_u32(),
                )
            }

            Some(InstantiationMode::Sync) => {
                uwriteln!(
                    self.src.js_init,
                    "({{ exports: exports{iu32} }} = {instantiate}(module{}{imports}));",
                    module_idx.as_u32(),
                );
            }
        }
    }

    /// Map all types in parameters and results to local resource types
    ///
    /// # Arguments
    ///
    /// * `func` - The function in question
    /// * `ty_func_idx` - Type index of the function
    /// * `resource_map` - resource map of locally resolved types
    fn create_resource_fn_map(
        &mut self,
        func: &Function,
        ty_func_idx: TypeFuncIndex,
        resource_map: &mut ResourceMap,
    ) {
        // Connect resources used in parameters
        let params_ty = &self.types[self.types[ty_func_idx].params];
        for (p, iface_ty) in func.params.iter().zip(params_ty.types.iter()) {
            if let Type::Id(id) = p.ty {
                self.connect_resource_types(id, iface_ty, resource_map);
            }
        }
        // Connect resources used in results
        let results_ty = &self.types[self.types[ty_func_idx].results];
        if let (Some(Type::Id(id)), Some(iface_ty)) = (func.result, results_ty.types.first()) {
            self.connect_resource_types(id, iface_ty, resource_map);
        }
    }

    fn resource_name(
        resolve: &Resolve,
        local_names: &'a mut LocalNames,
        resource: TypeId,
        resource_map: &BTreeMap<TypeId, ResourceIndex>,
    ) -> &'a str {
        let resource = crate::dealias(resolve, resource);
        local_names
            .get_or_create(
                resource_map[&resource],
                &resolve.types[resource]
                    .name
                    .as_ref()
                    .unwrap()
                    .to_upper_camel_case(),
            )
            .0
    }

    fn lower_import(&mut self, index: LoweredIndex, import: RuntimeImportIndex) {
        let (options, trampoline, func_ty) = self.lowering_options[index];

        // Get the world key for the CM import
        let (import_index, path) = &self.component.imports[import];
        let (import_name, _) = &self.component.import_types[*import_index];
        let world_key = &self.imports[import_name];

        // Determine the name of the function
        let (func, func_name, iface_name) =
            match &self.resolve.worlds[self.world].imports[world_key] {
                WorldItem::Function(func) => {
                    assert_eq!(path.len(), 0);
                    (func, import_name, None)
                }
                WorldItem::Interface { id, .. } => {
                    assert_eq!(path.len(), 1);
                    let iface = &self.resolve.interfaces[*id];
                    let func = &iface.functions[&path[0]];
                    (
                        func,
                        &path[0],
                        Some(iface.name.as_deref().unwrap_or_else(|| import_name)),
                    )
                }
                WorldItem::Type { .. } => unreachable!("unexpected imported world item type"),
            };

        let is_async = is_async_fn(func, options);

        if options.async_ {
            assert!(
                options.post_return.is_none(),
                "async function {func_name} (import {import_name}) can't have post return",
            );
        }

        // Host lifted async import (i.e. JSPI)
        let requires_async_porcelain = requires_async_porcelain(
            FunctionIdentifier::Fn(func),
            import_name,
            &self.async_imports,
        );

        // Nested interfaces only currently possible through mapping
        let (import_specifier, maybe_iface_member) = map_import(
            &self.bindgen.opts.map,
            if iface_name.is_some() {
                import_name
            } else {
                match func.kind {
                    FunctionKind::Method(_) => {
                        let stripped = import_name.strip_prefix("[method]").unwrap();
                        &stripped[0..stripped.find(".").unwrap()]
                    }
                    FunctionKind::AsyncMethod(_) => {
                        let stripped = import_name.strip_prefix("[async method]").unwrap();
                        &stripped[0..stripped.find(".").unwrap()]
                    }
                    FunctionKind::Static(_) => {
                        let stripped = import_name.strip_prefix("[static]").unwrap();
                        &stripped[0..stripped.find(".").unwrap()]
                    }
                    FunctionKind::AsyncStatic(_) => {
                        let stripped = import_name.strip_prefix("[async static]").unwrap();
                        &stripped[0..stripped.find(".").unwrap()]
                    }
                    FunctionKind::Constructor(_) => {
                        import_name.strip_prefix("[constructor]").unwrap()
                    }
                    FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => import_name,
                }
            },
        );

        // Create mappings for resources
        let mut import_resource_map = ResourceMap::new();

        self.create_resource_fn_map(func, func_ty, &mut import_resource_map);

        let (callee_name, call_type) = match func.kind {
            FunctionKind::Freestanding => (
                self.bindgen
                    .local_names
                    .get_or_create(
                        format!(
                            "import:{import}-{maybe_iface_member}-{func_name}",
                            import = import_specifier,
                            maybe_iface_member = maybe_iface_member.as_deref().unwrap_or(""),
                            func_name = &func.name
                        ),
                        &func.name,
                    )
                    .0
                    .to_string(),
                CallType::Standard,
            ),

            FunctionKind::AsyncFreestanding => (
                self.bindgen
                    .local_names
                    .get_or_create(
                        format!(
                            "import:async-{import}-{maybe_iface_member}-{func_name}",
                            import = import_specifier,
                            maybe_iface_member = maybe_iface_member.as_deref().unwrap_or(""),
                            func_name = &func.name
                        ),
                        &func.name,
                    )
                    .0
                    .to_string(),
                CallType::AsyncStandard,
            ),

            FunctionKind::Method(_) => (
                func.item_name().to_lower_camel_case(),
                CallType::CalleeResourceDispatch,
            ),

            FunctionKind::AsyncMethod(_) => (
                func.item_name().to_lower_camel_case(),
                CallType::AsyncCalleeResourceDispatch,
            ),

            FunctionKind::Static(resource_id) => (
                format!(
                    "{}.{}",
                    Instantiator::resource_name(
                        self.resolve,
                        &mut self.bindgen.local_names,
                        resource_id,
                        &self.imports_resource_types
                    ),
                    func.item_name().to_lower_camel_case()
                ),
                CallType::Standard,
            ),

            FunctionKind::AsyncStatic(resource_id) => (
                format!(
                    "{}.{}",
                    Instantiator::resource_name(
                        self.resolve,
                        &mut self.bindgen.local_names,
                        resource_id,
                        &self.imports_resource_types
                    ),
                    func.item_name().to_lower_camel_case()
                ),
                CallType::AsyncStandard,
            ),

            FunctionKind::Constructor(resource_id) => (
                format!(
                    "new {}",
                    Instantiator::resource_name(
                        self.resolve,
                        &mut self.bindgen.local_names,
                        resource_id,
                        &self.imports_resource_types
                    )
                ),
                CallType::Standard,
            ),
        };

        let nparams = self
            .resolve
            .wasm_signature(AbiVariant::GuestImport, func)
            .params
            .len();

        // Generate the JS trampoline function for a bound import
        let trampoline_idx = trampoline.as_u32();
        match self.bindgen.opts.import_bindings {
            None | Some(BindingsMode::Js) | Some(BindingsMode::Hybrid) => {
                // TODO(breaking): remove as we do not not need to manually specify async imports anymore in P3 w/ native coloring
                if is_async | requires_async_porcelain {
                    // NOTE: for async imports that will go through Trampoline::LowerImport,
                    // we prefix the raw import with '_' as it will later be used in the
                    // definition of trampoline{i} which will actually be fed into
                    // unbundled modules
                    uwrite!(
                        self.src.js,
                        "\nconst _trampoline{trampoline_idx} = async function"
                    );
                } else {
                    uwrite!(
                        self.src.js,
                        "\nconst _trampoline{trampoline_idx} = function"
                    );
                }

                let iface_name = if import_name.is_empty() {
                    None
                } else {
                    Some(import_name.to_string())
                };

                // Write out the function (brace + body + brace)
                self.bindgen(JsFunctionBindgenArgs {
                    nparams,
                    call_type,
                    iface_name: iface_name.as_deref(),
                    callee: &callee_name,
                    opts: options,
                    func,
                    resource_map: &import_resource_map,
                    abi: AbiVariant::GuestImport,
                    requires_async_porcelain,
                    is_async,
                });
                uwriteln!(self.src.js, "");

                uwriteln!(
                    self.src.js,
                    "_trampoline{trampoline_idx}.fnName = '{}#{callee_name}';",
                    iface_name.unwrap_or_default(),
                );

                // TODO(breaking): remove once support for manually specified async imports is removed
                if requires_async_porcelain {
                    uwriteln!(
                        self.src.js,
                        "_trampoline{trampoline_idx}.manuallyAsync = true;"
                    );
                }
            }

            Some(BindingsMode::Optimized) | Some(BindingsMode::DirectOptimized) => {
                uwriteln!(self.src.js, "let trampoline{trampoline_idx};");
            }
        };

        // Build import bindings & trampolines for the import
        //
        // This is only necessary if an import binding mode is specified and not JS (the default),
        // (e.g. Optimized, Direct, Hybrid).
        if !matches!(
            self.bindgen.opts.import_bindings,
            None | Some(BindingsMode::Js)
        ) {
            let (memory, realloc) =
                if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
                    memory,
                    realloc,
                }) = options.data_model
                {
                    (
                        memory.map(|idx| format!(" memory: memory{},", idx.as_u32())),
                        realloc.map(|idx| format!(" realloc: realloc{},", idx.as_u32())),
                    )
                } else {
                    (None, None)
                };
            let memory = memory.unwrap_or_default();
            let realloc = realloc.unwrap_or_default();

            let post_return = options
                .post_return
                .map(|idx| format!(" postReturn: postReturn{},", idx.as_u32()))
                .unwrap_or("".into());
            let string_encoding = match options.string_encoding {
                wasmtime_environ::component::StringEncoding::Utf8 => "",
                wasmtime_environ::component::StringEncoding::Utf16 => " stringEncoding: 'utf16',",
                wasmtime_environ::component::StringEncoding::CompactUtf16 => {
                    " stringEncoding: 'compact-utf16',"
                }
            };

            let callee_name = match func.kind {
                FunctionKind::Constructor(_) => callee_name[4..].to_string(),

                FunctionKind::Static(_)
                | FunctionKind::AsyncStatic(_)
                | FunctionKind::Freestanding
                | FunctionKind::AsyncFreestanding => callee_name.to_string(),

                FunctionKind::Method(resource_id) | FunctionKind::AsyncMethod(resource_id) => {
                    format!(
                        "{}.prototype.{callee_name}",
                        Instantiator::resource_name(
                            self.resolve,
                            &mut self.bindgen.local_names,
                            resource_id,
                            &self.imports_resource_types
                        )
                    )
                }
            };

            // Save information about imported resources for later
            self.resource_imports.extend(import_resource_map.clone());

            let resource_tables = {
                let mut resource_table_ids: Vec<TypeResourceTableIndex> = Vec::new();

                for (_, data) in import_resource_map {
                    let ResourceTable {
                        data: ResourceData::Host { tid, .. },
                        ..
                    } = &data
                    else {
                        unreachable!("unexpected non-host resource table");
                    };
                    resource_table_ids.push(*tid);
                }

                if resource_table_ids.is_empty() {
                    "".to_string()
                } else {
                    format!(
                        " resourceTables: [{}],",
                        resource_table_ids
                            .iter()
                            .map(|x| format!("handleTable{}", x.as_u32()))
                            .collect::<Vec<String>>()
                            .join(", ")
                    )
                }
            };

            // Build trampolines for the import
            match self.bindgen.opts.import_bindings {
                Some(BindingsMode::Hybrid) => {
                    let symbol_cabi_lower = self.bindgen.intrinsic(Intrinsic::SymbolCabiLower);
                    uwriteln!(self.src.js_init, "if ({callee_name}[{symbol_cabi_lower}]) {{
                        trampoline{} = {callee_name}[{symbol_cabi_lower}]({{{memory}{realloc}{post_return}{string_encoding}{resource_tables}}});
                    }}", trampoline.as_u32());
                }
                Some(BindingsMode::Optimized) => {
                    let symbol_cabi_lower = self.bindgen.intrinsic(Intrinsic::SymbolCabiLower);
                    if !self.bindgen.opts.valid_lifting_optimization {
                        uwriteln!(self.src.js_init, "if (!{callee_name}[{symbol_cabi_lower}]) {{
                            throw new TypeError('import for \"{import_name}\" does not define a Symbol.for(\"cabiLower\") optimized binding');
                        }}");
                    }
                    uwriteln!(
                        self.src.js_init,
                        "trampoline{} = {callee_name}[{symbol_cabi_lower}]({{{memory}{realloc}{post_return}{string_encoding}{resource_tables}}});",
                        trampoline.as_u32()
                    );
                }
                Some(BindingsMode::DirectOptimized) => {
                    uwriteln!(
                        self.src.js_init,
                        "trampoline{} = {callee_name}({{{memory}{realloc}{post_return}{string_encoding}}});",
                        trampoline.as_u32()
                    );
                }
                None | Some(BindingsMode::Js) => unreachable!("invalid bindings mode"),
            };
        }

        // Figure out the function name and callee (e.g. class for a given resource) to use
        let (import_name, binding_name) = match func.kind {
            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
                (func_name.to_lower_camel_case(), callee_name)
            }

            FunctionKind::Method(tid)
            | FunctionKind::AsyncMethod(tid)
            | FunctionKind::Static(tid)
            | FunctionKind::AsyncStatic(tid)
            | FunctionKind::Constructor(tid) => {
                let ty = &self.resolve.types[tid];
                let class_name = ty.name.as_ref().unwrap().to_upper_camel_case();
                let resource_name = Instantiator::resource_name(
                    self.resolve,
                    &mut self.bindgen.local_names,
                    tid,
                    &self.imports_resource_types,
                )
                .to_string();
                (class_name, resource_name)
            }
        };

        self.ensure_import(
            import_specifier,
            iface_name,
            maybe_iface_member.as_deref(),
            if iface_name.is_some() {
                Some(import_name.to_string())
            } else {
                None
            },
            binding_name,
        );
    }

    /// Process an import if it has not already been processed
    ///
    /// # Arguments
    ///
    /// * `import_specifier` - The specifier of the import as used in JS (ex. `"@bytecodealliance/preview2-shim/random"`)
    /// * `iface_name` - The name of the WIT interface related to this binding, if present (ex. `"random"`)
    /// * `iface_member` - The name of the interface member, if present (ex. `"random"`)
    /// * `import_binding` - The name of binding, if present (ex. `"getRandomBytes"`)
    /// * `local_name` - Local name of the import (ex. `"getRandomBytes"`)
    ///
    fn ensure_import(
        &mut self,
        import_specifier: String,
        iface_name: Option<&str>,
        iface_member: Option<&str>,
        import_binding: Option<String>,
        local_name: String,
    ) {
        if import_specifier.starts_with("webidl:") {
            self.bindgen
                .intrinsic(Intrinsic::WebIdl(WebIdlIntrinsic::GlobalThisIdlProxy));
        }

        // Build the import path depending on the kind of interface
        let mut import_path = Vec::with_capacity(2);
        import_path.push(import_specifier);
        if let Some(_iface_name) = iface_name {
            // Mapping can be used to construct virtual nested namespaces
            // which is used eg to support WASI interface groupings
            if let Some(iface_member) = iface_member {
                import_path.push(iface_member.to_lower_camel_case());
            }
            import_path.push(import_binding.clone().unwrap());
        } else if let Some(iface_member) = iface_member {
            import_path.push(iface_member.into());
        } else if let Some(import_binding) = &import_binding {
            import_path.push(import_binding.into());
        }

        // Add the import binding that represents this import
        self.bindgen
            .esm_bindgen
            .add_import_binding(&import_path, local_name);
    }

    /// Connect resources that have no types
    ///
    /// Commonly this is used for resources that have a type on on the import side
    /// but no relevant type on the receiving side, for which local types must be generated locally:
    /// - `error-context`
    /// - `future<_>`
    /// - `stream<_>`
    ///
    fn connect_p3_resources(
        &mut self,
        id: &TypeId,
        maybe_elem_ty: &Option<Type>,
        iface_ty: &InterfaceType,
        resource_map: &mut ResourceMap,
    ) {
        let remote_resource = match iface_ty {
            InterfaceType::Future(table_idx) => ResourceTable {
                imported: true,
                data: ResourceData::Guest {
                    resource_name: "Future".into(),
                    prefix: Some(format!("${}", table_idx.as_u32())),
                    extra: Some(ResourceExtraData::Future {
                        table_idx: *table_idx,
                        elem_ty: maybe_elem_ty.map(|ty| {
                            let table_ty = &self.types[*table_idx];
                            let future_ty_idx = table_ty.ty;
                            let future_ty = &self.types[future_ty_idx];
                            let iface_ty = future_ty
                                .payload
                                .expect("missing future payload despite elem type being present");
                            let abi = self.types.canonical_abi(&iface_ty);
                            PayloadTypeMetadata {
                                ty,
                                iface_ty,

                                // TODO: we need to use the currently-being-built resource map here,
                                // because it may contain *just inserted* information (could be either imports or exports)
                                // that should be used
                                //
                                // We need to *augment* the normal built in
                                // `instantiator.resource_{exports,imports}` with things that we're resolving now.
                                lift_js_expr: gen_flat_lift_fn_js_expr(
                                    self,
                                    &iface_ty,
                                    &Some(resource_map),
                                ),
                                lower_js_expr: gen_flat_lower_fn_js_expr(
                                    self,
                                    &iface_ty,
                                    &Some(resource_map),
                                ),
                                size32: abi.size32,
                                align32: abi.align32,
                                flat_count: abi.flat_count,
                            }
                        }),
                    }),
                },
            },
            InterfaceType::Stream(table_idx) => ResourceTable {
                imported: true,
                data: ResourceData::Guest {
                    resource_name: "Stream".into(),
                    prefix: Some(format!("${}", table_idx.as_u32())),
                    extra: Some(ResourceExtraData::Stream {
                        table_idx: *table_idx,
                        elem_ty: maybe_elem_ty.map(|ty| {
                            let table_ty = &self.types[*table_idx];
                            let stream_ty_idx = table_ty.ty;
                            let stream_ty = &self.types[stream_ty_idx];
                            let iface_ty = stream_ty
                                .payload
                                .expect("missing payload despite elem type being present");
                            let abi = self.types.canonical_abi(&iface_ty);
                            PayloadTypeMetadata {
                                ty,
                                iface_ty,
                                lift_js_expr: gen_flat_lift_fn_js_expr(
                                    self,
                                    &iface_ty,
                                    &Some(resource_map),
                                ),
                                lower_js_expr: gen_flat_lower_fn_js_expr(
                                    self,
                                    &iface_ty,
                                    &Some(resource_map),
                                ),
                                size32: abi.size32,
                                align32: abi.align32,
                                flat_count: abi.flat_count,
                            }
                        }),
                    }),
                },
            },
            InterfaceType::ErrorContext(table_idx) => ResourceTable {
                imported: true,
                data: ResourceData::Guest {
                    resource_name: "ErrorContext".into(),
                    prefix: Some(format!("${}", table_idx.as_u32())),
                    extra: Some(ResourceExtraData::ErrorContext {
                        table_idx: *table_idx,
                    }),
                },
            },
            _ => unreachable!("unexpected interface type [{iface_ty:?}] with no type"),
        };

        resource_map.insert(*id, remote_resource);
    }

    /// Connect two types as host resources
    ///
    /// # Arguments
    ///
    /// * `t` - the TypeId
    /// * `tid` - Index into the type resource table of the interface (foreign side)
    /// * `resource_map` - Resource map that holds resource pairings
    ///
    fn connect_host_resource(
        &mut self,
        t: TypeId,
        resource_table_ty_idx: TypeResourceTableIndex,
        resource_map: &mut ResourceMap,
    ) {
        self.ensure_resource_table(resource_table_ty_idx);

        // Figure out whether the resource index we're dealing with is for an imported type
        let resource_table_ty = &self.types[resource_table_ty_idx];
        let resource_idx = resource_table_ty.unwrap_concrete_ty();
        let imported = self
            .component
            .defined_resource_index(resource_idx)
            .is_none();

        // Retrieve the resource id for the type definition
        let resource_id = crate::dealias(self.resolve, t);
        let ty = &self.resolve.types[resource_id];

        // If the resource is defined by this component (i.e. exported/used internally, *not* imported),
        // then determine the destructor that should be run based on the relevant resource
        let mut dtor_str = None;
        if let Some(resource_idx) = self.component.defined_resource_index(resource_idx) {
            assert!(!imported);
            let resource_def = self
                .component
                .initializers
                .iter()
                .find_map(|i| match i {
                    GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
                    _ => None,
                })
                .unwrap();

            if let Some(dtor) = &resource_def.dtor {
                dtor_str = Some(self.core_def(dtor));
            }
        }

        // Look up the local import name
        let resource_name = ty.name.as_ref().unwrap().to_upper_camel_case();

        let local_name = if imported {
            let (world_key, iface_name) = match ty.owner {
                wit_parser::TypeOwner::World(world) => (
                    self.resolve.worlds[world]
                        .imports
                        .iter()
                        .find(|&(_, item)| matches!(*item, WorldItem::Type { id, .. } if id == t))
                        .unwrap()
                        .0
                        .clone(),
                    None,
                ),
                wit_parser::TypeOwner::Interface(iface) => {
                    match &self.resolve.interfaces[iface].name {
                        Some(name) => (WorldKey::Interface(iface), Some(name.as_str())),
                        None => {
                            let key = self.resolve.worlds[self.world]
                                .imports
                                .iter()
                                .find(|&(_, item)| match item {
                                    WorldItem::Interface { id, .. } => *id == iface,
                                    _ => false,
                                })
                                .unwrap()
                                .0;
                            (
                                key.clone(),
                                match key {
                                    WorldKey::Name(name) => Some(name.as_str()),
                                    WorldKey::Interface(_) => None,
                                },
                            )
                        }
                    }
                }
                wit_parser::TypeOwner::None => unimplemented!(),
            };

            let import_name = self.resolve.name_world_key(&world_key);
            let (local_name, _) = self
                .bindgen
                .local_names
                .get_or_create(resource_idx, &resource_name);

            let local_name_str = local_name.to_string();

            // Nested interfaces only currently possible through mapping
            let (import_specifier, maybe_iface_member) =
                map_import(&self.bindgen.opts.map, &import_name);

            // Ensure that the import exists
            self.ensure_import(
                import_specifier,
                iface_name,
                maybe_iface_member.as_deref(),
                iface_name.map(|_| resource_name),
                local_name_str.to_string(),
            );
            local_name_str
        } else {
            let (local_name, _) = self
                .bindgen
                .local_names
                .get_or_create(resource_idx, &resource_name);
            local_name.to_string()
        };

        // Add a resource table to track the host resource
        let entry = ResourceTable {
            imported,
            data: ResourceData::Host {
                tid: resource_table_ty_idx,
                rid: resource_idx,
                local_name,
                dtor_name: dtor_str,
            },
        };

        // If the the resource already exists, then  ensure that it is exactly the same as the
        // value we're attempting to insert
        if let Some(existing) = resource_map.get(&resource_id) {
            assert_eq!(*existing, entry);
            return;
        }

        // Insert the resource into the map,
        resource_map.insert(resource_id, entry);
    }

    /// Connect resources that are defined at the type levels in `wit-parser`
    /// to their types as defined in `wasmtime-environ`
    ///
    /// The types that are connected here are stored in the `resource_map` for
    /// use later.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the type if present (can be missing when dealing with `error-context`s, `future<_>`, etc)
    /// * `iface_ty` - The relevant interface type
    /// * `resource_map` - Resource map that we will update with pairings
    ///
    fn connect_resource_types(
        &mut self,
        id: TypeId,
        iface_ty: &InterfaceType,
        resource_map: &mut ResourceMap,
    ) {
        let kind = &self.resolve.types[id].kind;
        match (kind, iface_ty) {
            // For flags and enums we can do nothing -- they're simple values (string/number)
            (TypeDefKind::Flags(_), InterfaceType::Flags(_))
            | (TypeDefKind::Enum(_), InterfaceType::Enum(_)) => {}

            // Connect records to records
            (TypeDefKind::Record(t1), InterfaceType::Record(t2)) => {
                let t2 = &self.types[*t2];
                for (f1, f2) in t1.fields.iter().zip(t2.fields.iter()) {
                    if let Type::Id(id) = f1.ty {
                        self.connect_resource_types(id, &f2.ty, resource_map);
                    }
                }
            }

            // Handle connecting owned/borrowed handles to owned/borrowed handles
            (
                TypeDefKind::Handle(Handle::Own(t1) | Handle::Borrow(t1)),
                InterfaceType::Own(t2) | InterfaceType::Borrow(t2),
            ) => {
                self.connect_host_resource(*t1, *t2, resource_map);
            }

            // Connect tuples to interface tuples
            (TypeDefKind::Tuple(t1), InterfaceType::Tuple(t2)) => {
                let t2 = &self.types[*t2];
                for (f1, f2) in t1.types.iter().zip(t2.types.iter()) {
                    if let Type::Id(id) = f1 {
                        self.connect_resource_types(*id, f2, resource_map);
                    }
                }
            }

            // Connect inner types of variants to their interface types
            (TypeDefKind::Variant(t1), InterfaceType::Variant(t2)) => {
                let t2 = &self.types[*t2];
                for (f1, f2) in t1.cases.iter().zip(t2.cases.iter()) {
                    if let Some(Type::Id(id)) = &f1.ty {
                        self.connect_resource_types(*id, f2.1.as_ref().unwrap(), resource_map);
                    }
                }
            }

            // Connect option<t> to option<t>
            (TypeDefKind::Option(t1), InterfaceType::Option(t2)) => {
                let t2 = &self.types[*t2];
                if let Type::Id(id) = t1 {
                    self.connect_resource_types(*id, &t2.ty, resource_map);
                }
            }

            // Connect result<t> to result<t>
            (TypeDefKind::Result(t1), InterfaceType::Result(t2)) => {
                let t2 = &self.types[*t2];
                if let Some(Type::Id(id)) = &t1.ok {
                    self.connect_resource_types(*id, &t2.ok.unwrap(), resource_map);
                }
                if let Some(Type::Id(id)) = &t1.err {
                    self.connect_resource_types(*id, &t2.err.unwrap(), resource_map);
                }
            }

            // Connect list<t> to list types
            (TypeDefKind::List(t1), InterfaceType::List(t2)) => {
                let t2 = &self.types[*t2];
                if let Type::Id(id) = t1 {
                    self.connect_resource_types(*id, &t2.element, resource_map);
                }
            }

            // Connect list<t, size> to list types
            (TypeDefKind::FixedLengthList(t1, _len), InterfaceType::FixedLengthList(t2)) => {
                let t2 = &self.types[*t2];
                if let Type::Id(id) = t1 {
                    self.connect_resource_types(*id, &t2.element, resource_map);
                }
            }

            // Connect named types
            (TypeDefKind::Type(ty), _) => {
                if let Type::Id(id) = ty {
                    self.connect_resource_types(*id, iface_ty, resource_map);
                }
            }

            // Connect futures & stream types
            (TypeDefKind::Future(maybe_elem_ty), container_iface_ty)
            | (TypeDefKind::Stream(maybe_elem_ty), container_iface_ty) => {
                match maybe_elem_ty {
                    // The case of an empty future is the propagation of a `null`-like value, usually a simple signal
                    // which we'll connect with the *normally invalid* type value 0 as an indicator
                    None => {
                        self.connect_p3_resources(&id, maybe_elem_ty, iface_ty, resource_map);
                    }
                    // For custom types we must recur to properly connect the inner type
                    Some(elem_ty @ Type::Id(elem_ty_id)) => {
                        // As the internal type could be a resource, and connecting p3 resources
                        // may generate lifting/lowering fns, we must connect the payload of the
                        // future/stream first, if necessary
                        //
                        let maybe_elem_iface_ty = match container_iface_ty {
                            InterfaceType::Future(future_table_ty_idx) => {
                                let future_table_ty = &self.types[*future_table_ty_idx];
                                let future = &self.types[future_table_ty.ty];
                                future.payload
                            }
                            InterfaceType::Stream(stream_table_ty_idx) => {
                                let stream_table_ty = &self.types[*stream_table_ty_idx];
                                let stream = &self.types[stream_table_ty.ty];
                                stream.payload
                            }
                            _ => unreachable!("unexpected iface type"),
                        };
                        if let Some(elem_iface_ty) = maybe_elem_iface_ty {
                            // TODO(refactor): the last arg of `connect_resource_types()` (`extra_resource_map`) is
                            // necessary because we are not building the imports/exports array directly.
                            //
                            // It's a hack that *should* be removable if we do more explicit and intentional
                            // building of import/export resource mappings (i.e. not building a partial map that we
                            // later `.extend()` onto the instantiator's maps, depending on whether we were working on
                            // imports or exports).
                            self.connect_resource_types(*elem_ty_id, &elem_iface_ty, resource_map);
                        }

                        self.connect_p3_resources(&id, &Some(*elem_ty), iface_ty, resource_map);
                    }
                    // For basic types that are connected (non inner types) we can do a generic connect
                    Some(_) => {
                        self.connect_p3_resources(&id, maybe_elem_ty, iface_ty, resource_map);
                    }
                }
            }

            // Connect the types in an ok/error variant of a Result to the future that they're being sent in
            (
                TypeDefKind::Result(Result_ { ok, err }),
                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
            ) => {
                if let Some(Type::Id(ok_t)) = ok {
                    self.connect_resource_types(*ok_t, tk2, resource_map)
                }
                if let Some(Type::Id(err_t)) = err {
                    self.connect_resource_types(*err_t, tk2, resource_map)
                }
            }

            // Connect the types in an option to the future that they're being sent in
            (
                TypeDefKind::Option(ty),
                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
            ) => {
                if let Type::Id(some_t) = ty {
                    self.connect_resource_types(*some_t, tk2, resource_map)
                }
            }

            // Connect resources to the future/stream that they're being sent in
            (
                TypeDefKind::Handle(Handle::Own(t1) | Handle::Borrow(t1)),
                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
            ) => self.connect_resource_types(*t1, tk2, resource_map),

            (TypeDefKind::Resource, InterfaceType::Future(_) | InterfaceType::Stream(_)) => {}

            // Connect the inner types of variants to the future they're being sent in
            (
                TypeDefKind::Variant(variant),
                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
            ) => {
                for f1 in variant.cases.iter() {
                    if let Some(Type::Id(id)) = &f1.ty {
                        self.connect_resource_types(*id, tk2, resource_map);
                    }
                }
            }

            // Connect the inner types of variants to the future they're being sent in
            (
                TypeDefKind::Record(record),
                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
            ) => {
                for f1 in record.fields.iter() {
                    if let Type::Id(id) = f1.ty {
                        self.connect_resource_types(id, tk2, resource_map);
                    }
                }
            }

            // Simliar to the non-stream/future case, we don't have to do anything for
            // flags and plain enums as they are read directly
            (
                TypeDefKind::Enum(_) | TypeDefKind::Flags(_),
                InterfaceType::Future(_) | InterfaceType::Stream(_),
            ) => {}

            (TypeDefKind::Resource, tk2) => {
                unreachable!(
                    "resource types do not need to be connected (in this case, to [{tk2:?}])"
                )
            }

            (TypeDefKind::Unknown, tk2) => {
                unreachable!("unknown types cannot be connected (in this case to [{tk2:?}])")
            }

            (tk1, tk2) => unreachable!("invalid typedef kind combination [{tk1:?}] [{tk2:?}]",),
        }
    }

    fn bindgen(&mut self, args: JsFunctionBindgenArgs) {
        let JsFunctionBindgenArgs {
            nparams,
            call_type,
            iface_name,
            callee,
            opts,
            func,
            resource_map,
            abi,
            requires_async_porcelain,
            is_async,
        } = args;

        let (memory, realloc) =
            if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
                memory,
                realloc,
            }) = opts.data_model
            {
                (
                    memory.map(|idx| format!("memory{}", idx.as_u32())),
                    realloc.map(|idx| {
                        format!(
                            "realloc{}{}",
                            idx.as_u32(),
                            if is_async {
                                "Async"
                            } else {
                                Default::default()
                            }
                        )
                    }),
                )
            } else {
                (None, None)
            };

        let post_return = opts.post_return.map(|idx| {
            format!(
                "postReturn{}{}",
                idx.as_u32(),
                if is_async {
                    "Async"
                } else {
                    Default::default()
                }
            )
        });

        let tracing_prefix = format!(
            "[iface=\"{}\", function=\"{}\"]",
            iface_name.unwrap_or("<no iface>"),
            func.name
        );

        // Write the function argument list
        //
        // At this point, only the function preamble (e.g. 'function nameOfFunc()') has been written
        self.src.js("(");
        let mut params = Vec::new();
        let mut first = true;
        for i in 0..nparams {
            if i == 0
                && matches!(
                    call_type,
                    CallType::FirstArgIsThis | CallType::AsyncFirstArgIsThis
                )
            {
                params.push("this".into());
                continue;
            }
            if !first {
                self.src.js(", ");
            } else {
                first = false;
            }
            let param = format!("arg{i}");
            self.src.js(&param);
            params.push(param);
        }
        uwriteln!(self.src.js, ") {{");

        // If tracing is enabled, output a function entry tracing message
        if self.bindgen.opts.tracing {
            let event_fields = func
                .params
                .iter()
                .enumerate()
                .map(|(i, p)| format!("{}=${{arguments[{i}]}}", p.name))
                .collect::<Vec<String>>();
            uwriteln!(
                self.src.js,
                "console.error(`{tracing_prefix} call {}`);",
                event_fields.join(", ")
            );
        }

        // If TLA compat was enabled, ensure that it was initialized
        if self.bindgen.opts.tla_compat
            && matches!(abi, AbiVariant::GuestExport)
            && self.bindgen.opts.instantiation.is_none()
        {
            let throw_uninitialized = self.bindgen.intrinsic(Intrinsic::ThrowUninitialized);
            uwrite!(
                self.src.js,
                "\
                if (!_initialized) {throw_uninitialized}();
            "
            );
        }

        // Generate function body
        let mut f = FunctionBindgen {
            resource_map,
            clear_resource_borrows: false,
            intrinsics: &mut self.bindgen.all_intrinsics,
            valid_lifting_optimization: self.bindgen.opts.valid_lifting_optimization,
            sizes: &self.sizes,
            err: if get_thrown_type(self.resolve, func.result).is_some() {
                match abi {
                    AbiVariant::GuestExport
                    | AbiVariant::GuestExportAsync
                    | AbiVariant::GuestExportAsyncStackful => ErrHandling::ThrowResultErr,
                    AbiVariant::GuestImport | AbiVariant::GuestImportAsync => {
                        ErrHandling::ResultCatchHandler
                    }
                }
            } else {
                ErrHandling::None
            },
            block_storage: Vec::new(),
            blocks: Vec::new(),
            callee,
            callee_resource_dynamic: matches!(call_type, CallType::CalleeResourceDispatch),
            memory: memory.as_ref(),
            realloc: realloc.as_ref(),
            tmp: 0,
            params,
            post_return: post_return.as_ref(),
            tracing_prefix: &tracing_prefix,
            tracing_enabled: self.bindgen.opts.tracing,
            encoding: match opts.string_encoding {
                wasmtime_environ::component::StringEncoding::Utf8 => StringEncoding::UTF8,
                wasmtime_environ::component::StringEncoding::Utf16 => StringEncoding::UTF16,
                wasmtime_environ::component::StringEncoding::CompactUtf16 => {
                    StringEncoding::CompactUTF16
                }
            },
            src: source::Source::default(),
            resolve: self.resolve,
            requires_async_porcelain,
            is_async,
            canon_opts: opts,
            iface_name,
            asmjs: self.bindgen.opts.asmjs,
        };

        // Emit (and visit, via the `FunctionBindgen` object) an abstract sequence of
        // instructions which represents the function being generated.
        abi::call(
            self.resolve,
            abi,
            match abi {
                AbiVariant::GuestImport | AbiVariant::GuestImportAsync => {
                    LiftLower::LiftArgsLowerResults
                }
                AbiVariant::GuestExport
                | AbiVariant::GuestExportAsync
                | AbiVariant::GuestExportAsyncStackful => LiftLower::LowerArgsLiftResults,
            },
            func,
            &mut f,
            is_async,
        );

        // Once visiting has completed, write the contents the `FunctionBindgen` generated to output
        self.src.js(&f.src);

        // Close function body
        self.src.js("}");
    }

    fn augmented_import_def(&self, def: &core::AugmentedImport<'_>) -> String {
        match def {
            core::AugmentedImport::CoreDef(def) => self.core_def(def),
            core::AugmentedImport::Memory { mem, op } => {
                let mem = self.core_def(mem);
                match op {
                    core::AugmentedOp::I32Load => {
                        format!(
                            "(ptr, off) => new DataView({mem}.buffer).getInt32(ptr + off, true)"
                        )
                    }
                    core::AugmentedOp::I32Load8U => {
                        format!(
                            "(ptr, off) => new DataView({mem}.buffer).getUint8(ptr + off, true)"
                        )
                    }
                    core::AugmentedOp::I32Load8S => {
                        format!("(ptr, off) => new DataView({mem}.buffer).getInt8(ptr + off, true)")
                    }
                    core::AugmentedOp::I32Load16U => {
                        format!(
                            "(ptr, off) => new DataView({mem}.buffer).getUint16(ptr + off, true)"
                        )
                    }
                    core::AugmentedOp::I32Load16S => {
                        format!(
                            "(ptr, off) => new DataView({mem}.buffer).getInt16(ptr + off, true)"
                        )
                    }
                    core::AugmentedOp::I64Load => {
                        format!(
                            "(ptr, off) => new DataView({mem}.buffer).getBigInt64(ptr + off, true)"
                        )
                    }
                    core::AugmentedOp::F32Load => {
                        format!(
                            "(ptr, off) => new DataView({mem}.buffer).getFloat32(ptr + off, true)"
                        )
                    }
                    core::AugmentedOp::F64Load => {
                        format!(
                            "(ptr, off) => new DataView({mem}.buffer).getFloat64(ptr + off, true)"
                        )
                    }
                    core::AugmentedOp::I32Store8 => {
                        format!(
                            "(ptr, val, offset) => {{
                                new DataView({mem}.buffer).setInt8(ptr + offset, val, true);
                            }}"
                        )
                    }
                    core::AugmentedOp::I32Store16 => {
                        format!(
                            "(ptr, val, offset) => {{
                                new DataView({mem}.buffer).setInt16(ptr + offset, val, true);
                            }}"
                        )
                    }
                    core::AugmentedOp::I32Store => {
                        format!(
                            "(ptr, val, offset) => {{
                                new DataView({mem}.buffer).setInt32(ptr + offset, val, true);
                            }}"
                        )
                    }
                    core::AugmentedOp::I64Store => {
                        format!(
                            "(ptr, val, offset) => {{
                                new DataView({mem}.buffer).setBigInt64(ptr + offset, val, true);
                            }}"
                        )
                    }
                    core::AugmentedOp::F32Store => {
                        format!(
                            "(ptr, val, offset) => {{
                                new DataView({mem}.buffer).setFloat32(ptr + offset, val, true);
                            }}"
                        )
                    }
                    core::AugmentedOp::F64Store => {
                        format!(
                            "(ptr, val, offset) => {{
                                new DataView({mem}.buffer).setFloat64(ptr + offset, val, true);
                            }}"
                        )
                    }
                    core::AugmentedOp::MemorySize => {
                        format!("ptr => {mem}.buffer.byteLength / 65536")
                    }
                }
            }
        }
    }

    fn core_def(&self, def: &CoreDef) -> String {
        match def {
            CoreDef::Export(e) => self.core_export_var_name(e),
            CoreDef::TaskMayBlock => AsyncTaskIntrinsic::CurrentTaskMayBlock.name().into(),
            CoreDef::Trampoline(i) => format!("trampoline{}", i.as_u32()),
            CoreDef::InstanceFlags(i) => {
                // SAFETY: short-lived borrow-mut.
                self.used_instance_flags.borrow_mut().insert(*i);
                format!("instanceFlags{}", i.as_u32())
            }
            CoreDef::UnsafeIntrinsic(ui) => {
                let idx = ui.index();
                format!("unsafeIntrinsic{idx}")
            }
        }
    }

    fn core_export_var_name<T>(&self, export: &CoreExport<T>) -> String
    where
        T: Into<EntityIndex> + Copy,
    {
        let name = match &export.item {
            ExportItem::Index(idx) => {
                let module_idx = self
                    .instances
                    .get(export.instance)
                    .expect("unexpectedly missing export instance");
                let module = &self
                    .modules
                    .get(*module_idx)
                    .expect("unexpectedly missing module by idx");
                let idx = (*idx).into();
                module
                    .exports()
                    .iter()
                    .find_map(|(name, i)| if *i == idx { Some(name) } else { None })
                    .unwrap()
                    .to_string()
            }
            ExportItem::Name(s) => s.to_string(),
        };
        let i = export.instance.as_u32() as usize;
        let quoted = maybe_quote_member(&name);
        format!("exports{i}{quoted}")
    }

    /// Process the component imports and build mappings
    fn process_imports(&mut self) {
        let mut import_resource_map = ResourceMap::new();
        for (_import_name, (import_idx, _import_path)) in self.component.imports.iter() {
            let (import_name, import_type_def) = &self.component.import_types[*import_idx];
            let import_world_key = &self
                .imports
                .get(import_name)
                .expect("missing import mapping");
            let import_world_item = &self
                .resolve
                .worlds
                .get(self.world)
                .expect("missing world")
                .imports
                .get(*import_world_key)
                .expect("missing import in world for import");

            // Generate type information for types used in functions
            match import_world_item {
                WorldItem::Interface { id: iface_id, .. } => {
                    let iface = &self.resolve.interfaces[*iface_id];

                    // Process functions imported by the iface, which will use (as arg or param)
                    // relevant resources
                    for (fn_name, iface_fn) in iface.functions.iter() {
                        match import_type_def {
                            TypeDef::ComponentInstance(instance_ty) => {
                                if let Some(TypeDef::ComponentFunc(type_func_index)) =
                                    &self.types[*instance_ty].exports.get(fn_name)
                                {
                                    self.create_resource_fn_map(
                                        iface_fn,
                                        *type_func_index,
                                        &mut import_resource_map,
                                    );
                                }
                            }
                            TypeDef::ComponentFunc(type_func_idx) => {
                                self.create_resource_fn_map(
                                    iface_fn,
                                    *type_func_idx,
                                    &mut import_resource_map,
                                );
                            }
                            _ => {}
                        }
                    }
                }

                // Process imported functions directly to build resource maps
                WorldItem::Function(func) => {
                    // TODO: get func type index
                    let TypeDef::ComponentFunc(func_ty_idx) = import_type_def else {
                        unreachable!("invalid fn export");
                    };
                    self.create_resource_fn_map(func, *func_ty_idx, &mut import_resource_map);
                }
                // Simply informational at this point
                WorldItem::Type { .. } => {}
            }
        }

        self.resource_imports.extend(import_resource_map);
    }

    /// Process component exports and build mappings
    fn process_exports(&mut self) {
        // Since imports may be referred to by exports, we include all imports in the exports array
        self.resource_exports.extend(self.resource_imports.clone());

        // Process individual component exports
        for (export_name, export_idx) in self.component.exports.raw_iter() {
            let export = &self.component.export_items[*export_idx];
            let world_key = &self.exports[export_name];
            let item = &self.resolve.worlds[self.world].exports[world_key];
            let mut export_resource_map = ResourceMap::new();

            match export {
                Export::LiftedFunction {
                    func: def,
                    options,
                    ty: func_ty,
                } => {
                    let func = match item {
                        WorldItem::Function(f) => f,
                        WorldItem::Interface { .. } | WorldItem::Type { .. } => {
                            unreachable!("unexpectedly non-function lifted function export")
                        }
                    };

                    self.create_resource_fn_map(func, *func_ty, &mut export_resource_map);

                    let local_name = String::from(match func.kind {
                        // For resources, we must take the type name (adding `.prototype.<fn name>` later)
                        FunctionKind::Constructor(resource_id)
                        | FunctionKind::Method(resource_id)
                        | FunctionKind::AsyncMethod(resource_id)
                        | FunctionKind::Static(resource_id)
                        | FunctionKind::AsyncStatic(resource_id) => Instantiator::resource_name(
                            self.resolve,
                            &mut self.bindgen.local_names,
                            resource_id,
                            &self.exports_resource_types,
                        ),
                        // Fore free standing functions we can use the exoprt name directly as a local name
                        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
                            self.bindgen.local_names.create_once(export_name)
                        }
                    });

                    let options = self
                        .component
                        .options
                        .get(*options)
                        .expect("failed to find options");

                    self.export_bindgen(
                        &local_name,
                        def,
                        options,
                        func,
                        func_ty,
                        export_name,
                        &export_resource_map,
                    );

                    let js_binding_name = match func.kind {
                        // For resources, we must take the type name (adding `.prototype.<fn name>` later)
                        FunctionKind::Constructor(ty)
                        | FunctionKind::Method(ty)
                        | FunctionKind::AsyncMethod(ty)
                        | FunctionKind::Static(ty)
                        | FunctionKind::AsyncStatic(ty) => self.resolve.types[ty]
                            .name
                            .as_ref()
                            .unwrap()
                            .to_upper_camel_case(),
                        // For free standing functions we can use the export name directly
                        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
                            export_name.to_lower_camel_case()
                        }
                    };

                    // Add the export binding
                    self.bindgen.esm_bindgen.add_export_binding(
                        None,
                        local_name,
                        js_binding_name,
                        func,
                    );
                }

                Export::Instance { exports, .. } => {
                    let iface_id = match item {
                        WorldItem::Interface { id, .. } => *id,
                        WorldItem::Function(_) | WorldItem::Type { .. } => {
                            unreachable!("unexpectedly non-interface export instance")
                        }
                    };

                    // Process exported instances
                    for (func_name, export_idx) in exports.raw_iter() {
                        let export = &self.component.export_items[*export_idx];

                        // Gather function information for all lifted functions in the isntance export
                        let (def, options, func_ty) = match export {
                            Export::LiftedFunction { func, options, ty } => (func, options, ty),
                            Export::Type(_) => continue, // ignored
                            _ => unreachable!("unexpected non-lifted function export"),
                        };

                        let func = &self.resolve.interfaces[iface_id].functions[func_name];

                        self.create_resource_fn_map(func, *func_ty, &mut export_resource_map);

                        let local_name = String::from(match func.kind {
                            // For resources, we must use the name of the type
                            FunctionKind::Constructor(resource_id)
                            | FunctionKind::Method(resource_id)
                            | FunctionKind::AsyncMethod(resource_id)
                            | FunctionKind::Static(resource_id)
                            | FunctionKind::AsyncStatic(resource_id) => {
                                Instantiator::resource_name(
                                    self.resolve,
                                    &mut self.bindgen.local_names,
                                    resource_id,
                                    &self.exports_resource_types,
                                )
                            }
                            // For free standing functions we can use the bare func name
                            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
                                self.bindgen.local_names.create_once(func_name)
                            }
                        });

                        let options = self
                            .component
                            .options
                            .get(*options)
                            .expect("failed to find options");

                        self.export_bindgen(
                            &local_name,
                            def,
                            options,
                            func,
                            func_ty,
                            export_name,
                            &export_resource_map,
                        );

                        // Determine the export func name (this can also be a class name)
                        let export_binding_name = match func.kind {
                            // For resources, we must use the type name (later adding `.prototype.<actual fn>`)
                            FunctionKind::Constructor(ty)
                            | FunctionKind::Method(ty)
                            | FunctionKind::AsyncMethod(ty)
                            | FunctionKind::Static(ty)
                            | FunctionKind::AsyncStatic(ty) => self.resolve.types[ty]
                                .name
                                .as_ref()
                                .unwrap()
                                .to_upper_camel_case(),
                            // Free standing functions we can use the function name directly
                            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
                                func_name.to_lower_camel_case()
                            }
                        };

                        // Add the export binding
                        self.bindgen.esm_bindgen.add_export_binding(
                            Some(export_name),
                            local_name,
                            export_binding_name,
                            func,
                        );
                    }
                }

                // ignore type exports for now
                Export::Type(_) => {}

                // This can't be tested at this time so leave it unimplemented
                Export::ModuleStatic { .. } | Export::ModuleImport { .. } => unimplemented!(),
            }

            // Save information about exported resources for later
            self.resource_exports.extend(export_resource_map);
        }

        self.bindgen.esm_bindgen.populate_export_aliases();
    }

    #[allow(clippy::too_many_arguments)]
    fn export_bindgen(
        &mut self,
        local_name: &str,
        def: &CoreDef,
        options: &CanonicalOptions,
        func: &Function,
        _func_ty_idx: &TypeFuncIndex,
        export_name: &String,
        export_resource_map: &ResourceMap,
    ) {
        // Determine whether the function should be generated as async
        let requires_async_porcelain = requires_async_porcelain(
            FunctionIdentifier::Fn(func),
            export_name,
            &self.async_exports,
        );
        // If the function is *also* async lifted, it
        if options.async_ {
            assert!(
                options.post_return.is_none(),
                "async function {local_name} (export {export_name}) can't have post return"
            );
        }

        let is_async = is_async_fn(func, options);

        let maybe_async = if requires_async_porcelain || is_async {
            "async "
        } else {
            ""
        };

        // Start building early variable declarations
        let core_export_fn = self.core_def(def);
        let callee = match self
            .bindgen
            .local_names
            .get_or_create(&core_export_fn, &core_export_fn)
        {
            (local_name, true) => local_name.to_string(),
            (local_name, false) => {
                let local_name = local_name.to_string();
                uwriteln!(self.src.js, "let {local_name};");
                self.bindgen
                    .all_core_exported_funcs
                    // TODO(breaking): remove requires_async_porcelain  once support
                    // for manual async import specification is removed, as p3 has
                    // built-in function async coloring
                    .push((core_export_fn.clone(), is_async | requires_async_porcelain));
                local_name
            }
        };

        let iface_name = if export_name.is_empty() {
            None
        } else {
            Some(export_name)
        };

        // Write function preamble (everything up to the `(` in `function (...`)
        match func.kind {
            FunctionKind::Freestanding => {
                uwrite!(self.src.js, "\n{maybe_async}function {local_name}")
            }
            FunctionKind::Method(_) => {
                self.ensure_local_resource_class(local_name.to_string());
                let method_name = func.item_name().to_lower_camel_case();

                uwrite!(
                    self.src.js,
                    "\n{local_name}.prototype.{method_name} = {maybe_async}function {}",
                    if !is_js_reserved_word(&method_name) {
                        method_name.to_string()
                    } else {
                        format!("${method_name}")
                    }
                );
            }
            FunctionKind::Static(_) => {
                self.ensure_local_resource_class(local_name.to_string());
                let method_name = func.item_name().to_lower_camel_case();
                uwrite!(
                    self.src.js,
                    "\n{local_name}.{method_name} = function {}",
                    if !is_js_reserved_word(&method_name) {
                        method_name.to_string()
                    } else {
                        format!("${method_name}")
                    }
                );
            }
            FunctionKind::Constructor(_) => {
                if self.defined_resource_classes.contains(local_name) {
                    panic!(
                        "Internal error: Resource constructor must be defined before other methods and statics"
                    );
                }
                uwrite!(
                    self.src.js,
                    "
                    class {local_name} {{
                        constructor"
                );
                self.defined_resource_classes.insert(local_name.to_string());
            }
            FunctionKind::AsyncFreestanding => {
                uwrite!(self.src.js, "\nasync function {local_name}")
            }
            FunctionKind::AsyncMethod(_) => {
                self.ensure_local_resource_class(local_name.to_string());
                let method_name = func.item_name().to_lower_camel_case();
                let fn_name = if !is_js_reserved_word(&method_name) {
                    method_name.to_string()
                } else {
                    format!("${method_name}")
                };
                uwrite!(
                    self.src.js,
                    "\n{local_name}.prototype.{method_name} = async function {fn_name}",
                );
            }
            FunctionKind::AsyncStatic(_) => {
                self.ensure_local_resource_class(local_name.to_string());
                let method_name = func.item_name().to_lower_camel_case();
                let fn_name = if !is_js_reserved_word(&method_name) {
                    method_name.to_string()
                } else {
                    format!("${method_name}")
                };
                uwrite!(
                    self.src.js,
                    "\n{local_name}.{method_name} = async function {fn_name}",
                );
            }
        };

        // Perform bindgen
        self.bindgen(JsFunctionBindgenArgs {
            nparams: func.params.len(),
            call_type: match func.kind {
                FunctionKind::Method(_) => CallType::FirstArgIsThis,
                FunctionKind::AsyncMethod(_) => CallType::AsyncFirstArgIsThis,
                FunctionKind::Freestanding
                | FunctionKind::Static(_)
                | FunctionKind::Constructor(_) => CallType::Standard,
                FunctionKind::AsyncFreestanding | FunctionKind::AsyncStatic(_) => {
                    CallType::AsyncStandard
                }
            },
            iface_name: iface_name.map(|v| v.as_str()),
            callee: &callee,
            opts: options,
            func,
            resource_map: export_resource_map,
            abi: AbiVariant::GuestExport,
            requires_async_porcelain,
            is_async,
        });

        // End the function
        match func.kind {
            FunctionKind::AsyncFreestanding | FunctionKind::Freestanding => self.src.js("\n"),
            FunctionKind::AsyncMethod(_)
            | FunctionKind::AsyncStatic(_)
            | FunctionKind::Method(_)
            | FunctionKind::Static(_) => self.src.js(";\n"),
            FunctionKind::Constructor(_) => self.src.js("\n}\n"),
        }
    }
}

#[derive(Default)]
pub struct Source {
    pub js: source::Source,
    pub js_init: source::Source,
}

impl Source {
    pub fn js(&mut self, s: &str) {
        self.js.push_str(s);
    }
    pub fn js_init(&mut self, s: &str) {
        self.js_init.push_str(s);
    }
}

/// Compute the semver "compatibility track" for a version string.
/// Mirrors wasmtime's `alternate_lookup_key()` logic.
///
/// Returns the compat key and parsed `Version` on success.
///
/// Examples (showing just the key):
///   "1.2.3"  → Some(("1", ..))     — major > 0, compat within major
///   "0.2.10" → Some(("0.2", ..))   — minor > 0, compat within 0.minor
///   "0.0.1"  → None                — no semver compat
///   "1.0.0-rc.1" → None            — pre-release, no compat
fn semver_compat_key(version_str: &str) -> Option<(String, Version)> {
    let version = Version::parse(version_str).ok()?;
    if !version.pre.is_empty() {
        None
    } else if version.major != 0 {
        Some((format!("{}", version.major), version))
    } else if version.minor != 0 {
        Some((format!("0.{}", version.minor), version))
    } else {
        None
    }
}

fn parse_mapping(mapping: &str) -> (String, Option<String>) {
    if mapping.len() > 1
        && let Some(hash_idx) = mapping[1..].find('#')
    {
        return (
            mapping[0..hash_idx + 1].to_string(),
            Some(mapping[hash_idx + 2..].into()),
        );
    }
    (mapping.into(), None)
}

fn map_import(map: &Option<HashMap<String, String>>, impt: &str) -> (String, Option<String>) {
    let impt_sans_version = match impt.find('@') {
        Some(version_idx) => &impt[0..version_idx],
        None => impt,
    };
    if let Some(map) = map.as_ref() {
        // Exact match (including version)
        if let Some(mapping) = map.get(impt) {
            return parse_mapping(mapping);
        }
        // Match without version
        if let Some(mapping) = map.get(impt_sans_version) {
            return parse_mapping(mapping);
        }
        // Wildcard matching (version-stripped and full)
        for (key, mapping) in map {
            if let Some(wildcard_idx) = key.find('*') {
                let lhs = &key[0..wildcard_idx];
                let rhs = &key[wildcard_idx + 1..];
                if impt_sans_version.starts_with(lhs) && impt_sans_version.ends_with(rhs) {
                    let matched = &impt_sans_version[wildcard_idx
                        ..wildcard_idx + impt_sans_version.len() - lhs.len() - rhs.len()];
                    let mapping = mapping.replace('*', matched);
                    return parse_mapping(&mapping);
                }
                if impt.starts_with(lhs) && impt.ends_with(rhs) {
                    let matched =
                        &impt[wildcard_idx..wildcard_idx + impt.len() - lhs.len() - rhs.len()];
                    let mapping = mapping.replace('*', matched);
                    return parse_mapping(&mapping);
                }
            }
        }
        // Semver-compatible matching for versioned map entries.
        // If the import has a parseable version and earlier steps didn't match,
        // try matching against map entries with compatible versions.
        if let Some(at) = impt.find('@') {
            let impt_ver_str = &impt[at + 1..];
            if let Some((impt_compat, _)) = semver_compat_key(impt_ver_str) {
                let mut best_match: Option<(String, Version)> = None;

                for (key, mapping) in map {
                    // Only consider map entries that have a version
                    let key_at = match key.find('@') {
                        Some(at) => at,
                        None => continue,
                    };
                    let key_base = &key[..key_at];
                    let key_ver_str = &key[key_at + 1..];

                    // Check version compatibility
                    let (key_compat, key_ver) = match semver_compat_key(key_ver_str) {
                        Some(k) => k,
                        None => continue,
                    };
                    if impt_compat != key_compat {
                        continue;
                    }

                    // Versions are on the same compatibility track.
                    // Now check if the base (sans version) matches.
                    let resolved = if let Some(wildcard_idx) = key_base.find('*') {
                        let lhs = &key_base[..wildcard_idx];
                        let rhs = &key_base[wildcard_idx + 1..];
                        if impt_sans_version.starts_with(lhs) && impt_sans_version.ends_with(rhs) {
                            let matched = &impt_sans_version[wildcard_idx
                                ..wildcard_idx + impt_sans_version.len() - lhs.len() - rhs.len()];
                            Some(mapping.replace('*', matched))
                        } else {
                            None
                        }
                    } else if key_base == impt_sans_version {
                        Some(mapping.clone())
                    } else {
                        None
                    };

                    if let Some(resolved_mapping) = resolved {
                        // Prefer the highest compatible version
                        match &best_match {
                            Some((_, prev_ver)) if key_ver <= *prev_ver => {}
                            _ => {
                                best_match = Some((resolved_mapping, key_ver));
                            }
                        }
                    }
                }

                if let Some((mapping, _)) = best_match {
                    return parse_mapping(&mapping);
                }
            }
        }
    }
    (impt_sans_version.to_string(), None)
}

pub fn parse_world_key(name: &str) -> Option<(&str, &str, &str)> {
    let registry_idx = name.find(':')?;
    let ns = &name[0..registry_idx];
    match name.rfind('/') {
        Some(sep_idx) => {
            let end = if let Some(version_idx) = name.rfind('@') {
                version_idx
            } else {
                name.len()
            };
            Some((
                ns,
                &name[registry_idx + 1..sep_idx],
                &name[sep_idx + 1..end],
            ))
        }
        // interface is a namespace, function is a default export
        None => Some((ns, &name[registry_idx + 1..], "")),
    }
}

fn core_file_name(name: &str, idx: u32) -> String {
    let i_str = if idx == 0 {
        String::from("")
    } else {
        (idx + 1).to_string()
    };
    format!("{name}.core{i_str}.wasm")
}

/// Encode a [`StringEncoding`] as a string that can be used in Javascript
fn string_encoding_js_literal(val: &wasmtime_environ::component::StringEncoding) -> &'static str {
    match val {
        wasmtime_environ::component::StringEncoding::Utf8 => "'utf8'",
        wasmtime_environ::component::StringEncoding::Utf16 => "'utf16'",
        wasmtime_environ::component::StringEncoding::CompactUtf16 => "'compact-utf16'",
    }
}

/// Generate the javascript that corresponds to a list of lifting functions for a given list of types
///
/// # Arguments
///
/// * `instantiator`
/// * `types` - Types for which to generate lift functions
/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
///
pub fn gen_flat_lift_fn_list_js_expr(
    instantiator: &mut Instantiator,
    types: &[InterfaceType],
    extra_resource_map: &Option<&mut ResourceMap>,
) -> String {
    let mut lift_fns: Vec<String> = Vec::with_capacity(types.len());
    for ty in types.iter() {
        lift_fns.push(gen_flat_lift_fn_js_expr(
            instantiator,
            ty,
            extra_resource_map,
        ));
    }
    format!("[{}]", lift_fns.join(","))
}

/// Generate the javascript lifting function for a given type
///
/// This function will a function object that can be executed with the right
/// context in order to perform the lift. For example, running this for bool
/// will produce the following:
///
/// ```
/// _liftFlatBool
/// ```
///
/// This is becasue all it takes to lift a flat boolean is to run the _liftFlatBool function intrinsic.
///
/// The intrinsic it guaranteed to be in scope once execution time because it wlil be used in the relevant branch.
///
/// # Arguments
///
/// * `instantiator`
/// * `ty` - The type for which to generate a lift function
/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
///
pub fn gen_flat_lift_fn_js_expr(
    instantiator: &mut Instantiator,
    ty: &InterfaceType,
    extra_resource_map: &Option<&mut ResourceMap>,
) -> String {
    let component_types = instantiator.types;

    match ty {
        InterfaceType::Bool => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatBool));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatBool).name().into()
        }

        InterfaceType::S8 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS8));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatS8).name().into()
        }

        InterfaceType::U8 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU8));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatU8).name().into()
        }

        InterfaceType::S16 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS16));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatS16).name().into()
        }

        InterfaceType::U16 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU16));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatU16).name().into()
        }

        InterfaceType::S32 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS32));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatS32).name().into()
        }

        InterfaceType::U32 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU32));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatU32).name().into()
        }

        InterfaceType::S64 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS64));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatS64).name().into()
        }

        InterfaceType::U64 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU64));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatU64).name().into()
        }

        InterfaceType::Float32 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat32));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat32)
                .name()
                .into()
        }

        InterfaceType::Float64 => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat64));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat64)
                .name()
                .into()
        }

        InterfaceType::Char => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatChar));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatChar).name().into()
        }

        InterfaceType::String => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny));
            Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny)
                .name()
                .into()
        }

        InterfaceType::Record(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatRecord));
            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatRecord).name();
            let record_ty = &component_types[*ty_idx];
            let mut keys_and_lifts_expr = String::from("[");
            // For each field we build a list of [name, liftFn, 32bit alignment]
            // so that the record lifting function (which is a higher level function)
            // can properly generate a function that lifts the fields.
            for f in &record_ty.fields {
                keys_and_lifts_expr.push_str(&format!(
                    "['{}', {}, {}, {}],",
                    f.name.to_lower_camel_case(),
                    gen_flat_lift_fn_js_expr(instantiator, &f.ty, extra_resource_map),
                    component_types.canonical_abi(ty).size32,
                    component_types.canonical_abi(ty).align32,
                ));
            }
            keys_and_lifts_expr.push(']');
            format!("{lift_fn}({keys_and_lifts_expr})")
        }

        InterfaceType::Variant(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant));
            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant).name();
            let variant_ty = &component_types[*ty_idx];
            let mut cases_and_lifts_expr = String::from("[");
            for (name, maybe_ty) in &variant_ty.cases {
                let lift_args = match maybe_ty {
                    None => format!("['{}', null, 0, 0, 0],", name),
                    Some(ty) => {
                        format!(
                            "['{name}', {}, {}, {}, {}],",
                            gen_flat_lift_fn_js_expr(instantiator, ty, extra_resource_map),
                            variant_ty.abi.size32,
                            variant_ty.abi.align32,
                            variant_ty.info.payload_offset32,
                        )
                    }
                };
                cases_and_lifts_expr.push_str(&lift_args);
            }
            cases_and_lifts_expr.push(']');
            format!("{lift_fn}({cases_and_lifts_expr})")
        }

        InterfaceType::List(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatList));
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatList).name();
            let list_ty = &component_types[*ty_idx];
            let lift_fn_expr =
                gen_flat_lift_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
            let elem_cabi = component_types.canonical_abi(&list_ty.element);
            let elem_align32 = elem_cabi.align32;
            let elem_size32 = elem_cabi.size32;
            format!(
                "{f}({{
                     elemLiftFn: {lift_fn_expr},
                     elemAlign32: {elem_align32},
                     elemSize32: {elem_size32},
                 }})"
            )
        }

        InterfaceType::FixedLengthList(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatList));
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatList).name();
            let list_ty = &component_types[*ty_idx];
            let list_size32 = list_ty.abi.size32;
            let list_align32 = list_ty.abi.align32;
            let lift_fn_expr =
                gen_flat_lift_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
            let list_len = list_ty.size;
            let elem_cabi = component_types.canonical_abi(&list_ty.element);
            let elem_align32 = elem_cabi.align32;
            let elem_size32 = elem_cabi.size32;
            format!(
                "{f}({{
                     elemLiftFn: {lift_fn_expr},
                     elemAlign32: {elem_align32},
                     elemSize32: {elem_size32},
                     listSize32: {list_size32},
                     listAlign32: {list_align32},
                     knownLen: {list_len},
                 }})"
            )
        }

        InterfaceType::Tuple(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatTuple));
            let tuple_ty = &component_types[*ty_idx];
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatTuple).name();
            let size_u32 = tuple_ty.abi.size32;
            let align_u32 = tuple_ty.abi.align32;

            let mut elem_lifts_expr = String::from("[");
            for ty in &tuple_ty.types {
                let lift_fn_js = gen_flat_lift_fn_js_expr(instantiator, ty, extra_resource_map);
                elem_lifts_expr.push_str(&format!("[{lift_fn_js}, {size_u32}, {align_u32}],"));
            }
            elem_lifts_expr.push(']');

            format!("{f}({elem_lifts_expr})")
        }

        InterfaceType::Flags(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags));
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags).name();
            let flags_ty = &component_types[*ty_idx];
            let size_u32 = flags_ty.abi.size32;
            let align_u32 = flags_ty.abi.align32;
            let names_expr = format!(
                "[{}]",
                flags_ty
                    .names
                    .iter()
                    .map(|s| format!("'{s}'"))
                    .collect::<Vec<_>>()
                    .join(",")
            );
            let num_flags = flags_ty.names.len();
            let elem_size = if num_flags <= 8 {
                1
            } else if num_flags <= 16 {
                2
            } else {
                4
            };

            format!(
                "{f}({{ names: {names_expr}, size32: {size_u32}, align32: {align_u32}, intSizeBytes: {elem_size} }})"
            )
        }

        InterfaceType::Enum(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatEnum));
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatEnum).name();
            let enum_ty = &component_types[*ty_idx];
            let size_32 = enum_ty.abi.size32;
            let align_32 = enum_ty.abi.align32;
            let payload_offset_32 = enum_ty.info.payload_offset32;

            let mut elem_lifts_expr = String::from("[");
            for name in &enum_ty.names {
                elem_lifts_expr.push_str(&format!(
                    "['{name}', null, {size_32}, {align_32}, {payload_offset_32}],"
                ));
            }
            elem_lifts_expr.push(']');

            format!("{f}({elem_lifts_expr})")
        }

        InterfaceType::Option(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatOption));
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatOption).name();
            let option_ty = &component_types[*ty_idx];
            let payload_offset_32 = option_ty.info.payload_offset32;
            let align_32 = option_ty.abi.align32;
            let size_32 = option_ty.abi.size32;
            let lift_fn_js =
                gen_flat_lift_fn_js_expr(instantiator, &option_ty.ty, extra_resource_map);
            // NOTE: options are treated as variants
            format!(
                "{f}([
                     ['none', null, {size_32}, {align_32}, {payload_offset_32} ],
                     ['some', {lift_fn_js}, {size_32}, {align_32}, {payload_offset_32} ],
                 ])"
            )
        }

        InterfaceType::Result(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatResult));
            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatResult).name();
            let result_ty = &component_types[*ty_idx];
            let mut cases_and_lifts_expr = String::from("[");

            if let Some(ok_ty) = result_ty.ok {
                cases_and_lifts_expr.push_str(&format!(
                    "['ok', {}, {}, {}, {}],",
                    gen_flat_lift_fn_js_expr(instantiator, &ok_ty, extra_resource_map),
                    result_ty.abi.size32,
                    result_ty.abi.align32,
                    result_ty.info.payload_offset32,
                ))
            } else {
                cases_and_lifts_expr.push_str("['ok', null, 0, 0, 0],");
            }

            if let Some(err_ty) = &result_ty.err {
                cases_and_lifts_expr.push_str(&format!(
                    "['err', {}, {}, {}, {}],",
                    gen_flat_lift_fn_js_expr(instantiator, err_ty, extra_resource_map),
                    result_ty.abi.size32,
                    result_ty.abi.align32,
                    result_ty.info.payload_offset32,
                ))
            } else {
                cases_and_lifts_expr.push_str("['err', null, 0, 0, 0],");
            }

            cases_and_lifts_expr.push(']');
            format!("{lift_fn}({cases_and_lifts_expr})")
        }

        InterfaceType::Own(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatOwn));
            instantiator.add_intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
            instantiator.add_intrinsic(Intrinsic::SymbolResourceHandle);
            instantiator.add_intrinsic(Intrinsic::SymbolDispose);
            instantiator.add_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
            instantiator.add_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatOwn).name();
            let table_ty = &component_types[*ty_idx];
            let component_idx = table_ty.unwrap_concrete_instance().as_u32();
            let resource_idx = table_ty.unwrap_concrete_ty();

            // Attempt to find information about the owned resource
            match instantiator.exports_resource_index_types.get(&resource_idx) {
                // Type information not found for this resource index
                None => format!(
                    r#"{f}({{
                       componentIdx: {component_idx},
                       className: null,
                       createResourceFn: () => {{ throw new Error('invalid/missing resource type data'); }},
                    }})
                "#,
                ),

                // If we have a resource type def, find more information about it to generate
                // the resource creation function
                Some(resource_typedef) => {
                    // Look in both the resource exports and the provided extra resource map for the resource
                    let (resource_class_name, create_resource_fn_js) = match (
                        instantiator.resource_exports.get(resource_typedef),
                        extra_resource_map
                            .as_ref()
                            .and_then(|v| v.get(resource_typedef)),
                    ) {
                        // Resource type information wasn't found
                        (None, None) => (
                            "null".into(),
                            "() => {{ throw new Error('missing resource information'); }}".into(),
                        ),

                        // Resource type was found in either resource_exports or extra provided resource map
                        (Some(ResourceTable { data, .. }), _)
                        | (_, Some(ResourceTable { data, .. })) => match data {
                            ResourceData::Guest { .. } => {
                                unimplemented!(
                                    "owned resources created by guests should must have host-side data"
                                )
                            }
                            ResourceData::Host {
                                tid,
                                local_name,
                                dtor_name,
                                ..
                            } => {
                                let empty_func = JsHelperIntrinsic::EmptyFunc.name();
                                let symbol_resource_handle = Intrinsic::SymbolResourceHandle.name();
                                let symbol_dispose = Intrinsic::SymbolDispose.name();
                                let rsc_table_remove =
                                    ResourceIntrinsic::ResourceTableRemove.name();
                                let tid = tid.as_u32();
                                let rsc_flag = ResourceIntrinsic::ResourceTableFlag.name();

                                let dtor_setup_js = dtor_name
                                .as_ref()
                                .map(|dtor|
                                     format!(
                                         r#"
                                           Object.defineProperty(
                                               resourceObj,
                                               {symbol_dispose},
                                               {{
                                                   writable: true,
                                                   value: function() {{
                                                       finalizationRegistry{tid}.unregister(resourceObj);
                                                       {rsc_table_remove}(handleTable{tid}, handle);
                                                       resourceObj[{symbol_dispose}] = {empty_func};
                                                       resourceObj[{symbol_resource_handle}] = undefined;
                                                       {dtor}(handleTable{tid}[(handle << 1) + 1] & ~{rsc_flag});
                                                   }}
                                              }}
                                          );
                                    "#
                                     )
                                ).unwrap_or_default();

                                let create_resource_fn_js = format!(
                                    r#"
                                  (handle) => {{
                                      const resourceObj = Object.create({local_name}.prototype);
                                      Object.defineProperty(resourceObj, {symbol_resource_handle}, {{
                                          writable: true,
                                          value: handle,
                                      }});
                                      finalizationRegistry{tid}.register(resourceObj, handle, resourceObj);
                                      {dtor_setup_js}
                                      return resourceObj;
                                  }}
                                 "#
                                );

                                (local_name.to_string(), create_resource_fn_js)
                            }
                        },
                    };

                    format!(
                        r#"{f}({{
                       componentIdx: {component_idx},
                       className: {resource_class_name},
                       createResourceFn: {create_resource_fn_js},
                    }})
                "#,
                    )
                }
            }
        }

        InterfaceType::Borrow(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatBorrow));
            let table_idx = ty_idx.as_u32();
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatBorrow).name();
            format!("{f}.bind(null, {table_idx})")
        }

        InterfaceType::Future(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture));
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture).name();
            let table_idx = ty_idx.as_u32();
            let table_ty = &component_types[*ty_idx];
            let component_idx = table_ty.instance.as_u32();
            format!("{f}({{ futureTableIdx: {table_idx}, componentIdx: {component_idx} }})")
        }

        InterfaceType::Stream(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatStream));
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatStream).name();
            let table_idx = ty_idx.as_u32();
            let table_ty = &component_types[*ty_idx];
            let component_idx = table_ty.instance.as_u32();
            format!("{f}({{ streamTableIdx: {table_idx}, componentIdx: {component_idx} }})")
        }

        InterfaceType::ErrorContext(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatErrorContext));
            let table_idx = ty_idx.as_u32();
            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatErrorContext).name();
            format!("{f}.bind(null, {table_idx})")
        }
    }
}

/// Generate the javascript that corresponds to a list of lowering functions for a given list of types
///
/// # Arguments
///
/// * `instantiator`
/// * `types` - Types for which to generate lift functions
/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
///
pub fn gen_flat_lower_fn_list_js_expr(
    instantiator: &mut Instantiator,
    types: &[InterfaceType],
    extra_import_map: &Option<&mut ResourceMap>,
) -> String {
    let mut lower_fns: Vec<String> = Vec::with_capacity(types.len());
    for ty in types.iter() {
        lower_fns.push(gen_flat_lower_fn_js_expr(
            instantiator,
            ty,
            extra_import_map,
        ));
    }
    format!("[{}]", lower_fns.join(","))
}

/// Generate the javascript lowering function for a given type
///
/// This function will a function object that can be executed with the right
/// context in order to perform the lower. For example, running this for bool
/// will produce the following:
///
/// ```
/// _lowerFlatBool
/// ```
///
/// This is becasue all it takes to lower a flat boolean is to run the _lowerFlatBool function intrinsic.
///
/// The intrinsic it guaranteed to be in scope once execution time because it wlil be used in the relevant branch.
///
/// # Arguments
///
/// * `instantiator`
/// * `ty` - type for which to generate a lower function
/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
///
pub fn gen_flat_lower_fn_js_expr(
    instantiator: &mut Instantiator,
    ty: &InterfaceType,
    extra_resource_map: &Option<&mut ResourceMap>,
) -> String {
    let component_types = instantiator.types;
    match ty {
        InterfaceType::Bool => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatBool));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatBool)
                .name()
                .into()
        }

        InterfaceType::S8 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS8));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatS8).name().into()
        }

        InterfaceType::U8 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU8));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatU8).name().into()
        }

        InterfaceType::S16 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS16));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatS16).name().into()
        }

        InterfaceType::U16 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU16));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatU16).name().into()
        }

        InterfaceType::S32 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS32));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatS32).name().into()
        }

        InterfaceType::U32 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU32));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatU32).name().into()
        }

        InterfaceType::S64 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS64));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatS64).name().into()
        }

        InterfaceType::U64 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU64));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatU64).name().into()
        }

        InterfaceType::Float32 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat32));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat32)
                .name()
                .into()
        }

        InterfaceType::Float64 => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat64));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat64)
                .name()
                .into()
        }

        InterfaceType::Char => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatChar));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatChar)
                .name()
                .into()
        }

        InterfaceType::String => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny));
            Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny)
                .name()
                .into()
        }

        InterfaceType::Record(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatRecord));
            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatRecord).name();
            let record_ty = &component_types[*ty_idx];
            let mut keys_and_lowers_expr = String::from("[");
            for f in &record_ty.fields {
                // For each field we build a list of [name, lowerFn, 32bit alignment]
                // so that the record lowering function (which is a higher level function)
                // can properly generate a function that lowers the fields.
                keys_and_lowers_expr.push_str(&format!(
                    "['{}', {}, {}, {} ],",
                    f.name.to_lower_camel_case(),
                    gen_flat_lower_fn_js_expr(instantiator, &f.ty, &None),
                    component_types.canonical_abi(ty).size32,
                    component_types.canonical_abi(ty).align32,
                ));
            }
            keys_and_lowers_expr.push(']');
            format!("{lower_fn}({keys_and_lowers_expr})")
        }

        InterfaceType::Variant(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant));
            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant).name();
            let variant_ty = &component_types[*ty_idx];
            let size32 = variant_ty.abi.size32;
            let align32 = variant_ty.abi.align32;
            let payload_offset32 = variant_ty.info.payload_offset32;

            let mut lower_metas_expr = String::from("[");
            for (name, maybe_ty) in variant_ty.cases.iter() {
                lower_metas_expr.push_str(&format!(
                    "[ '{name}', {}, {size32}, {align32}, {payload_offset32} ],",
                    maybe_ty
                        .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, &None))
                        .unwrap_or_else(|| "null".into()),
                ));
            }
            lower_metas_expr.push(']');

            format!("{lower_fn}({lower_metas_expr})")
        }

        InterfaceType::List(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatList));
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatList).name();
            let list_ty = &component_types[*ty_idx];
            let elem_ty_lower_expr =
                gen_flat_lower_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
            let elem_cabi = component_types.canonical_abi(&list_ty.element);
            let elem_align32 = elem_cabi.align32;
            let elem_size32 = elem_cabi.size32;

            format!(
                "{f}({{
                elemLowerFn: {elem_ty_lower_expr},
                elemSize32: {elem_size32},
                elemAlign32: {elem_align32},
            }})"
            )
        }

        InterfaceType::FixedLengthList(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatList));
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatList).name();
            let list_ty = &component_types[*ty_idx];
            let elem_ty_lower_expr =
                gen_flat_lower_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
            let list_len = list_ty.size;
            let list_align32 = list_ty.abi.size32;
            let list_size32 = list_ty.abi.size32;
            let elem_cabi = component_types.canonical_abi(&list_ty.element);
            let elem_align32 = elem_cabi.align32;
            let elem_size32 = elem_cabi.size32;

            format!(
                r#"{f}({{
                       elemLowerFn: {elem_ty_lower_expr},
                       elemAlign32: {elem_align32},
                       elemSize32: {elem_size32},
                       align32: {list_align32},
                       size32: {list_size32},
                       knownLen: {list_len},
                   }})"#
            )
        }

        InterfaceType::Tuple(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatTuple));
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatTuple).name();
            let tuple_ty = &component_types[*ty_idx];
            let size_u32 = tuple_ty.abi.size32;
            let align_u32 = tuple_ty.abi.align32;

            let mut elem_lowers_expr = String::from("[");
            for ty in &tuple_ty.types {
                let lower_fn_js = gen_flat_lower_fn_js_expr(instantiator, ty, extra_resource_map);
                elem_lowers_expr.push_str(&format!("[{lower_fn_js}, {size_u32}, {align_u32}],"));
            }
            elem_lowers_expr.push(']');

            format!("{f}({elem_lowers_expr})")
        }

        InterfaceType::Flags(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags));
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags).name();
            let flags_ty = &component_types[*ty_idx];
            let size32 = flags_ty.abi.size32;
            let align32 = flags_ty.abi.align32;
            let names_list_js = format!(
                "[{}]",
                flags_ty
                    .names
                    .iter()
                    .map(|s| format!("'{s}'"))
                    .collect::<Vec<_>>()
                    .join(",")
            );
            let num_flags = flags_ty.names.len();
            let elem_size = if num_flags <= 8 {
                1
            } else if num_flags <= 16 {
                2
            } else {
                4
            };

            format!(
                "{f}({{ names: {names_list_js}, size32: {size32}, align32: {align32}, intSizeBytes: {elem_size} }})"
            )
        }

        InterfaceType::Enum(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatEnum));
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatEnum).name();
            let enum_ty = &component_types[*ty_idx];
            let size32 = enum_ty.abi.size32;
            let align32 = enum_ty.abi.align32;
            let payload_offset32 = enum_ty.info.payload_offset32;

            let mut elem_lowers_expr = String::from("[");
            for name in &enum_ty.names {
                elem_lowers_expr.push_str(&format!(
                    "['{name}', null, {size32}, {align32}, {payload_offset32}],"
                ));
            }
            elem_lowers_expr.push(']');

            format!("{f}({elem_lowers_expr})")
        }

        InterfaceType::Option(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatOption));
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatOption).name();
            let option_ty = &component_types[*ty_idx];
            let size32 = option_ty.abi.size32;
            let align32 = option_ty.abi.align32;
            let payload_offset32 = option_ty.info.payload_offset32;
            let lower_fn_js =
                gen_flat_lower_fn_js_expr(instantiator, &option_ty.ty, extra_resource_map);

            format!(
                r#"{f}([
                       [ 'none', null, {size32}, {align32}, {payload_offset32} ],
                       [ 'some', {lower_fn_js}, {size32}, {align32}, {payload_offset32} ],
                   ])
                "#
            )
        }

        InterfaceType::Result(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatResult));
            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatResult).name();
            let result_ty = &component_types[*ty_idx];
            let size32 = result_ty.abi.size32;
            let align32 = result_ty.abi.align32;
            let payload_offset32 = result_ty.info.payload_offset32;
            let ok_lower_fn_js = result_ty
                .ok
                .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, extra_resource_map))
                .unwrap_or_else(|| "null".into());
            let err_lower_fn_js = result_ty
                .err
                .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, extra_resource_map))
                .unwrap_or_else(|| "null".into());

            format!(
                r#"{lower_fn}([
                       [ 'ok', {ok_lower_fn_js}, {size32}, {align32}, {payload_offset32} ],
                       [ 'err', {err_lower_fn_js}, {size32}, {align32}, {payload_offset32} ],
                   ])
                "#
            )
        }

        InterfaceType::Own(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatOwn));
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatOwn).name();
            let resource_table_ty = &component_types[*ty_idx];
            let component_idx = resource_table_ty.unwrap_concrete_instance().as_u32();
            let resource_idx = resource_table_ty.unwrap_concrete_ty();

            // Retrieve resource information for the given resource, looking
            // in both the extra resource map and the instantiator's dedicated resource-to-imports/
            // exports maps.
            let (_, ResourceTable { imported, data }) = match (
                instantiator.imports_resource_index_types.get(&resource_idx),
                instantiator.exports_resource_index_types.get(&resource_idx),
            ) {
                (Some(import_ty_id), _) => {
                    let ty = crate::dealias(instantiator.resolve, *import_ty_id);
                    let maybe_resource_table =
                        instantiator.resource_imports.get(&ty).or(extra_resource_map
                            .as_ref()
                            .and_then(|m| m.get(import_ty_id)));
                    (
                        ty,
                        maybe_resource_table.expect("missing imported resource table information"),
                    )
                }
                (_, Some(export_ty_id)) => {
                    let ty = crate::dealias(instantiator.resolve, *export_ty_id);
                    let maybe_resource_table =
                        instantiator.resource_exports.get(&ty).or(extra_resource_map
                            .as_ref()
                            .and_then(|m| m.get(export_ty_id)));
                    (
                        ty,
                        maybe_resource_table.expect("missing exported resource table information"),
                    )
                }

                // If resource was not found in the index type map at all, we're missing resource metadata.
                (None, None) => {
                    return format!(
                        "{f}({{
                             componentIdx: {component_idx},
                             lowerFn: () => {{ throw new Error('missing/invalid resource metadata'); }}
                         }})"
                    );
                }
            };

            // Build the function to create the resource, depending on how it was provided
            let lower_fn_js = match data {
                // If the resource was provided by the host, build the function to create it.
                ResourceData::Host {
                    tid,
                    rid,
                    local_name,
                    ..
                } => {
                    let tid = tid.as_u32();
                    let rid = rid.as_u32();
                    let symbol_resource_rep =
                        instantiator.bindgen.intrinsic(Intrinsic::SymbolResourceRep);
                    let symbol_resource_handle = instantiator
                        .bindgen
                        .intrinsic(Intrinsic::SymbolResourceHandle);
                    let symbol_dispose = instantiator.bindgen.intrinsic(Intrinsic::SymbolDispose);

                    if *imported {
                        // If imported (and from the host), we must ensure that the incoming object is of the right
                        // instance, then add it to the capture table w/ the right resource ID,
                        let create_own_fn = instantiator.bindgen.intrinsic(Intrinsic::Resource(
                            ResourceIntrinsic::ResourceTableCreateOwn,
                        ));
                        format!(
                            r#"
                              function lowerImportedOwnedHost_{local_name}(obj) {{
                                  if (!(obj instanceof {local_name})) {{
                                      throw new TypeError('Resource error: Not a valid \"{local_name}\" resource.');
                                  }}
                                  let handle = obj[{symbol_resource_handle}];
                                  if (!handle) {{
                                    const rep = obj[{symbol_resource_rep}] || ++captureCnt{rid};
                                    captureTable{rid}.set(rep, obj);
                                    handle = {create_own_fn}(handleTable{tid}, rep);
                                  }}
                                  return handle;
                              }}
                            "#
                        )
                    } else {
                        // If the resource was not imported (and came from the host), it comes from the component receiving it,
                        // and the object should already have a handle associated inside of it (the component must have created it).
                        //
                        // We disconnect the external connections for dispose and remove the external
                        // facing resource handle that was added when lifted out.
                        let empty_func = instantiator
                            .bindgen
                            .intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
                        format!(
                            r#"
                               function lowerExportedOwnedHost_{local_name}(obj) {{
                                   let handle = obj[{symbol_resource_handle}];
                                   if (!handle) {{
                                       throw new TypeError('Resource error: Not a valid \"{local_name}\" resource.');
                                   }}
                                   finalizationRegistry{tid}.unregister(obj);
                                   obj[{symbol_dispose}] = {empty_func};
                                   obj[{symbol_resource_handle}] = undefined;
                                   return handle;
                               }}
                        "#
                        )
                    }
                }

                // If the resource was provided by the guest, build the function to create it.
                ResourceData::Guest {
                    resource_name,
                    prefix,
                    extra,
                } => {
                    assert!(
                        extra.is_none(),
                        "plain resource handles do not carry extra data"
                    );

                    let upper_camel = resource_name.to_upper_camel_case();
                    let lower_camel = resource_name.to_lower_camel_case();
                    let prefix = prefix.as_deref().unwrap_or("");

                    if *imported {
                        // If we get a resource that is provided by the host, then
                        // it should already have an external-facing resource handle on it.
                        let symbol_resource_handle = instantiator
                            .bindgen
                            .intrinsic(Intrinsic::SymbolResourceHandle);
                        format!(
                            r#"
                              function lowerImportedOwnedGuest_{upper_camel}(obj) {{
                                  const handle = obj[{symbol_resource_handle}];
                                  finalizationRegistry_import${prefix}{lower_camel}.unregister(obj);
                                  return handle;
                              }}
                            "#
                        )
                    } else {
                        // If we get a resource that was exported by the guest and is being lowered in,
                        // we can check that the object is of the right kidn of instance, and
                        // create rep for it if one does not already exist.
                        let symbol_resource_handle = instantiator
                            .bindgen
                            .intrinsic(Intrinsic::SymbolResourceHandle);
                        format!(
                            r#"
                              function lowerExportedOwnedGuest_{upper_camel}(obj) {{
                                  if (!(obj instanceof {upper_camel})) {{
                                    throw new TypeError('Resource error: Not a valid \"{upper_camel}\" resource.');
                                  }}
                                  let handle = obj[{symbol_resource_handle}];
                                  if (handle === undefined) {{
                                      const localRep = repCnt++;
                                      repTable.set(localRep, {{ rep: obj, own: true }});
                                      handle = $resource_{prefix}new${lower_camel}(localRep);
                                      obj[{symbol_resource_handle}] = handle;
                                      finalizationRegistry_export${prefix}{lower_camel}.register(obj, handle, obj);
                                  }}
                                  return handle;
                              }}
                            "#
                        )
                    }
                }
            };

            format!(
                "{f}({{
                     componentIdx: {component_idx},
                     lowerFn: {lower_fn_js},
                 }})"
            )
        }

        InterfaceType::Borrow(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatBorrow));
            let table_idx = ty_idx.as_u32();
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatBorrow).name();
            format!("{f}.bind(null, {table_idx})")
        }

        InterfaceType::Future(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFuture));
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatFuture).name();
            let table_idx = ty_idx.as_u32();
            let table_ty = &component_types[*ty_idx];
            let component_idx = table_ty.instance.as_u32();
            let future_ty_idx = table_ty.ty;
            let future_ty = &component_types[future_ty_idx];
            let payload = future_ty.payload;
            let payload_ty_name_js = future_ty
                .payload
                .map(|iface_ty| format!("'{iface_ty:?}'"))
                .unwrap_or_else(|| "null".into());

            // Gather element metadata
            let (
                payload_size32,
                payload_align32,
                payload_flat_count_js,
                payload_lift_fn_js,
                payload_lower_fn_js,
                is_borrowed,
                is_none_type,
                is_numeric_type,
                is_async_value,
            ) = match payload {
                None => (
                    0,
                    0,
                    "0".into(),
                    "() => {{ throw new Error('empty future payload'); }}".into(),
                    "() => {{ throw new Error('empty future payload'); }}".into(),
                    false,
                    true,
                    false,
                    false,
                ),
                Some(payload_ty) => {
                    let cabi = instantiator.types.canonical_abi(&payload_ty);
                    (
                        cabi.size32,
                        cabi.align32,
                        cabi.flat_count
                            .map(|v| format!("{v}"))
                            .unwrap_or_else(|| "null".into()),
                        gen_flat_lift_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
                        gen_flat_lower_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
                        matches!(payload_ty, InterfaceType::Borrow(_)),
                        false,
                        matches!(
                            payload_ty,
                            InterfaceType::U8
                                | InterfaceType::U16
                                | InterfaceType::U32
                                | InterfaceType::U64
                                | InterfaceType::S8
                                | InterfaceType::S16
                                | InterfaceType::S32
                                | InterfaceType::S64
                                | InterfaceType::Float32
                                | InterfaceType::Float64
                        ),
                        matches!(
                            payload_ty,
                            InterfaceType::Stream(_) | InterfaceType::Future(_)
                        ),
                    )
                }
            };

            format!(
                r#"{f}.bind(null, {{
                       futureTableIdx: {table_idx},
                       componentIdx: {component_idx},
                       elemMeta: {{
                           liftFn: {payload_lift_fn_js},
                           lowerFn: {payload_lower_fn_js},
                           payloadTypeName: {payload_ty_name_js},
                           isNone: {is_none_type},
                           isNumeric: {is_numeric_type},
                           isBorrowed: {is_borrowed},
                           isAsyncValue: {is_async_value},
                           flatCount: {payload_flat_count_js},
                           align32: {payload_align32},
                           size32: {payload_size32},
                       }},
                   }})
                "#
            )
        }

        InterfaceType::Stream(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatStream));
            let table_idx = ty_idx.as_u32();
            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatStream).name();
            let table_ty = &component_types[*ty_idx];
            let component_idx = table_ty.instance.as_u32();
            let stream_ty_idx = table_ty.ty;
            let stream_ty = &component_types[stream_ty_idx];
            let payload = stream_ty.payload;
            let payload_ty_name_js = stream_ty
                .payload
                .map(|iface_ty| format!("'{iface_ty:?}'"))
                .unwrap_or_else(|| "null".into());

            // TODO(fix): payload u8 should be special cased here

            let (
                payload_size32,
                payload_align32,
                payload_flat_count_js,
                payload_lift_fn_js,
                payload_lower_fn_js,
                is_borrowed,
                is_none_type,
                is_numeric_type,
                is_async_value,
            ) = match payload {
                None => (
                    0,
                    0,
                    "0".into(),
                    "() => {{ throw new Error('empty stream payload'); }}".into(),
                    "() => {{ throw new Error('empty stream payload'); }}".into(),
                    false,
                    true,
                    false,
                    false,
                ),
                Some(payload_ty) => {
                    let cabi = instantiator.types.canonical_abi(&payload_ty);
                    (
                        cabi.size32,
                        cabi.align32,
                        cabi.flat_count
                            .map(|v| format!("{v}"))
                            .unwrap_or_else(|| "null".into()),
                        gen_flat_lift_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
                        gen_flat_lower_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
                        matches!(payload_ty, InterfaceType::Borrow(_)),
                        false,
                        matches!(
                            payload_ty,
                            InterfaceType::U8
                                | InterfaceType::U16
                                | InterfaceType::U32
                                | InterfaceType::U64
                                | InterfaceType::S8
                                | InterfaceType::S16
                                | InterfaceType::S32
                                | InterfaceType::S64
                                | InterfaceType::Float32
                                | InterfaceType::Float64
                        ),
                        matches!(
                            payload_ty,
                            InterfaceType::Stream(_) | InterfaceType::Future(_)
                        ),
                    )
                }
            };

            format!(
                r#"{f}({{
                       streamTableIdx: {table_idx},
                       componentIdx: {component_idx},
                       elemMeta: {{
                           liftFn: {payload_lift_fn_js},
                           lowerFn: {payload_lower_fn_js},
                           payloadTypeName: {payload_ty_name_js},
                           isNone: {is_none_type},
                           isNumeric: {is_numeric_type},
                           isBorrowed: {is_borrowed},
                           isAsyncValue: {is_async_value},
                           flatCount: {payload_flat_count_js},
                           align32: {payload_align32},
                           size32: {payload_size32},
                       }},
                   }})
                "#
            )
        }

        InterfaceType::ErrorContext(ty_idx) => {
            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatErrorContext));
            let table_idx = ty_idx.as_u32();
            let lower_flat_err_ctx_fn =
                Intrinsic::Lower(LowerIntrinsic::LowerFlatErrorContext).name();
            format!("{lower_flat_err_ctx_fn}.bind(null, {table_idx})")
        }
    }
}

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

    /// Helper to extract just the compat key string for cleaner test assertions.
    fn compat_key(version_str: &str) -> Option<String> {
        semver_compat_key(version_str).map(|(key, _)| key)
    }

    #[test]
    fn test_semver_compat_key() {
        assert_eq!(compat_key("1.0.0"), Some("1".into()));
        assert_eq!(compat_key("1.2.3"), Some("1".into()));
        assert_eq!(compat_key("2.0.0"), Some("2".into()));
        assert_eq!(compat_key("0.2.0"), Some("0.2".into()));
        assert_eq!(compat_key("0.2.10"), Some("0.2".into()));
        assert_eq!(compat_key("0.1.0"), Some("0.1".into()));
        assert_eq!(compat_key("0.0.1"), None);
        assert_eq!(compat_key("1.0.0-rc.1"), None);
        assert_eq!(compat_key("0.2.0-pre"), None);
        assert_eq!(compat_key("not-a-version"), None);
    }

    #[test]
    fn test_semver_compat_key_returns_parsed_version() {
        let (key, ver) = semver_compat_key("1.2.3").unwrap();
        assert_eq!(key, "1");
        assert_eq!(ver, Version::new(1, 2, 3));
    }

    #[test]
    fn test_map_import_exact_match() {
        let mut map = HashMap::new();
        map.insert("wasi:http/types@0.2.0".into(), "./http.js#types".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.0"),
            ("./http.js".into(), Some("types".into()))
        );
    }

    #[test]
    fn test_map_import_sans_version_match() {
        let mut map = HashMap::new();
        map.insert("wasi:http/types".into(), "./http.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.10"),
            ("./http.js".into(), None)
        );
    }

    #[test]
    fn test_map_import_wildcard_sans_version() {
        // Unversioned wildcard key matches via version-stripped path (pre-existing logic)
        let mut map = HashMap::new();
        map.insert("wasi:http/*".into(), "./http.js#*".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.10"),
            ("./http.js".into(), Some("types".into()))
        );
    }

    #[test]
    fn test_map_import_semver_exact_key() {
        // Map has @0.2.0, import is @0.2.10 — should match via semver
        let mut map = HashMap::new();
        map.insert("wasi:http/types@0.2.0".into(), "./http.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.10"),
            ("./http.js".into(), None)
        );
    }

    #[test]
    fn test_map_import_semver_wildcard_key() {
        // Map has wasi:http/*@0.2.0, import is @0.2.10 — should match via semver
        let mut map = HashMap::new();
        map.insert("wasi:http/*@0.2.1".into(), "./http.js#*".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.10"),
            ("./http.js".into(), Some("types".into()))
        );
    }

    #[test]
    fn test_map_import_semver_lower_import_version() {
        // Import version (0.2.1) is lower than map entry (0.2.10) — same compat track
        let mut map = HashMap::new();
        map.insert("wasi:http/types@0.2.10".into(), "./http.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.1"),
            ("./http.js".into(), None)
        );
    }

    #[test]
    fn test_map_import_semver_no_cross_minor() {
        // 0.2.x should NOT match 0.3.x
        let mut map = HashMap::new();
        map.insert("wasi:http/types@0.3.0".into(), "./http.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.10"),
            ("wasi:http/types".into(), None)
        );
    }

    #[test]
    fn test_map_import_semver_prefers_highest() {
        // Multiple compatible versions — should prefer highest
        let mut map = HashMap::new();
        map.insert("wasi:http/types@0.2.1".into(), "./http-old.js".into());
        map.insert("wasi:http/types@0.2.5".into(), "./http-new.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.10"),
            ("./http-new.js".into(), None)
        );
    }

    #[test]
    fn test_map_import_no_match_prerelease() {
        let mut map = HashMap::new();
        map.insert("wasi:http/types@0.2.0-rc.1".into(), "./http.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.2.0"),
            ("wasi:http/types".into(), None)
        );
    }

    #[test]
    fn test_map_import_no_match_zero_zero() {
        let mut map = HashMap::new();
        map.insert("wasi:http/types@0.0.1".into(), "./http.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@0.0.2"),
            ("wasi:http/types".into(), None)
        );
    }

    #[test]
    fn test_map_import_semver_major_version() {
        // Major version compat: 1.0.0 and 1.2.3 share compat key "1"
        let mut map = HashMap::new();
        map.insert("wasi:http/types@1.0.0".into(), "./http.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@1.2.3"),
            ("./http.js".into(), None)
        );
    }

    #[test]
    fn test_map_import_semver_no_cross_major() {
        // 1.x.y should NOT match 2.x.y
        let mut map = HashMap::new();
        map.insert("wasi:http/types@1.0.0".into(), "./http.js".into());
        let map = Some(map);
        assert_eq!(
            map_import(&map, "wasi:http/types@2.0.0"),
            ("wasi:http/types".into(), None)
        );
    }

    #[test]
    fn test_map_import_no_map() {
        // No map provided — returns import sans version
        assert_eq!(
            map_import(&None, "wasi:http/types@0.2.0"),
            ("wasi:http/types".into(), None)
        );
    }

    #[test]
    fn test_map_import_no_map_unversioned() {
        // No map, no version — returns import as-is
        assert_eq!(
            map_import(&None, "wasi:http/types"),
            ("wasi:http/types".into(), None)
        );
    }

    #[test]
    fn test_parse_mapping_with_hash() {
        assert_eq!(
            parse_mapping("./http.js#types"),
            ("./http.js".into(), Some("types".into()))
        );
    }

    #[test]
    fn test_parse_mapping_without_hash() {
        assert_eq!(parse_mapping("./http.js"), ("./http.js".into(), None));
    }

    #[test]
    fn test_parse_mapping_leading_hash() {
        // Leading '#' should not be treated as a separator
        assert_eq!(parse_mapping("#foo"), ("#foo".into(), None));
    }

    #[test]
    fn test_parse_mapping_empty() {
        assert_eq!(parse_mapping(""), ("".into(), None));
    }
}