File: observable.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (3305 lines) | stat: -rw-r--r-- 128,795 bytes parent folder | download | duplicates (5)
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
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/dom/observable.h"

#include "base/types/pass_key.h"
#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_catch_callback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_mapper.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_observable_inspector.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_observable_inspector_abort_handler.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_observer.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_observer_callback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_observer_complete_callback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_predicate.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_reducer.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_subscribe_callback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_subscribe_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_observableinspector_observercallback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_observer_observercallback.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_visitor.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_void_function.h"
#include "third_party/blink/renderer/core/dom/abort_controller.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/observable_internal_observer.h"
#include "third_party/blink/renderer/core/dom/subscriber.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"

namespace blink {

namespace {

// A helper wrapper since we cannot hold `Member<ScriptValue>` directly.
class ScriptValueHolder final : public GarbageCollected<ScriptValueHolder> {
 public:
  explicit ScriptValueHolder(ScriptValue value) : value_(value) {}
  const ScriptValue& Value() const { return value_; }
  void Trace(Visitor* visitor) const { visitor->Trace(value_); }

 private:
  ScriptValue value_;
};

class RejectPromiseAbortAlgorithm final : public AbortSignal::Algorithm {
 public:
  RejectPromiseAbortAlgorithm(ScriptPromiseResolverBase* resolver,
                              AbortSignal* signal)
      : resolver_(resolver), signal_(signal) {
    CHECK(resolver);
    CHECK(signal);
  }

  void Run() override {
    resolver_->Reject(signal_->reason(resolver_->GetScriptState()));
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(resolver_);
    visitor->Trace(signal_);

    Algorithm::Trace(visitor);
  }

 private:
  // The `ScriptPromiseResolverBase` that `this` must reject when `signal_` is
  // aborted (as notified by `Run()` above).
  Member<ScriptPromiseResolverBase> resolver_;
  // Never null. We have to store the `signal_` that `this` is associated with
  // in order to get the abort reason.
  Member<AbortSignal> signal_;
};

class ScriptCallbackInternalObserver final : public ObservableInternalObserver {
 public:
  ScriptCallbackInternalObserver(V8ObserverCallback* next_callback,
                                 V8ObserverCallback* error_callback,
                                 V8ObserverCompleteCallback* complete_callback)
      : next_callback_(next_callback),
        error_callback_(error_callback),
        complete_callback_(complete_callback) {}

  void Next(ScriptValue value) override {
    if (next_callback_) {
      next_callback_->InvokeAndReportException(nullptr, value);
    }
  }
  void Error(ScriptState* script_state, ScriptValue error_value) override {
    if (error_callback_) {
      error_callback_->InvokeAndReportException(nullptr, error_value);
    } else {
      // This is the "default error algorithm" [1] that must be invoked in the
      // case where `error_callback_` was not provided.
      //
      // [1]: https://wicg.github.io/observable/#default-error-algorithm
      ObservableInternalObserver::Error(script_state, error_value);
    }
  }
  void Complete() override {
    if (complete_callback_) {
      complete_callback_->InvokeAndReportException(nullptr);
    }
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(next_callback_);
    visitor->Trace(error_callback_);
    visitor->Trace(complete_callback_);
  }

 private:
  Member<V8ObserverCallback> next_callback_;
  Member<V8ObserverCallback> error_callback_;
  Member<V8ObserverCompleteCallback> complete_callback_;
};

class ToArrayInternalObserver final : public ObservableInternalObserver {
 public:
  ToArrayInternalObserver(ScriptPromiseResolver<IDLSequence<IDLAny>>* resolver,
                          AbortSignal::AlgorithmHandle* handle)
      : resolver_(resolver), abort_algorithm_handle_(handle) {}

  void Next(ScriptValue value) override {
    // "Append the passed in value to values."
    values_.push_back(value);
  }
  void Error(ScriptState* script_state, ScriptValue error_value) override {
    abort_algorithm_handle_.Clear();

    // "Reject p with the passed in error."
    resolver_->Reject(error_value);
  }
  void Complete() override {
    abort_algorithm_handle_.Clear();

    // "Resolve p with values."
    resolver_->Resolve(values_);
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(resolver_);
    visitor->Trace(values_);
    visitor->Trace(abort_algorithm_handle_);
  }

 private:
  Member<ScriptPromiseResolver<IDLSequence<IDLAny>>> resolver_;
  HeapVector<ScriptValue> values_;
  Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
};

// This is the internal observer associated with the `reduce()` operator. See
// https://wicg.github.io/observable/#dom-observable-reduce for its definition
// and spec prose.
class OperatorReduceInternalObserver final : public ObservableInternalObserver {
 public:
  OperatorReduceInternalObserver(ScriptPromiseResolver<IDLAny>* resolver,
                                 AbortController* controller,
                                 V8Reducer* reducer,
                                 std::optional<ScriptValue> initial_value,
                                 AbortSignal::AlgorithmHandle* handle)
      : resolver_(resolver),
        controller_(controller),
        reducer_(reducer),
        abort_algorithm_handle_(handle) {
    CHECK(resolver_);
    CHECK(controller_);
    CHECK(reducer_);
    CHECK(abort_algorithm_handle_);
    if (initial_value) {
      accumulator_ = MakeGarbageCollected<ScriptValueHolder>(*initial_value);
    }
  }

  void Next(ScriptValue value) override {
    if (!accumulator_) [[unlikely]] {
      // For all subsequent values, we will take the path where `accumulator_`
      // is *not* null, and we invoke `reducer_` with it.
      accumulator_ = MakeGarbageCollected<ScriptValueHolder>(value);
      // Adjust the index, so that when we first call `reducer_` on the *second*
      // value, the index is adjusted accordingly.
      idx_++;
      return;
    }

    // `ScriptState::Scope` can only be created in a valid context, so
    // early-return if we're in a detached one.
    ScriptState* script_state = resolver_->GetScriptState();
    if (!script_state->ContextIsValid()) {
      return;
    }

    ScriptState::Scope scope(script_state);
    v8::TryCatch try_catch(script_state->GetIsolate());
    const v8::Maybe<ScriptValue> result = reducer_->Invoke(
        /*thisArg=*/nullptr, /*accumulator=*/accumulator_->Value(),
        /*currentValue=*/value, /*index=*/idx_++);
    if (try_catch.HasCaught()) {
      abort_algorithm_handle_.Clear();
      ScriptValue exception(script_state->GetIsolate(), try_catch.Exception());
      resolver_->Reject(exception);
      controller_->abort(script_state, exception);
      return;
    }

    // Since we handled the exception case above, `result` must not be
    // `v8::Nothing`.
    accumulator_ = MakeGarbageCollected<ScriptValueHolder>(result.ToChecked());
  }

  void Error(ScriptState* script_state, ScriptValue error_value) override {
    abort_algorithm_handle_.Clear();

    resolver_->Reject(error_value);
  }
  void Complete() override {
    abort_algorithm_handle_.Clear();

    if (accumulator_) {
      resolver_->Resolve(accumulator_->Value());
    } else {
      v8::Isolate* isolate = resolver_->GetScriptState()->GetIsolate();
      resolver_->Reject(V8ThrowException::CreateTypeError(
          isolate, "Reduce of empty array with no initial value"));
    }
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(resolver_);
    visitor->Trace(controller_);
    visitor->Trace(reducer_);
    visitor->Trace(accumulator_);
    visitor->Trace(abort_algorithm_handle_);
  }

 private:
  uint64_t idx_ = 0;
  Member<ScriptPromiseResolver<IDLAny>> resolver_;
  Member<AbortController> controller_;
  Member<V8Reducer> reducer_;
  // `accumulator_` is initually null unless `initialValue` is passed into the
  // constructor of `this`. When `accumulator_` is initially null, we eventually
  // set it to the first value that `this` encounters in `Next()`. Then, for all
  // subsequent values, we use `accumulator_` as the "accumulator" argument for
  // `reducer_` callback above.
  Member<ScriptValueHolder> accumulator_;
  Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
};

// This is the internal observer associated with the `find()` operator. See
// https://wicg.github.io/observable/#dom-observable-find for its definition
// and spec prose quoted below.
class OperatorFindInternalObserver final : public ObservableInternalObserver {
 public:
  OperatorFindInternalObserver(ScriptPromiseResolver<IDLAny>* resolver,
                               AbortController* controller,
                               V8Predicate* predicate,
                               AbortSignal::AlgorithmHandle* handle)
      : resolver_(resolver),
        controller_(controller),
        predicate_(predicate),
        abort_algorithm_handle_(handle) {
    CHECK(resolver_);
    CHECK(controller_);
    CHECK(predicate_);
    CHECK(abort_algorithm_handle_);
  }

  void Next(ScriptValue value) override {
    // `ScriptState::Scope` can only be created in a valid context, so
    // early-return if we're in a detached one.
    ScriptState* script_state = resolver_->GetScriptState();
    if (!script_state->ContextIsValid()) {
      return;
    }

    ScriptState::Scope scope(script_state);
    v8::TryCatch try_catch(script_state->GetIsolate());
    const v8::Maybe<bool> maybe_matches =
        predicate_->Invoke(nullptr, value, idx_++);
    if (try_catch.HasCaught()) {
      abort_algorithm_handle_.Clear();
      ScriptValue exception(script_state->GetIsolate(), try_catch.Exception());
      resolver_->Reject(exception);
      controller_->abort(script_state, exception);
      return;
    }

    // Since we handled the exception case above, `maybe_matches` must not be
    // `v8::Nothing`.
    const bool matches = maybe_matches.ToChecked();
    if (matches) {
      abort_algorithm_handle_.Clear();
      resolver_->Resolve(value);
      controller_->abort(resolver_->GetScriptState());
    }
  }

  void Error(ScriptState* script_state, ScriptValue error_value) override {
    abort_algorithm_handle_.Clear();

    // "Reject p with the passed in error."
    resolver_->Reject(error_value);
  }
  void Complete() override {
    abort_algorithm_handle_.Clear();

    // "Resolve p with undefined."
    resolver_->Resolve(
        v8::Undefined(resolver_->GetScriptState()->GetIsolate()));
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(resolver_);
    visitor->Trace(controller_);
    visitor->Trace(predicate_);
    visitor->Trace(abort_algorithm_handle_);
  }

 private:
  uint64_t idx_ = 0;
  Member<ScriptPromiseResolver<IDLAny>> resolver_;
  Member<AbortController> controller_;
  Member<V8Predicate> predicate_;
  Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
};

// This is the internal observer associated with the `every()` operator. See
// https://wicg.github.io/observable/#dom-observable-every for its definition
// and spec prose quoted below.
class OperatorEveryInternalObserver final : public ObservableInternalObserver {
 public:
  OperatorEveryInternalObserver(ScriptPromiseResolver<IDLBoolean>* resolver,
                                AbortController* controller,
                                V8Predicate* predicate,
                                AbortSignal::AlgorithmHandle* handle)
      : resolver_(resolver),
        controller_(controller),
        predicate_(predicate),
        abort_algorithm_handle_(handle) {
    CHECK(resolver_);
    CHECK(controller_);
    CHECK(predicate_);
    CHECK(abort_algorithm_handle_);
  }

  void Next(ScriptValue value) override {
    // `ScriptState::Scope` can only be created in a valid context, so
    // early-return if we're in a detached one.
    ScriptState* script_state = resolver_->GetScriptState();
    if (!script_state->ContextIsValid()) {
      return;
    }

    ScriptState::Scope scope(script_state);
    v8::TryCatch try_catch(script_state->GetIsolate());
    const v8::Maybe<bool> maybe_matches =
        predicate_->Invoke(nullptr, value, idx_++);
    if (try_catch.HasCaught()) {
      abort_algorithm_handle_.Clear();
      ScriptValue exception(script_state->GetIsolate(), try_catch.Exception());
      resolver_->Reject(exception);
      controller_->abort(script_state, exception);
      return;
    }

    // Since we handled the exception case above, `maybe_matches` must not be
    // `v8::Nothing`.
    const bool matches = maybe_matches.ToChecked();
    if (!matches) {
      abort_algorithm_handle_.Clear();
      resolver_->Resolve(false);
      controller_->abort(resolver_->GetScriptState());
    }
  }

  void Error(ScriptState* script_state, ScriptValue error_value) override {
    abort_algorithm_handle_.Clear();

    // "Reject p with the passed in error."
    resolver_->Reject(error_value);
  }
  void Complete() override {
    abort_algorithm_handle_.Clear();

    // "Resolve p with true."
    resolver_->Resolve(true);
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(resolver_);
    visitor->Trace(controller_);
    visitor->Trace(predicate_);
    visitor->Trace(abort_algorithm_handle_);
  }

 private:
  uint64_t idx_ = 0;
  Member<ScriptPromiseResolver<IDLBoolean>> resolver_;
  Member<AbortController> controller_;
  Member<V8Predicate> predicate_;
  Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
};

// This is the internal observer associated with the `some()` operator. See
// https://wicg.github.io/observable/#dom-observable-some for its definition
// and spec prose quoted below.
class OperatorSomeInternalObserver final : public ObservableInternalObserver {
 public:
  OperatorSomeInternalObserver(ScriptPromiseResolver<IDLBoolean>* resolver,
                               AbortController* controller,
                               V8Predicate* predicate,
                               AbortSignal::AlgorithmHandle* handle)
      : resolver_(resolver),
        controller_(controller),
        predicate_(predicate),
        abort_algorithm_handle_(handle) {
    CHECK(resolver_);
    CHECK(controller_);
    CHECK(predicate_);
    CHECK(abort_algorithm_handle_);
  }

  void Next(ScriptValue value) override {
    // `ScriptState::Scope` can only be created in a valid context, so
    // early-return if we're in a detached one.
    ScriptState* script_state = resolver_->GetScriptState();
    if (!script_state->ContextIsValid()) {
      return;
    }

    ScriptState::Scope scope(script_state);
    v8::TryCatch try_catch(script_state->GetIsolate());
    const v8::Maybe<bool> maybe_matches =
        predicate_->Invoke(nullptr, value, idx_++);
    if (try_catch.HasCaught()) {
      abort_algorithm_handle_.Clear();
      ScriptValue exception(script_state->GetIsolate(), try_catch.Exception());
      resolver_->Reject(exception);
      controller_->abort(script_state, exception);
      return;
    }

    // Since we handled the exception case above, `maybe_matches` must not be
    // `v8::Nothing`.
    const bool matches = maybe_matches.ToChecked();
    if (matches) {
      abort_algorithm_handle_.Clear();
      resolver_->Resolve(true);
      controller_->abort(resolver_->GetScriptState());
    }
  }

  void Error(ScriptState* script_state, ScriptValue error_value) override {
    abort_algorithm_handle_.Clear();

    // "Reject p with the passed in error."
    resolver_->Reject(error_value);
  }
  void Complete() override {
    abort_algorithm_handle_.Clear();

    // "Resolve p with false".
    resolver_->Resolve(false);
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(resolver_);
    visitor->Trace(controller_);
    visitor->Trace(predicate_);
    visitor->Trace(abort_algorithm_handle_);
  }

 private:
  uint64_t idx_ = 0;
  Member<ScriptPromiseResolver<IDLBoolean>> resolver_;
  Member<AbortController> controller_;
  Member<V8Predicate> predicate_;
  Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
};

// This is the internal observer associated with the `last()` operator. See
// https://wicg.github.io/observable/#dom-observable-last for its definition
// and spec prose quoted below.
class OperatorLastInternalObserver final : public ObservableInternalObserver {
 public:
  OperatorLastInternalObserver(ScriptPromiseResolver<IDLAny>* resolver,
                               AbortSignal::AlgorithmHandle* handle)
      : resolver_(resolver), abort_algorithm_handle_(handle) {}

  void Next(ScriptValue value) override {
    last_value_ = MakeGarbageCollected<ScriptValueHolder>(value);
  }
  void Error(ScriptState* script_state, ScriptValue error_value) override {
    abort_algorithm_handle_.Clear();

    // "Reject p with the passed in error."
    resolver_->Reject(error_value);
  }
  void Complete() override {
    abort_algorithm_handle_.Clear();

    // "If lastValue is not null, resolve p with lastValue."
    if (last_value_) {
      resolver_->Resolve(last_value_->Value());
      return;
    }

    // "Otherwise, reject p with a new RangeError."
    v8::Isolate* isolate = resolver_->GetScriptState()->GetIsolate();
    resolver_->Reject(
        ScriptValue(isolate, V8ThrowException::CreateRangeError(
                                 isolate, "No values in Observable")));
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(resolver_);
    visitor->Trace(abort_algorithm_handle_);
    visitor->Trace(last_value_);
  }

 private:
  Member<ScriptPromiseResolver<IDLAny>> resolver_;
  Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
  Member<ScriptValueHolder> last_value_;
};

// This is the internal observer associated with the `first()` operator. See
// https://wicg.github.io/observable/#dom-observable-first for its definition
// and spec prose quoted below.
class OperatorFirstInternalObserver final : public ObservableInternalObserver {
 public:
  OperatorFirstInternalObserver(ScriptPromiseResolver<IDLAny>* resolver,
                                AbortController* controller,
                                AbortSignal::AlgorithmHandle* handle)
      : resolver_(resolver),
        controller_(controller),
        abort_algorithm_handle_(handle) {}

  void Next(ScriptValue value) override {
    abort_algorithm_handle_.Clear();

    // "Resolve p with the passed in value."
    resolver_->Resolve(value);
    // "Signal abort controller".
    controller_->abort(resolver_->GetScriptState());
  }
  void Error(ScriptState* script_state, ScriptValue error_value) override {
    abort_algorithm_handle_.Clear();

    // "Reject p with the passed in error."
    resolver_->Reject(error_value);
  }
  void Complete() override {
    abort_algorithm_handle_.Clear();

    // "Reject p with a new RangeError."
    v8::Isolate* isolate = resolver_->GetScriptState()->GetIsolate();
    resolver_->Reject(
        ScriptValue(isolate, V8ThrowException::CreateRangeError(
                                 isolate, "No values in Observable")));
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(resolver_);
    visitor->Trace(controller_);
    visitor->Trace(abort_algorithm_handle_);
  }

 private:
  Member<ScriptPromiseResolver<IDLAny>> resolver_;
  Member<AbortController> controller_;
  Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
};

class OperatorForEachInternalObserver final
    : public ObservableInternalObserver {
 public:
  OperatorForEachInternalObserver(ScriptPromiseResolver<IDLUndefined>* resolver,
                                  AbortController* controller,
                                  V8Visitor* callback,
                                  AbortSignal::AlgorithmHandle* handle)
      : resolver_(resolver),
        controller_(controller),
        callback_(callback),
        abort_algorithm_handle_(handle) {}

  void Next(ScriptValue value) override {
    // Invoke callback with the passed in value.
    //
    // If an exception |E| was thrown, then reject |p| with |E| and signal
    // abort |visitor callback controller| with |E|.

    // `ScriptState::Scope` can only be created in a valid context, so
    // early-return if we're in a detached one.
    ScriptState* script_state = resolver_->GetScriptState();
    if (!script_state->ContextIsValid()) {
      return;
    }

    ScriptState::Scope scope(script_state);
    v8::TryCatch try_catch(script_state->GetIsolate());
    // Invoking `callback_` can detach the context, but that's OK, nothing below
    // this invocation relies on an attached/valid context.
    std::ignore = callback_->Invoke(nullptr, value, idx_++);
    if (try_catch.HasCaught()) {
      ScriptValue exception(script_state->GetIsolate(), try_catch.Exception());
      resolver_->Reject(exception);
      controller_->abort(script_state, exception);
    }
  }
  void Error(ScriptState* script_state, ScriptValue error_value) override {
    abort_algorithm_handle_.Clear();

    // "Reject p with the passed in error."
    resolver_->Reject(error_value);
  }
  void Complete() override {
    abort_algorithm_handle_.Clear();

    // "Resolve p with undefined."
    resolver_->Resolve();
  }

  void Trace(Visitor* visitor) const override {
    ObservableInternalObserver::Trace(visitor);

    visitor->Trace(resolver_);
    visitor->Trace(controller_);
    visitor->Trace(callback_);
    visitor->Trace(abort_algorithm_handle_);
  }

 private:
  uint64_t idx_ = 0;
  Member<ScriptPromiseResolver<IDLUndefined>> resolver_;
  Member<AbortController> controller_;
  Member<V8Visitor> callback_;
  Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
};

// This delegate is used by the `Observer#from()` operator, in the case where
// the given `any` value is a `Promise`. It simply utilizes the promise's
// then/catch handlers to pipe the corresponding fulfilled/rejection value to
// the Observable in a one-shot manner.
class OperatorFromPromiseSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  explicit OperatorFromPromiseSubscribeDelegate(ScriptPromise<IDLAny> promise)
      : promise_(promise) {}

  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    promise_.Unwrap().Then(
        script_state,
        MakeGarbageCollected<ObservablePromiseResolverFunction>(
            subscriber,
            ObservablePromiseResolverFunction::ResolveType::kFulfill),
        MakeGarbageCollected<ObservablePromiseResolverFunction>(
            subscriber,
            ObservablePromiseResolverFunction::ResolveType::kReject));
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(promise_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class ObservablePromiseResolverFunction final
      : public ThenCallable<IDLAny, ObservablePromiseResolverFunction> {
   public:
    enum class ResolveType { kFulfill, kReject };

    ObservablePromiseResolverFunction(Subscriber* subscriber, ResolveType type)
        : subscriber_(subscriber), type_(type) {
      CHECK(subscriber_);
    }

    void React(ScriptState* script_state, ScriptValue value) {
      if (type_ == ResolveType::kFulfill) {
        subscriber_->next(value);
        subscriber_->complete(script_state);
      } else {
        subscriber_->error(script_state, value);
      }
    }

    void Trace(Visitor* visitor) const final {
      visitor->Trace(subscriber_);

      ThenCallable<IDLAny, ObservablePromiseResolverFunction>::Trace(visitor);
    }

   private:
    Member<Subscriber> subscriber_;
    ResolveType type_;
  };

  MemberScriptPromise<IDLAny> promise_;
};

// This is the subscribe delegate for the `catch()` operator. It allows one to
// "catch" errors pushed from upstream Observables, and handle them by returning
// a new Observable derived from that error. The Observable returned from the
// catch handler is immediately subscribed to, and its values are plumbed
// downstream. See https://wicg.github.io/observable/#dom-observable-catch.
class OperatorCatchSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorCatchSubscribeDelegate(Observable* source_observable,
                                 V8CatchCallback* catch_callback)
      : source_observable_(source_observable),
        catch_callback_(catch_callback) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state,
                                                     catch_callback_),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);
    visitor->Trace(catch_callback_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* outer_subscriber,
                           ScriptState* script_state,
                           V8CatchCallback* catch_callback)
        : outer_subscriber_(outer_subscriber),
          script_state_(script_state),
          catch_callback_(catch_callback) {
      CHECK(outer_subscriber_);
      CHECK(script_state_);
      CHECK(catch_callback_);
    }

    void Next(ScriptValue value) override { outer_subscriber_->next(value); }
    void Error(ScriptState*, ScriptValue error) override {
      // `ScriptState::Scope` can only be created in a valid context, so
      // early-return if we're in a detached one.
      if (!script_state_->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state_);
      v8::TryCatch try_catch(script_state_->GetIsolate());
      // This is the return value of the `catch_callback_`, which must be
      // convertible to an `Observable` object.
      v8::Maybe<ScriptValue> mapped_value =
          catch_callback_->Invoke(nullptr, error);
      if (try_catch.HasCaught()) {
        outer_subscriber_->error(
            script_state_,
            ScriptValue(script_state_->GetIsolate(), try_catch.Exception()));
        return;
      }

      // Since we handled the exception case above, `mapped_value` must not be
      // `v8::Nothing`.
      Observable* inner_observable =
          Observable::from(script_state_, mapped_value.ToChecked(),
                           PassThroughException(script_state_->GetIsolate()));
      if (try_catch.HasCaught()) {
        ApplyContextToException(
            script_state_, try_catch.Exception(),
            ExceptionContext(v8::ExceptionContext::kOperation, "Observable",
                             "catch"));
        outer_subscriber_->error(
            script_state_,
            ScriptValue(script_state_->GetIsolate(), try_catch.Exception()));
        return;
      }

      SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
      options->setSignal(outer_subscriber_->signal());

      inner_observable->SubscribeWithNativeObserver(
          script_state_,
          MakeGarbageCollected<InnerCatchHandlerObserver>(outer_subscriber_,
                                                          script_state_),
          options);
    }
    void Complete() override { outer_subscriber_->complete(script_state_); }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(outer_subscriber_);
      visitor->Trace(script_state_);
      visitor->Trace(catch_callback_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    // This is the internal observer that manages the subscription for the
    // Observable returned by the catch handler. It's a trivial pass-through.
    //
    // TODO(crbug.com/40282760): Deduplicate this with
    // `OperatorTakeUntilSubscribeDelegate::SourceInternalObserver`, which is an
    // exact copy of this, by factoring this out into a more common class.
    class InnerCatchHandlerObserver final : public ObservableInternalObserver {
     public:
      InnerCatchHandlerObserver(Subscriber* outer_subscriber,
                                ScriptState* script_state)
          : outer_subscriber_(outer_subscriber), script_state_(script_state) {}

      void Next(ScriptValue value) override { outer_subscriber_->next(value); }
      void Error(ScriptState* script_state, ScriptValue value) override {
        outer_subscriber_->error(script_state, value);
      }
      void Complete() override { outer_subscriber_->complete(script_state_); }

      void Trace(Visitor* visitor) const override {
        visitor->Trace(outer_subscriber_);
        visitor->Trace(script_state_);

        ObservableInternalObserver::Trace(visitor);
      }

     private:
      Member<Subscriber> outer_subscriber_;
      Member<ScriptState> script_state_;
    };

    Member<Subscriber> outer_subscriber_;
    Member<ScriptState> script_state_;
    Member<V8CatchCallback> catch_callback_;
  };

  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  //
  // All of these members are essentially state-less, and are just held here so
  // that we can pass them into the `SourceInternalObserver` above, which gets
  // created for each new subscription.
  Member<Observable> source_observable_;
  Member<V8CatchCallback> catch_callback_;
};

class OperatorFinallySubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorFinallySubscribeDelegate(Observable* source_observable,
                                   V8VoidFunction* callback)
      : source_observable_(source_observable), callback_(callback) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    subscriber->addTeardown(callback_);
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);
    visitor->Trace(callback_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* subscriber, ScriptState* script_state)
        : subscriber_(subscriber), script_state_(script_state) {
      CHECK(subscriber_);
      CHECK(script_state_);
    }

    void Next(ScriptValue value) override { subscriber_->next(value); }

    void Error(ScriptState*, ScriptValue error) override {
      subscriber_->error(script_state_, error);
    }

    void Complete() override { subscriber_->complete(script_state_); }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(subscriber_);
      visitor->Trace(script_state_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    Member<Subscriber> subscriber_;
    Member<ScriptState> script_state_;
  };
  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  Member<Observable> source_observable_;
  Member<V8VoidFunction> callback_;
};

// This is the subscribe delegate for the `inspect()` operator. It allows one to
// supply a pseudo "Observer" dictionary, specifically an `ObservableInspector`,
// which can tap into the direct outputs of a source Observable. It mirrors its
// `next()`, `error()`, and `complete()` handlers, as well as letting you pass
// in two supplemental callbacks:
//   1. A `subscribe()` callback, which runs immediately when the
//      `Observable`-returned-from-`inspect()` is subscribed to, and just before
//      *it* subscribes to its source Observable. Errors from this callback are
//      piped to the consumer Subscriber's `error()` handler, and the
//      subscription is promptly closed.
//   2. An `abort()` callback, which is run specifically for consumer-initiated
//      unsubscriptions/aborts, NOT producer (source-Observable-initiated)
//      unsubscriptions (via `complete()` or `error()`). See the documentation
//      in `OperatorInspectSubscribeDelegate::SourceInternalObserver::Error()`.
class OperatorInspectSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorInspectSubscribeDelegate(
      Observable* source_observable,
      V8ObserverCallback* next_callback,
      V8ObserverCallback* error_callback,
      V8ObserverCompleteCallback* complete_callback,
      V8VoidFunction* subscribe_callback,
      V8ObservableInspectorAbortHandler* abort_callback)
      : source_observable_(source_observable),
        next_callback_(next_callback),
        error_callback_(error_callback),
        complete_callback_(complete_callback),
        subscribe_callback_(subscribe_callback),
        abort_callback_(abort_callback) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    if (subscribe_callback_) {
      // `ScriptState::Scope` can only be created in a valid context, so
      // early-return if we're in a detached one.
      if (!script_state->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state);
      v8::TryCatch try_catch(script_state->GetIsolate());
      std::ignore = subscribe_callback_->Invoke(nullptr);
      if (try_catch.HasCaught()) {
        ScriptValue exception(script_state->GetIsolate(),
                              try_catch.Exception());
        subscriber->error(script_state, exception);
        return;
      }
    }

    AbortSignal::AlgorithmHandle* abort_algorithm_handle = nullptr;
    if (abort_callback_) {
      abort_algorithm_handle = subscriber->signal()->AddAlgorithm(
          MakeGarbageCollected<InspectorAbortHandlerAlgorithm>(
              abort_callback_, subscriber->signal(), script_state));
    }

    // At this point, the `subscribe_callback_` has been called and has not
    // thrown an exception, so we proceed to *actually* subscribe to the
    // underlying Observable, invoking *its* callback through the normal flow
    // and so on.
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(
            subscriber, script_state, abort_algorithm_handle, next_callback_,
            error_callback_, complete_callback_),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);

    visitor->Trace(next_callback_);
    visitor->Trace(error_callback_);
    visitor->Trace(complete_callback_);
    visitor->Trace(abort_callback_);
    visitor->Trace(subscribe_callback_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class InspectorAbortHandlerAlgorithm final : public AbortSignal::Algorithm {
   public:
    InspectorAbortHandlerAlgorithm(
        V8ObservableInspectorAbortHandler* abort_handler,
        AbortSignal* signal,
        ScriptState* script_state)
        : abort_handler_(abort_handler),
          signal_(signal),
          script_state_(script_state) {
      CHECK(abort_handler_);
      CHECK(signal_);
      CHECK(script_state_);
    }

    void Run() override {
      abort_handler_->InvokeAndReportException(nullptr,
                                               signal_->reason(script_state_));
    }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(abort_handler_);
      visitor->Trace(signal_);
      visitor->Trace(script_state_);

      Algorithm::Trace(visitor);
    }

   private:
    // Never null. The JS callback that `this` runs when `signal_ is aborted.
    Member<V8ObservableInspectorAbortHandler> abort_handler_;
    // Never null. We have to store the `signal_` that `this` is associated with
    // in order to get the abort reason.
    Member<AbortSignal> signal_;
    Member<ScriptState> script_state_;
  };

  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* subscriber,
                           ScriptState* script_state,
                           AbortSignal::AlgorithmHandle* abort_algorithm_handle,
                           V8ObserverCallback* next_callback,
                           V8ObserverCallback* error_callback,
                           V8ObserverCompleteCallback* complete_callback)
        : subscriber_(subscriber),
          script_state_(script_state),
          abort_algorithm_handle_(abort_algorithm_handle),
          next_callback_(next_callback),
          error_callback_(error_callback),
          complete_callback_(complete_callback) {
      CHECK(subscriber_);
      CHECK(script_state_);
      // All of `next_callback_`, `error_callback_`, `complete_callback_`,
      // `abort_callback`, can all be null, because script may not have provided
      // any of them.
    }

    void ResetAbortAlgorithm() {
      if (!abort_algorithm_handle_) {
        return;
      }

      subscriber_->signal()->RemoveAlgorithm(abort_algorithm_handle_);
      abort_algorithm_handle_ = nullptr;
    }

    void Next(ScriptValue value) override {
      if (!next_callback_) {
        subscriber_->next(value);
        return;
      }

      // `ScriptState::Scope` can only be created in a valid context, so
      // early-return if we're in a detached one.
      if (!script_state_->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state_);
      v8::TryCatch try_catch(script_state_->GetIsolate());
      // Invoking `callback_` can detach the context, but that's OK, nothing
      // below this invocation relies on an attached/valid context.
      std::ignore = next_callback_->Invoke(nullptr, value);
      if (try_catch.HasCaught()) {
        ScriptValue exception(script_state_->GetIsolate(),
                              try_catch.Exception());
        // See the documentation in `Error()` for what this does.
        ResetAbortAlgorithm();
        subscriber_->error(script_state_, exception);
      }

      subscriber_->next(value);
    }
    void Error(ScriptState*, ScriptValue error) override {
      // The algorithm represented by `abort_algorithm_handle_` invokes the
      // `ObservableInspector` dictionary's `ObservableInspectorAbortHandler`
      // callback. However, that callback must only be invoked for
      // consumer-initiated aborts, NOT producer-initiated aborts. This means,
      // when the source Observable calls `Error()` or `Complete()` on `this`,
      // we must remove the algorithm from `subscriber_`'s signal, because said
      // signal is about to be aborted for producer-initiated reasons.
      ResetAbortAlgorithm();

      if (!error_callback_) {
        subscriber_->error(script_state_, error);
        return;
      }

      if (!script_state_->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state_);
      v8::TryCatch try_catch(script_state_->GetIsolate());
      std::ignore = error_callback_->Invoke(nullptr, error);
      if (try_catch.HasCaught()) {
        ScriptValue exception(script_state_->GetIsolate(),
                              try_catch.Exception());
        subscriber_->error(script_state_, exception);
      }

      subscriber_->error(script_state_, error);
    }
    void Complete() override {
      // See the documentation in `Error()` for what this does.
      ResetAbortAlgorithm();

      if (!complete_callback_) {
        subscriber_->complete(script_state_);
        return;
      }

      if (!script_state_->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state_);
      v8::TryCatch try_catch(script_state_->GetIsolate());
      std::ignore = complete_callback_->Invoke(nullptr);
      if (try_catch.HasCaught()) {
        ScriptValue exception(script_state_->GetIsolate(),
                              try_catch.Exception());
        subscriber_->error(script_state_, exception);
      }

      subscriber_->complete(script_state_);
    }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(subscriber_);
      visitor->Trace(script_state_);
      visitor->Trace(abort_algorithm_handle_);

      visitor->Trace(next_callback_);
      visitor->Trace(error_callback_);
      visitor->Trace(complete_callback_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    Member<Subscriber> subscriber_;
    Member<ScriptState> script_state_;
    Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;

    Member<V8ObserverCallback> next_callback_;
    Member<V8ObserverCallback> error_callback_;
    Member<V8ObserverCompleteCallback> complete_callback_;
  };
  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  Member<Observable> source_observable_;

  Member<V8ObserverCallback> next_callback_;
  Member<V8ObserverCallback> error_callback_;
  Member<V8ObserverCompleteCallback> complete_callback_;
  Member<V8VoidFunction> subscribe_callback_;
  Member<V8ObservableInspectorAbortHandler> abort_callback_;
};

class OperatorSwitchMapSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorSwitchMapSubscribeDelegate(Observable* source_observable,
                                     V8Mapper* mapper)
      : source_observable_(source_observable), mapper_(mapper) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state,
                                                     mapper_),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);
    visitor->Trace(mapper_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* outer_subscriber,
                           ScriptState* script_state,
                           V8Mapper* mapper)
        : outer_subscriber_(outer_subscriber),
          script_state_(script_state),
          mapper_(mapper) {
      CHECK(outer_subscriber_);
      CHECK(script_state_);
      CHECK(mapper_);
    }

    // https://wicg.github.io/observable/#switchmap-next-steps.
    void Next(ScriptValue value) override {
      if (active_inner_abort_controller_) {
        active_inner_abort_controller_->abort(script_state_);
      }

      active_inner_abort_controller_ = AbortController::Create(script_state_);

      SwitchMapProcessNextValueSteps(value);
    }
    void Error(ScriptState*, ScriptValue error) override {
      outer_subscriber_->error(script_state_, error);
    }
    // https://wicg.github.io/observable/#switchmap-complete-steps.
    void Complete() override {
      outer_subscription_has_completed_ = true;

      if (!active_inner_abort_controller_) {
        outer_subscriber_->complete(script_state_);
      }
    }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(outer_subscriber_);
      visitor->Trace(script_state_);
      visitor->Trace(mapper_);
      visitor->Trace(active_inner_abort_controller_);

      ObservableInternalObserver::Trace(visitor);
    }

    // https://wicg.github.io/observable/#switchmap-process-next-value-steps.
    void SwitchMapProcessNextValueSteps(ScriptValue value) {
      // `ScriptState::Scope` can only be created in a valid context, so
      // early-return if we're in a detached one.
      if (!script_state_->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state_);
      v8::TryCatch try_catch(script_state_->GetIsolate());
      v8::Maybe<ScriptValue> mapped_value =
          mapper_->Invoke(nullptr, value, ++idx_);
      if (try_catch.HasCaught()) {
        outer_subscriber_->error(
            script_state_,
            ScriptValue(script_state_->GetIsolate(), try_catch.Exception()));
        return;
      }

      // Since we handled the exception case above, `mapped_value` must not be
      // `v8::Nothing`.
      Observable* inner_observable =
          Observable::from(script_state_, mapped_value.ToChecked(),
                           PassThroughException(script_state_->GetIsolate()));
      if (try_catch.HasCaught()) {
        ApplyContextToException(
            script_state_, try_catch.Exception(),
            ExceptionContext(v8::ExceptionContext::kOperation, "Observable",
                             "map"));
        outer_subscriber_->error(
            script_state_,
            ScriptValue(script_state_->GetIsolate(), try_catch.Exception()));
        return;
      }

      // The `AbortSignal` with which we subscribe to the "inner" Observable is
      // dependent on two signals:
      //   1. The outer subscriber's signal; this one is no surprise, so that we
      //      can unsubscribe from the inner Observable when the outer source
      //      Observable gets torn down.
      HeapVector<Member<AbortSignal>> signals;
      signals.push_back(outer_subscriber_->signal());
      //   2. A more narrowly-scoped signal: the one derived from
      //      `active_inner_abort_controller_`. This signal allows `this` to
      //      abort the inner Observable when the outer source Observable emits
      //      new values.
      DCHECK(active_inner_abort_controller_);
      signals.push_back(active_inner_abort_controller_->signal());

      SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
      options->setSignal(
          MakeGarbageCollected<AbortSignal>(script_state_, signals));

      inner_observable->SubscribeWithNativeObserver(
          script_state_,
          MakeGarbageCollected<InnerSwitchMapObserver>(outer_subscriber_, this),
          options);
    }

    void InnerObservableCompleted() {
      if (outer_subscription_has_completed_) {
        outer_subscriber_->complete(script_state_);
        return;
      }

      active_inner_abort_controller_ = nullptr;
    }

   private:
    // This is the internal observer that manages the subscription for each
    // "inner" Observable, that is derived from each `any` value that the
    // `V8Mapper` omits for each value that the source Observable. So the flow
    // looks like this:
    //   1. "source observable" emits `any` values, which get processed by
    //      `SourceInternalObserver::Next()`.
    //   2. It then goes through
    //      `SourceInternalObserver::SwitchMapProcessNextValueSteps()`, which
    //      calls `V8Mapper` on the `any` value, transforming it into an
    //      `Observable` (via `Observable::from()` semantics).
    //   3. That `Observable` gets subscribed to, via this
    //      `InnerSwitchMapObserver`. `InnerSwitchMapObserver` subscribes to the
    //      given "inner" Observable, piping values/errors it omits to
    //      `outer_subscriber_`, and upon completion, letting calling back to
    //      `SourceInternalObserver` to let it know of the most recent "inner"
    //      subscription completion, so it can process any subsequent ones.
    class InnerSwitchMapObserver final : public ObservableInternalObserver {
     public:
      InnerSwitchMapObserver(Subscriber* outer_subscriber,
                             SourceInternalObserver* source_observer)
          : outer_subscriber_(outer_subscriber),
            source_observer_(source_observer) {}

      void Next(ScriptValue value) override { outer_subscriber_->next(value); }
      void Error(ScriptState* script_state, ScriptValue value) override {
        outer_subscriber_->error(script_state, value);
      }
      void Complete() override { source_observer_->InnerObservableCompleted(); }

      void Trace(Visitor* visitor) const override {
        visitor->Trace(source_observer_);
        visitor->Trace(outer_subscriber_);

        ObservableInternalObserver::Trace(visitor);
      }

     private:
      Member<Subscriber> outer_subscriber_;
      Member<SourceInternalObserver> source_observer_;
    };

    uint64_t idx_ = 0;
    Member<Subscriber> outer_subscriber_;
    Member<ScriptState> script_state_;
    Member<V8Mapper> mapper_;

    Member<AbortController> active_inner_abort_controller_ = nullptr;

    // This member keeps track of whether the "outer" subscription has
    // completed. This is relevant because while we're currently processing
    // "inner" observable subscriptions (i.e., the subscriptions associated with
    // individual Observable values that the "outer" subscriber produces), the
    // "outer" subscription may very well complete. This member helps us keep
    // track of that so we know to complete our subscription once all "inner"
    // values are done being processed.
    bool outer_subscription_has_completed_ = false;
  };

  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  //
  // All of these members are essentially state-less, and are just held here so
  // that we can pass them into the `SourceInternalObserver` above, which gets
  // created for each new subscription.
  Member<Observable> source_observable_;
  Member<V8Mapper> mapper_;
};

// This class is the subscriber delegate for Observables returned by
// `flatMap()`. Flat map is a tricky operator, so here's how the flow works.
// Upon subscription, `this` subscribes to the "source" Observable, that had its
// `flatMap()` method called. All values that the source Observable emits, get
// piped to its subscription's internal observer, which is
// `OperatorFlatMapSubscribeDelegate::SourceInternalObserver`. It is that class
// that is responsible for mapping each of the individual source Observable, via
// `mapper`, to an Observable (that we call the "inner" Observable), which then
// gets subscribed to. Through the remainder the "inner" Observable's lifetime,
// its values are exclusively piped to the "outer" Subscriber — this allows the
// IDL `Observer` handlers associated with the Observable returned from
// `flatMap()` to observe the inner Observable's values.
//
// Once the inner Observable completes, the focus is transferred to the *next*
// value that the outer Observable has emitted, if one such exists. That value
// too gets mapped and converted to an Observable, and subscribed to, and so on.
// See also, the documentation above
// `OperatorFlatMapSubscribeDelegate::SourceInternalObserver::InnerFlatMapObserver`.
class OperatorFlatMapSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorFlatMapSubscribeDelegate(Observable* source_observable,
                                   V8Mapper* mapper)
      : source_observable_(source_observable), mapper_(mapper) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state,
                                                     mapper_),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);
    visitor->Trace(mapper_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* outer_subscriber,
                           ScriptState* script_state,
                           V8Mapper* mapper)
        : outer_subscriber_(outer_subscriber),
          script_state_(script_state),
          mapper_(mapper) {
      CHECK(outer_subscriber_);
      CHECK(script_state_);
      CHECK(mapper_);
    }

    void Next(ScriptValue value) override {
      if (active_inner_subscription_) {
        queue_.push_back(std::move(value));
        return;
      }

      active_inner_subscription_ = true;

      FlatMapProcessNextValueSteps(value);
    }
    void Error(ScriptState*, ScriptValue error) override {
      outer_subscriber_->error(script_state_, error);
    }
    void Complete() override {
      outer_subscription_has_completed_ = true;

      if (!active_inner_subscription_ && queue_.empty()) {
        outer_subscriber_->complete(script_state_);
      }
    }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(outer_subscriber_);
      visitor->Trace(script_state_);
      visitor->Trace(mapper_);
      visitor->Trace(queue_);

      ObservableInternalObserver::Trace(visitor);
    }

    // Analogous to
    // https://wicg.github.io/observable/#flatmap-process-next-value-steps.
    //
    // This method can be called re-entrantly. Imagine the following:
    //   1. The source Observable emits a value that gets passed to this method
    //      (`value` below).
    //   2. `this` derives an Observable from that value, and immediately
    //      subscribes to it.
    //   3. Upon subscription, the Observable synchronously `complete()`s.
    //   4. Upon completion, `InnerObservableCompleted()` gets called, which has
    //      to synchronously process the next value in `queue_`, restarting
    //      these steps from the top.
    void FlatMapProcessNextValueSteps(ScriptValue value) {
      // `ScriptState::Scope` can only be created in a valid context, so
      // early-return if we're in a detached one.
      if (!script_state_->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state_);
      v8::TryCatch try_catch(script_state_->GetIsolate());
      v8::Maybe<ScriptValue> mapped_value =
          mapper_->Invoke(nullptr, value, ++idx_);
      if (try_catch.HasCaught()) {
        outer_subscriber_->error(
            script_state_,
            ScriptValue(script_state_->GetIsolate(), try_catch.Exception()));
        return;
      }

      // Since we handled the exception case above, `mapped_value` must not be
      // `v8::Nothing`.
      Observable* inner_observable =
          Observable::from(script_state_, mapped_value.ToChecked(),
                           PassThroughException(script_state_->GetIsolate()));
      if (try_catch.HasCaught()) {
        ApplyContextToException(
            script_state_, try_catch.Exception(),
            ExceptionContext(v8::ExceptionContext::kOperation, "Observable",
                             "flatMap"));
        outer_subscriber_->error(
            script_state_,
            ScriptValue(script_state_->GetIsolate(), try_catch.Exception()));
        return;
      }

      SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
      options->setSignal(outer_subscriber_->signal());

      inner_observable->SubscribeWithNativeObserver(
          script_state_,
          MakeGarbageCollected<InnerFlatMapObserver>(outer_subscriber_, this),
          options);
    }

    // This method can be called re-entrantly. See the documentation above
    // `FlatMapProcessNextValueSteps()`.
    void InnerObservableCompleted() {
      if (!queue_.empty()) {
        ScriptValue value = queue_.front();
        // This is inefficient! See the documentation above `queue_` for more.
        queue_.EraseAt(0);
        FlatMapProcessNextValueSteps(value);
        return;
      }

      // When the `queue_` is empty and the last "inner" Observable has
      // completed, we can finally complete `outer_subscriber_`.
      active_inner_subscription_ = false;
      if (outer_subscription_has_completed_) {
        outer_subscriber_->complete(script_state_);
      }
    }

   private:
    // This is the internal observer that manages the subscription for each
    // "inner" Observable, that is derived from each `any` value that the
    // `V8Mapper` omits for each value that the source Observable. So the flow
    // looks like this:
    //   1. "source observable" emits `any` values, which get processed by
    //      `SourceInternalObserver::Next()`.
    //   2. It then goes through
    //      `SourceInternalObserver::FlatMapProcessNextValueSteps()`, which
    //      calls `V8Mapper` on the `any` value, transforming it into an
    //      `Observable` (via `Observable::from()` semantics).
    //   3. That `Observable` gets subscribed to, via this
    //      `InnerFlatMapObserver`. `InnerFlatMapObserver` subscribes to the
    //      given "inner" Observable, piping values/errors it omits to
    //      `outer_subscriber_`, and upon completion, letting calling back to
    //      `SourceInternalObserver` to let it know of the most recent "inner"
    //      subscription completion, so it can process any subsequent ones.
    class InnerFlatMapObserver final : public ObservableInternalObserver {
     public:
      InnerFlatMapObserver(Subscriber* outer_subscriber,
                           SourceInternalObserver* source_observer)
          : outer_subscriber_(outer_subscriber),
            source_observer_(source_observer) {}

      void Next(ScriptValue value) override { outer_subscriber_->next(value); }
      void Error(ScriptState* script_state, ScriptValue value) override {
        outer_subscriber_->error(script_state, value);
      }
      void Complete() override { source_observer_->InnerObservableCompleted(); }

      void Trace(Visitor* visitor) const override {
        visitor->Trace(source_observer_);
        visitor->Trace(outer_subscriber_);

        ObservableInternalObserver::Trace(visitor);
      }

     private:
      Member<Subscriber> outer_subscriber_;
      Member<SourceInternalObserver> source_observer_;
    };

    uint64_t idx_ = 0;
    Member<Subscriber> outer_subscriber_;
    Member<ScriptState> script_state_;
    Member<V8Mapper> mapper_;

    // This queue stores all of the values that the "outer" subscription emits
    // while there is an active inner subscription (captured by the member below
    // this). These values are queued and processed one-by-one; they each get
    // passed into `mapper_`.
    //
    // TODO(crbug.com/40282760): This should be a `WTF::Deque` or `HeapDeque`,
    // but neither support holding a `ScriptValue` type at the moment. This
    // needs some investigation, so we can avoid using `HeapVector` here, which
    // has O(n) performance when removing values from the front.
    HeapVector<ScriptValue> queue_;

    bool active_inner_subscription_ = false;

    // This member keeps track of whether the "outer" subscription has
    // completed. This is relevant because while we're currently processing
    // "inner" observable subscriptions (i.e., the subscriptions associated with
    // individual Observable values that the "outer" subscriber produces), the
    // "outer" subscription may very well complete. This member helps us keep
    // track of that so we know to complete our subscription once all "inner"
    // values are done being processed.
    bool outer_subscription_has_completed_ = false;
  };

  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  //
  // All of these members are essentially state-less, and are just held here so
  // that we can pass them into the `SourceInternalObserver` above, which gets
  // created for each new subscription.
  Member<Observable> source_observable_;
  Member<V8Mapper> mapper_;
};

// This delegate is used by the `Observer#from()` operator, in the case where
// the given `any` value is an async iterable. In that case, we store the async
// iterable in `this` delegate, and upon subscription, push to the subscriber
// all of the async iterable's resolved values, once the internal promises are
// reacted to.
class OperatorFromAsyncIterableSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  // Upon construction of `this`, we know that `async_iterable` is a valid
  // object that implements the async iterable prototcol, however:
  //   1. We don't assert that here, because it has script-observable
  //      consequences that shouldn't be invoked just for assertion/sanity
  //      purposes.
  //   2. In `OnSubscribe()` we still have to confirm that fact, because in
  //      between the constructor and `OnSubscribe()` running, that could have
  //      changed.
  explicit OperatorFromAsyncIterableSubscribeDelegate(
      ScriptValue async_iterable)
      : async_iterable_(async_iterable) {}

  // "Return a new Observable whose subscribe callback is an algorithm that
  // takes a Subscriber |subscriber| and does the following:"
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    if (subscriber->signal()->aborted()) {
      return;
    }

    // `Observable::from()` already checks that `async_iterable_` is a JS
    // object, so we can safely convert it here.
    //
    // The runner is never owned by `this`, since the lifetime of `this` is too
    // long. Instead, we just create it now and leave it alone. This ties the
    // ownership to the underlying iterator that produces values. Specifically,
    // `SubscriptionRunner::next_promise_` is kept alive by the script that owns
    // the resolver.
    MakeGarbageCollected<SubscriptionRunner>(
        async_iterable_.V8Value().As<v8::Object>(), subscriber, script_state);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(async_iterable_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  // An instance of this class gets created for every single call of
  // `OperatorFromAsyncIterableSubscribeDelegate::OnSubscribe()`, and is
  // responsible for managing each subscription. That's because each
  // subscription must grab a brand new iterator off of `async_iterable_` and
  // run it to completion, which `SubscriptionRunner` is responsible for.
  //
  // See documentation above its instantiation for ownership details.
  class SubscriptionRunner final : public AbortSignal::Algorithm {
   public:
    SubscriptionRunner(v8::Local<v8::Object> v8_async_iterable,
                       Subscriber* subscriber,
                       ScriptState* script_state)
        : subscriber_(subscriber), script_state_(script_state) {
      v8::TryCatch try_catch(script_state->GetIsolate());

      // "Let |iteratorRecord| be GetIterator(value, async)."
      //
      // This invokes script, so we have to check if there was an exception. In
      // all of the exception-throwing cases in this method, we always catch the
      // exception, clear it, and report it properly through `subscriber`.
      iterator_ = ScriptIterator::FromIterable(
          script_state->GetIsolate(), v8_async_iterable,
          PassThroughException(script_state_->GetIsolate()),
          ScriptIterator::Kind::kAsync);

      // "If |iteratorRecord| is a throw completion, then run |subscriber|'s
      // error() method, given |iteratorRecord|'s [[Value]]."
      if (try_catch.HasCaught()) {
        // Don't ApplyContextToException(), because FromIterable() might return
        // a user-defined exception, which we shouldn't modify.
        subscriber->error(script_state, ScriptValue(script_state->GetIsolate(),
                                                    try_catch.Exception()));
        return;
      }

      // Note that it's possible for `iterator_.IsNull()` to be true here, and
      // we have to handle it appropriately. Here's why:
      //
      // ECMAScript's `GetIterator(value, async)` [1] throws a TypeError when it
      // fails to find both a %Symbol.asyncIterator% or fallback
      // %Symbol.iterator% implementation on the object to convert. However,
      // Blink's implementation of this does not throw an exception in this
      // case, to allow for Blink to specify alternate behavior in the case
      // where the object simply doesn't implement the protocols. However,
      // Observables have no alternate behavior, so we treat the `IsNull()` case
      // the same as the error-throwing case.
      //
      // [1]: https://tc39.es/ecma262/#sec-getiterator
      if (iterator_.IsNull()) {
        DCHECK(!try_catch.HasCaught());
        // The object failed to convert to an async or sync iterable.
        v8::Local<v8::Value> type_error = V8ThrowException::CreateTypeError(
            script_state->GetIsolate(), "Object must be iterable");
        subscriber->error(script_state,
                          ScriptValue(script_state->GetIsolate(), type_error));
        return;
      }

      // This happens if `ScriptIterator::FromIterable()`, which runs script,
      // aborts the subscription. In that case, we respect the abort and leave
      // the iterator alone.
      if (subscriber_->signal()->aborted()) {
        return;
      }

      abort_algorithm_handle_ = subscriber->signal()->AddAlgorithm(this);

      // "Run |nextAlgorithm| given |subscriber| and |iteratorRecord|."
      GetNextValue(subscriber, script_state);
    }

    // "Let |nextAlgorithm| be the following steps, given a Subscriber
    // |subscriber| and an Iterator Record |iteratorRecord|:"
    void GetNextValue(Subscriber* subscriber, ScriptState* script_state) {
      // This can happen when the subscription is aborted in between async
      // values being emitted. The Promise resulting from the previous iteration
      // eventually resolves, but we ensure not to retrieve the value *after
      // that* with this check.
      if (subscriber->signal()->aborted()) {
        return;
      }

      DCHECK(!iterator_.IsNull());
      ExecutionContext* execution_context =
          ExecutionContext::From(script_state);

      // "Let |nextRecord| be IteratorNext(|iteratorRecord|)."
      v8::TryCatch try_catch(script_state->GetIsolate());
      const bool is_done_because_exception_was_thrown = !iterator_.Next(
          execution_context, PassThroughException(script_state->GetIsolate()));

      // "If |nextRecord| is a throw completion:"
      ScriptPromise<IDLAny> next_promise;
      if (try_catch.HasCaught()) {
        // Assert: |iteratorRecord|'s [[Done]] is true.
        CHECK(is_done_because_exception_was_thrown);

        // Set |nextPromise| to a promise rejected with |nextRecord|'s
        // [[Value]].
        ApplyContextToException(
            script_state_, try_catch.Exception(),
            ExceptionContext(v8::ExceptionContext::kOperation, "Observable",
                             "from"));
        next_promise =
            ScriptPromise<IDLAny>::Reject(script_state, try_catch.Exception());
      } else {
        // "Otherwise, if |nextRecord| is normal completion, then set
        // |nextPromise| to a promise resolved with |nextRecord|'s [[Value]].
        next_promise = ToResolvedPromise<IDLAny>(
            script_state, iterator_.GetValue().ToLocalChecked());
      }

      // "React to |nextPromise|:"
      //
      // See continued documentation in
      // `AsyncIteratorNextResolverFunction::Call()`.
      next_promise.Then(
          script_state,
          MakeGarbageCollected<AsyncIteratorNextResolverFunction>(
              this, subscriber,
              AsyncIteratorNextResolverFunction::ResolveType::kFulfill),
          MakeGarbageCollected<AsyncIteratorNextResolverFunction>(
              this, subscriber,
              AsyncIteratorNextResolverFunction::ResolveType::kReject));
      next_promise_ = next_promise;
    }

    void ClearAbortAlgorithm() {
      subscriber_->signal()->RemoveAlgorithm(abort_algorithm_handle_);
      abort_algorithm_handle_.Clear();
    }

    // This is the abort algorithm that runs when the relevant subscription is
    // aborted. It's responsible for running ECMAScript's AsyncIteratorClose()
    // abstract algorithm [1] on `SubscriptionManager::iterator_`, which invokes
    // the `return()` method on the iterator if one such exists, to indicate to
    // the underlying object that the consumer is terminating its consumption of
    // values before exhaustion.
    //
    // [1]: https://tc39.es/ecma262/#sec-asynciteratorclose.
    void Run() override {
      // The abort algorithm is only set up once the `iterator_` is established.
      DCHECK(!iterator_.IsNull());
      iterator_.CloseAsync(
          script_state_,
          ExceptionContext(v8::ExceptionContext::kOperation, "Observable",
                           "from"),
          subscriber_->signal()->reason(script_state_).V8Value());
    }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(abort_algorithm_handle_);
      visitor->Trace(subscriber_);
      visitor->Trace(script_state_);
      visitor->Trace(iterator_);
      visitor->Trace(next_promise_);

      Algorithm::Trace(visitor);
    }

   private:
    // The handle associated with the algorithm that runs in response to the
    // consumer aborting the subscription. Initialized in the constructor, and
    // used to "remove" the algorithm from the signal in the case where the
    // iterable becomes exhausted before the signal is aborted.
    Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
    // The specific `Subscriber` that `this` will push values to from
    // `iterator_`, as they are asynchronously emitted.
    Member<Subscriber> subscriber_;
    Member<ScriptState> script_state_;
    // The `ScriptIterator` that this subscription is associated with. Per the
    // Observable specification's conversion semantics [1], each subscription
    // from an Observable that was created from an async iterable, will be
    // associated with a new "Iterator Record" grabbed from invoking the
    // @@asyncIterator on the underlying async iterable object. The subscription
    // gets its values pushed to it by each Promise returned by the Iterator
    // Record's `[[NextMethod]]` (i.e., `ScriptIterator::Next()`). This member
    // represents the |iteratorRecord| variable in [1].
    //
    // [1]:
    // https://wicg.github.io/observable/#observable-convert-to-an-observable.
    ScriptIterator iterator_;
    // Represents the |nextPromise| variable in the Observable specification's
    // conversion algorithm [1]. It is obtained by wrapping the latest value
    // returned by the above member's `Next()` method, and is reset each time it
    // resolves. Once obtained, `next_promise_` gets "reacted" to by
    // `GetNextValue()` with instances of `AsyncIteratorNextResolverFunction`
    // algorithms owned by the promise. The promise needs to be owned by `this`
    // however, so that it doesn't get garbage collected prematurely
    //
    // [1]:
    // https://wicg.github.io/observable/#observable-convert-to-an-observable.
    MemberScriptPromise<IDLAny> next_promise_;
  };

  class AsyncIteratorNextResolverFunction final
      : public ThenCallable<IDLAny, AsyncIteratorNextResolverFunction> {
   public:
    enum class ResolveType { kFulfill, kReject };

    AsyncIteratorNextResolverFunction(SubscriptionRunner* delegate,
                                      Subscriber* subscriber,
                                      ResolveType type)
        : delegate_(delegate), subscriber_(subscriber), type_(type) {
      CHECK(delegate_);
      CHECK(subscriber_);
    }

    void React(ScriptState* script_state, ScriptValue value) {
      v8::Local<v8::Value> iterator_result = value.V8Value();
      v8::Isolate* isolate = script_state->GetIsolate();
      v8::Local<v8::Context> context = script_state->GetContext();
      if (type_ == ResolveType::kFulfill) {
        // "If |nextPromise| was fulfilled with value |iteratorResult|, then:

        // "If Type(|iteratorResult|) is not Object, then run |subscriber|'s
        // error() method with a TypeError and abort these steps.
        if (!iterator_result->IsObject()) {
          v8::Local<v8::Value> type_error = V8ThrowException::CreateTypeError(
              isolate, "Expected next() Promise to resolve to an Object");
          delegate_->ClearAbortAlgorithm();
          subscriber_->error(script_state, ScriptValue(isolate, type_error));
          return;
        }

        v8::TryCatch try_catch(isolate);
        v8::Local<v8::Object> iterator_result_obj =
            iterator_result.As<v8::Object>();

        // "Let done be IteratorComplete(|iteratorResult|)."
        v8::MaybeLocal<v8::Value> maybe_done =
            iterator_result_obj->Get(context, V8AtomicString(isolate, "done"));

        // "If done is a throw completion, then run subscriber's error() method
        // with |done|'s [[Value]] and abort these steps."
        if (try_catch.HasCaught()) {
          ScriptValue exception(script_state->GetIsolate(),
                                try_catch.Exception());
          delegate_->ClearAbortAlgorithm();
          subscriber_->error(script_state, exception);
          return;
        }

        // "Otherwise, if done's [[Value]] is true, then run subscriber's
        // complete() and abort these steps."
        //
        // Since we handled the exception case above, `maybe_done` must not be
        // `v8::Nothing`.
        const bool done = ToBoolean(isolate, maybe_done.ToLocalChecked(),
                                    ASSERT_NO_EXCEPTION);
        if (done) {
          delegate_->ClearAbortAlgorithm();
          subscriber_->complete(script_state);
          return;
        }

        // "Let value be IteratorValue(|iteratorResult|)."
        v8::MaybeLocal<v8::Value> maybe_value =
            iterator_result_obj->Get(context, V8AtomicString(isolate, "value"));

        // "If value is a throw completion, then run subscriber's error() method
        // with |value|'s [[Value]] and abort these steps."
        if (try_catch.HasCaught()) {
          ScriptValue exception(script_state->GetIsolate(),
                                try_catch.Exception());
          delegate_->ClearAbortAlgorithm();
          subscriber_->error(script_state, exception);
          return;
        }

        // "Run subscriber’s next() method, given value's [[Value]]."
        //
        // Since we handled the exception case above, `maybe_value` must not be
        // `v8::Nothing`.
        subscriber_->next(ScriptValue(isolate, maybe_value.ToLocalChecked()));

        // Run |nextAlgorithm|, given |subscriber| and |iteratorRecord|.
        delegate_->GetNextValue(subscriber_, script_state);
      } else {
        // If |nextPromise| was rejected with reason |r|, then run
        // |subscriber|'s error() method, given |r|.
        delegate_->ClearAbortAlgorithm();
        subscriber_->error(script_state, value);
      }
    }

    void Trace(Visitor* visitor) const final {
      visitor->Trace(delegate_);
      visitor->Trace(subscriber_);
      ThenCallable<IDLAny, AsyncIteratorNextResolverFunction>::Trace(visitor);
    }

   private:
    Member<SubscriptionRunner> delegate_;
    Member<Subscriber> subscriber_;
    ResolveType type_;
  };

  // The iterable that `this` synchronously pushes values from, for the
  // subscription that `this` represents.
  ScriptValue async_iterable_;
};

// This delegate is used by the `Observer#from()` operator, in the case where
// the given `any` value is an iterable. In that case, we store the iterable in
// `this` delegate, and upon subscription, synchronously push to the subscriber
// all of the iterable's values.
class OperatorFromIterableSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  // Upon construction of `this`, we know that `iterable` is a valid object that
  // implements the iterable prototcol, however:
  //   1. We don't assert that here, because it has script-observable
  //      consequences that shouldn't be invoked just for assertion/sanity
  //      purposes.
  //   2. In `OnSubscribe()` we still have to confirm that fact, because in
  //      between the constructor and `OnSubscribe()` running, that could have
  //      changed.
  explicit OperatorFromIterableSubscribeDelegate(ScriptValue iterable)
      : iterable_(iterable) {}

  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    if (subscriber->signal()->aborted()) {
      return;
    }

    MakeGarbageCollected<SubscriptionRunner>(
        iterable_.V8Value().As<v8::Object>(), subscriber, script_state);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(iterable_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SubscriptionRunner final : public AbortSignal::Algorithm {
   public:
    SubscriptionRunner(v8::Local<v8::Object> v8_iterable,
                       Subscriber* subscriber,
                       ScriptState* script_state)
        : signal_(subscriber->signal()), script_state_(script_state) {
      CHECK(subscriber);
      CHECK(script_state);


      ExecutionContext* execution_context =
          ExecutionContext::From(script_state);
      v8::Isolate* isolate = script_state->GetIsolate();

      // This invokes script, so we have to check if there was an exception. In
      // all of the exception-throwing cases in this method, we always catch the
      // exception, clear it, and report it properly through `subscriber`.
      v8::TryCatch try_catch(isolate);
      iterator_ = ScriptIterator::FromIterable(isolate, v8_iterable,
                                               PassThroughException(isolate),
                                               ScriptIterator::Kind::kSync);
      if (try_catch.HasCaught()) {
        // Don't ApplyContextToException(), because FromIterable() might return
        // a user-defined exception, which we shouldn't modify.
        subscriber->error(script_state,
                          ScriptValue(isolate, try_catch.Exception()));
        return;
      }

      // This happens if the `@@iterator` implementation is undefined or null.
      // When `ScriptIterator::FromIterable()` encounters this, instead of
      // throwing as ECMAScript's `GetIterator()` [1] calls for, it silently
      // returns a null iterator to give embedders a chance to override the
      // behavior. We do not want to override the behavior in this case, so we
      // throw, which is called for in the Observable spec [2].
      //
      // [1]: https://tc39.es/ecma262/#sec-getiterator.
      // [2]: http://wicg.github.io/observable/#from-iterable-conversion
      if (iterator_.IsNull()) {
        v8::Local<v8::Value> type_error = V8ThrowException::CreateTypeError(
            script_state->GetIsolate(),
            "@@iterator must not be undefined or null");
        ApplyContextToException(
            script_state_, type_error,
            ExceptionContext(v8::ExceptionContext::kOperation, "Observable",
                             "subscribe"));
        subscriber->error(script_state,
                          ScriptValue(script_state->GetIsolate(), type_error));
        return;
      }

      // This happens if `ScriptIterator::FromIterable()`, which runs script,
      // aborts the subscription. In that case, we respect the abort and leave
      // the iterator alone.
      if (subscriber->signal()->aborted()) {
        return;
      }

      abort_algorithm_handle_ = subscriber->signal()->AddAlgorithm(this);

      while (iterator_.Next(execution_context, PassThroughException(isolate))) {
        CHECK(!try_catch.HasCaught());

        v8::Local<v8::Value> value = iterator_.GetValue().ToLocalChecked();
        subscriber->next(ScriptValue(isolate, value));

        if (subscriber->signal()->aborted()) {
          break;
        }
      }

      // If any call to `ScriptIterator::Next()` above throws an error, then the
      // loop will break, and we'll need to catch any exceptions here and
      // properly report the error to the `subscriber`.
      if (try_catch.HasCaught()) {
        // Don't ApplyContextToException(), because Next() might return
        // a user-defined exception, which we shouldn't modify.
        ClearAbortAlgorithm();
        subscriber->error(script_state,
                          ScriptValue(isolate, try_catch.Exception()));
        return;
      }

      ClearAbortAlgorithm();
      subscriber->complete(script_state);
    }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(abort_algorithm_handle_);
      visitor->Trace(iterator_);
      visitor->Trace(signal_);
      visitor->Trace(script_state_);

      Algorithm::Trace(visitor);
    }

    void ClearAbortAlgorithm() {
      signal_->RemoveAlgorithm(abort_algorithm_handle_);
      abort_algorithm_handle_.Clear();
    }

    void Run() override {
      // The abort algorithm is only set up once the `iterator_` is established.
      DCHECK(!iterator_.IsNull());
      // Don't ApplyContextToException(), because CloseSync() might return
      // a user-defined exception, which we shouldn't modify.
      iterator_.CloseSync(script_state_,
                          PassThroughException(script_state_->GetIsolate()),
                          signal_->reason(script_state_).V8Value());
    }

   private:
    Member<AbortSignal::AlgorithmHandle> abort_algorithm_handle_;
    ScriptIterator iterator_;
    Member<AbortSignal> signal_;
    Member<ScriptState> script_state_;
  };

  // The iterable that `this` synchronously pushes values from, for the
  // subscription that `this` represents.
  ScriptValue iterable_;
};

class OperatorDropSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorDropSubscribeDelegate(Observable* source_observable,
                                uint64_t number_to_drop)
      : source_observable_(source_observable),
        number_to_drop_(number_to_drop) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state,
                                                     number_to_drop_),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* subscriber,
                           ScriptState* script_state,
                           uint64_t number_to_drop)
        : subscriber_(subscriber),
          script_state_(script_state),
          number_to_drop_(number_to_drop) {
      CHECK(subscriber_);
      CHECK(script_state_);
    }

    void Next(ScriptValue value) override {
      if (number_to_drop_ > 0) {
        --number_to_drop_;
        return;
      }

      CHECK_EQ(number_to_drop_, 0ull);
      subscriber_->next(value);
    }
    void Error(ScriptState*, ScriptValue error) override {
      subscriber_->error(script_state_, error);
    }
    void Complete() override { subscriber_->complete(script_state_); }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(subscriber_);
      visitor->Trace(script_state_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    Member<Subscriber> subscriber_;
    Member<ScriptState> script_state_;
    uint64_t number_to_drop_;
  };
  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  Member<Observable> source_observable_;
  const uint64_t number_to_drop_;
};

class OperatorTakeSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorTakeSubscribeDelegate(Observable* source_observable,
                                uint64_t number_to_take)
      : source_observable_(source_observable),
        number_to_take_(number_to_take) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    if (number_to_take_ == 0) {
      subscriber->complete(script_state);
      return;
    }

    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state,
                                                     number_to_take_),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* subscriber,
                           ScriptState* script_state,
                           uint64_t number_to_take)
        : subscriber_(subscriber),
          script_state_(script_state),
          number_to_take_(number_to_take) {
      CHECK(subscriber_);
      CHECK(script_state_);
      CHECK_GT(number_to_take_, 0ull);
    }

    void Next(ScriptValue value) override {
      CHECK_GT(number_to_take_, 0ull);
      // This can run script, which may detach the context, but that's OK
      // because nothing below this invocation relies on an attached/valid
      // context.
      subscriber_->next(value);
      --number_to_take_;

      if (!number_to_take_) {
        subscriber_->complete(script_state_);
      }
    }
    void Error(ScriptState*, ScriptValue error) override {
      subscriber_->error(script_state_, error);
    }
    void Complete() override { subscriber_->complete(script_state_); }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(subscriber_);
      visitor->Trace(script_state_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    Member<Subscriber> subscriber_;
    Member<ScriptState> script_state_;
    uint64_t number_to_take_;
  };
  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  Member<Observable> source_observable_;
  const uint64_t number_to_take_;
};

class OperatorFilterSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorFilterSubscribeDelegate(Observable* source_observable,
                                  V8Predicate* predicate)
      : source_observable_(source_observable), predicate_(predicate) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state,
                                                     predicate_),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);
    visitor->Trace(predicate_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* subscriber,
                           ScriptState* script_state,
                           V8Predicate* predicate)
        : subscriber_(subscriber),
          script_state_(script_state),
          predicate_(predicate) {
      CHECK(subscriber_);
      CHECK(script_state_);
      CHECK(predicate_);
    }

    void Next(ScriptValue value) override {
      // `ScriptState::Scope` can only be created in a valid context, so
      // early-return if we're in a detached one.
      if (!script_state_->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state_);
      v8::TryCatch try_catch(script_state_->GetIsolate());
      v8::Maybe<bool> matches = predicate_->Invoke(nullptr, value, idx_++);
      if (try_catch.HasCaught()) {
        subscriber_->error(
            script_state_,
            ScriptValue(script_state_->GetIsolate(), try_catch.Exception()));
        return;
      }

      // Since we handled the exception case above, `matches` must not be
      // `v8::Nothing`.
      if (matches.ToChecked()) {
        subscriber_->next(value);
      }
    }
    void Error(ScriptState*, ScriptValue error) override {
      subscriber_->error(script_state_, error);
    }
    void Complete() override { subscriber_->complete(script_state_); }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(subscriber_);
      visitor->Trace(script_state_);
      visitor->Trace(predicate_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    uint64_t idx_ = 0;
    Member<Subscriber> subscriber_;
    Member<ScriptState> script_state_;
    Member<V8Predicate> predicate_;
  };
  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  Member<Observable> source_observable_;
  Member<V8Predicate> predicate_;
};

class OperatorMapSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorMapSubscribeDelegate(Observable* source_observable, V8Mapper* mapper)
      : source_observable_(source_observable), mapper_(mapper) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state,
                                                     mapper_),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);
    visitor->Trace(mapper_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* subscriber,
                           ScriptState* script_state,
                           V8Mapper* mapper)
        : subscriber_(subscriber),
          script_state_(script_state),
          mapper_(mapper) {
      CHECK(subscriber_);
      CHECK(script_state_);
      CHECK(mapper_);
    }

    void Next(ScriptValue value) override {
      // `ScriptState::Scope` can only be created in a valid context, so
      // early-return if we're in a detached one.
      if (!script_state_->ContextIsValid()) {
        return;
      }

      ScriptState::Scope scope(script_state_);
      v8::TryCatch try_catch(script_state_->GetIsolate());
      v8::Maybe<ScriptValue> mapped_value =
          mapper_->Invoke(nullptr, value, idx_++);
      if (try_catch.HasCaught()) {
        subscriber_->error(
            script_state_,
            ScriptValue(script_state_->GetIsolate(), try_catch.Exception()));
        return;
      }

      // Since we handled the exception case above, `mapped_value` must not be
      // `v8::Nothing`.
      subscriber_->next(mapped_value.ToChecked());
    }
    void Error(ScriptState*, ScriptValue error) override {
      subscriber_->error(script_state_, error);
    }
    void Complete() override { subscriber_->complete(script_state_); }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(subscriber_);
      visitor->Trace(script_state_);
      visitor->Trace(mapper_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    uint64_t idx_ = 0;
    Member<Subscriber> subscriber_;
    Member<ScriptState> script_state_;
    Member<V8Mapper> mapper_;
  };
  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  Member<Observable> source_observable_;
  Member<V8Mapper> mapper_;
};

class OperatorTakeUntilSubscribeDelegate final
    : public Observable::SubscribeDelegate {
 public:
  OperatorTakeUntilSubscribeDelegate(Observable* source_observable,
                                     Observable* notifier)
      : source_observable_(source_observable), notifier_(notifier) {}
  void OnSubscribe(Subscriber* subscriber, ScriptState* script_state) override {
    SubscribeOptions* options = MakeGarbageCollected<SubscribeOptions>();
    options->setSignal(subscriber->signal());

    notifier_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<NotifierInternalObserver>(subscriber,
                                                       script_state),
        options);

    // If `notifier_` synchronously emits a "next" or "error" value, thus making
    // `subscriber` inactive, we do not even attempt to subscribe to
    // `source_observable_` at all.
    if (!subscriber->active()) {
      return;
    }

    source_observable_->SubscribeWithNativeObserver(
        script_state,
        MakeGarbageCollected<SourceInternalObserver>(subscriber, script_state),
        options);
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(source_observable_);
    visitor->Trace(notifier_);

    Observable::SubscribeDelegate::Trace(visitor);
  }

 private:
  // This is the "internal observer" that we use to subscribe to
  // `source_observable_`. It is a simple pass-through, which forwards all of
  // the `source_observable_` values to `outer_subscriber_`, which is the
  // `Subscriber` associated with the subscription to `this`.
  //
  // In addition to being a simple pass-through, it also appropriately
  // unsubscribes from `notifier_`, once the `source_observable_` subscription
  // ends. This is accomplished by simply calling
  // `outer_subscriber_->complete()` which will abort the outer subscriber's
  // signal, triggering the dependent signals to be aborted as well, including
  // the signal associated with the notifier's Observable's subscription.
  class SourceInternalObserver final : public ObservableInternalObserver {
   public:
    SourceInternalObserver(Subscriber* outer_subscriber,
                           ScriptState* script_state)
        : outer_subscriber_(outer_subscriber),
          script_state_(script_state) {
      CHECK(outer_subscriber_);
      CHECK(script_state_);
    }

    void Next(ScriptValue value) override { outer_subscriber_->next(value); }
    void Error(ScriptState* script_state, ScriptValue error) override {
      outer_subscriber_->error(script_state_, error);
    }
    void Complete() override {
      outer_subscriber_->complete(script_state_);
    }

    void Trace(Visitor* visitor) const override {
      visitor->Trace(outer_subscriber_);
      visitor->Trace(script_state_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    Member<Subscriber> outer_subscriber_;
    Member<ScriptState> script_state_;
  };
  // The `Observable` which `this` will mirror, when `this` is subscribed to.
  Member<Observable> source_observable_;

  // This is the "internal observer" that we use to subscribe to `notifier_`
  // with. It is simply responsible for taking the `Subscriber` associated with
  // `this`, and completing it.
  class NotifierInternalObserver final : public ObservableInternalObserver {
   public:
    NotifierInternalObserver(Subscriber* outer_subscriber,
                             ScriptState* script_state)
        : outer_subscriber_(outer_subscriber),
          script_state_(script_state) {
      CHECK(outer_subscriber_);
      CHECK(script_state_);
    }
    void Next(ScriptValue) override {
      // When a notifier Observable emits a "next" or "error" value, we
      // "complete" `outer_subscriber_`, since the outer/source Observables
      // don't care about anything the notifier produces; only its completion is
      // interesting.
      outer_subscriber_->complete(script_state_);
    }
    void Error(ScriptState* script_state, ScriptValue) override {
      outer_subscriber_->complete(script_state_);
    }
    void Complete() override {}

    void Trace(Visitor* visitor) const override {
      visitor->Trace(outer_subscriber_);
      visitor->Trace(script_state_);

      ObservableInternalObserver::Trace(visitor);
    }

   private:
    Member<Subscriber> outer_subscriber_;
    Member<ScriptState> script_state_;
  };
  // The `Observable` that, once a `next` or `error` value is emitted`, will
  // force the unsubscription to `source_observable_`.
  Member<Observable> notifier_;
};

}  // namespace

using PassKey = base::PassKey<Observable>;

// static
Observable* Observable::Create(ScriptState* script_state,
                               V8SubscribeCallback* subscribe_callback) {
  return MakeGarbageCollected<Observable>(ExecutionContext::From(script_state),
                                          subscribe_callback);
}

Observable::Observable(ExecutionContext* execution_context,
                       V8SubscribeCallback* subscribe_callback)
    : ExecutionContextClient(execution_context),
      subscribe_callback_(subscribe_callback) {
  DCHECK(subscribe_callback_);
  DCHECK(!subscribe_delegate_);
  DCHECK(RuntimeEnabledFeatures::ObservableAPIEnabled(execution_context));
}

Observable::Observable(ExecutionContext* execution_context,
                       SubscribeDelegate* subscribe_delegate)
    : ExecutionContextClient(execution_context),
      subscribe_delegate_(subscribe_delegate) {
  DCHECK(!subscribe_callback_);
  DCHECK(subscribe_delegate_);
  DCHECK(RuntimeEnabledFeatures::ObservableAPIEnabled(execution_context));
}

void Observable::subscribe(ScriptState* script_state,
                           V8UnionObserverOrObserverCallback* observer_union,
                           SubscribeOptions* options) {
  SubscribeInternal(script_state, observer_union, /*internal_observer=*/nullptr,
                    options);
}

void Observable::SubscribeWithNativeObserver(
    ScriptState* script_state,
    ObservableInternalObserver* internal_observer,
    SubscribeOptions* options) {
  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    options);
}

void Observable::SubscribeInternal(
    ScriptState* script_state,
    V8UnionObserverOrObserverCallback* observer_union,
    ObservableInternalObserver* internal_observer,
    SubscribeOptions* options) {
  // Cannot subscribe to an Observable that was constructed in a detached
  // context, because this might involve reporting an exception with the global,
  // which relies on a valid `ScriptState`.
  if (!script_state->ContextIsValid()) {
    CHECK(!GetExecutionContext());
    return;
  }

  // Exactly one of `observer_union` or `internal_observer` must be non-null.
  // This is important because this method is called in one of two paths:
  //   1. The the "usual" path of `Observable#subscribe()` with
  //      developer-supplied callbacks (aka `observer_union` is non-null). In
  //      this case, no `internal_observer` is passed in, and we instead
  //      construct a new `ScriptCallbackInternalObserver` out of
  //      `observer_union`, to give to a brand new `Subscriber` for this
  //      specific subscription.
  //   2. The "internal subscription" path, where a custom `internal_observer`
  //      is already built, passed in, and fed to the brand new `Subscriber` for
  //      this specific subscription. No `observer_union` is passed in.
  CHECK_NE(!!observer_union, !!internal_observer);

  ObservableInternalObserver* observer = nullptr;
  if (observer_union) {
    // Case (1) above.
    switch (observer_union->GetContentType()) {
      case V8UnionObserverOrObserverCallback::ContentType::kObserver: {
        Observer* script_observer = observer_union->GetAsObserver();
        observer = MakeGarbageCollected<ScriptCallbackInternalObserver>(
            script_observer->hasNext() ? script_observer->next() : nullptr,
            script_observer->hasError() ? script_observer->error() : nullptr,
            script_observer->hasComplete() ? script_observer->complete()
                                           : nullptr);
        break;
      }
      case V8UnionObserverOrObserverCallback::ContentType::kObserverCallback:
        observer = MakeGarbageCollected<ScriptCallbackInternalObserver>(
            /*next=*/observer_union->GetAsObserverCallback(),
            /*error_callback=*/nullptr, /*complete_callback=*/nullptr);
        break;
    }
  } else {
    // Case (2) above.
    observer = internal_observer;
  }

  CHECK(observer);
  if (weak_subscriber_ && weak_subscriber_->active()) {
    weak_subscriber_->RegisterNewObserver(script_state, observer, options);
    return;
  }

  // Construct `weak_subscriber_` for the first subscription. This will take
  // care of registering `observer` as the first observer.
  weak_subscriber_ = MakeGarbageCollected<Subscriber>(PassKey(), script_state,
                                                      observer, options);

  // Exactly one of `subscribe_callback_` or `subscribe_delegate_` is non-null.
  // Use whichever is provided.
  CHECK_NE(!!subscribe_delegate_, !!subscribe_callback_)
      << "Exactly one of subscribe_callback_ or subscribe_delegate_ should be "
         "non-null";
  if (subscribe_delegate_) {
    subscribe_delegate_->OnSubscribe(weak_subscriber_, script_state);
    return;
  }

  // Ordinarily we'd just invoke `subscribe_callback_` with
  // `InvokeAndReportException()`, so that any exceptions get reported to the
  // global. However, Observables have special semantics with the error handler
  // passed in via `observer`. Specifically, if the subscribe callback throws an
  // exception (that doesn't go through the manual `Subscriber::error()`
  // pathway), we still give that method a first crack at handling the
  // exception. This does one of two things:
  //   1. Lets the provided `Observer#error()` handler run with the thrown
  //      exception, if such handler was provided
  //   2. Reports the exception to the global if no such handler was provided.
  // See `Subscriber::error()` for more details.
  //
  // In either case, no exception in this path interrupts the ordinary flow of
  // control. Therefore, `subscribe()` will never synchronously throw an
  // exception.

  ScriptState::Scope scope(script_state);
  v8::TryCatch try_catch(script_state->GetIsolate());
  std::ignore = subscribe_callback_->Invoke(nullptr, weak_subscriber_);
  if (try_catch.HasCaught()) {
    // There are two cases where we might have a JS exception on the stack here:
    //   1. The `subscribe_callback_` immediately started pushing values to the
    //      observer, and somewhere along the way an exception was thrown. In
    //      this case, `weak_subscriber_` is non-null, and still active. Report
    //      the exception to it.
    if (weak_subscriber_->active()) {
      weak_subscriber_->error(
          script_state,
          ScriptValue(script_state->GetIsolate(), try_catch.Exception()));
    } else {
      // 2. The `subscriber_callback_` immediately closed the subscription, and
      //    during this, an error was thrown (an exception-throwing `complete()`
      //    handler for example). In that case, `weak_subscriber_` is non-null
      //    but inactive. Report the exception to the global instead of the
      //    subscriber.
      if (!script_state->ContextIsValid()) {
        CHECK(!GetExecutionContext());
        return;
      }
      V8ScriptRunner::ReportException(script_state->GetIsolate(),
                                      try_catch.Exception());
    }
  }
}

// static
Observable* Observable::from(ScriptState* script_state,
                             ScriptValue value,
                             ExceptionState& exception_state) {
  v8::Isolate* isolate = script_state->GetIsolate();
  v8::Local<v8::Value> v8_value = value.V8Value();

  // 1. Try to convert to an Observable.
  // In the failed conversion case, the native bindings layer throws an
  // exception to indicate the conversion cannot be done. This is not an
  // exception thrown by web author code, it's a native exception that only
  // signals conversion failure, so we must (and can safely) ignore it and let
  // other conversion attempts below continue.
  if (Observable* converted = NativeValueTraits<Observable>::NativeValue(
          isolate, v8_value, IGNORE_EXCEPTION)) {
    return converted;
  }

  // 2. Try to convert to an AsyncIterable.
  //
  // 3. Try to convert to an Iterable.
  //
  // Because an array is an object, arrays will be converted into iterables here
  // using the iterable protocol. This means that if an array defines a custom
  // @@iterator, it will be used here instead of deferring to "regular array
  // iteration". This seems natural, but is inconsistent with what
  // `NativeValueTraits` does in some cases.
  // See:
  // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h;l=1167-1174;drc=f4a00cc248dd2dc8ec8759fb51620d47b5114090.
  if (v8_value->IsObject()) {
    TryRethrowScope rethrow_scope(isolate, exception_state);
    v8::Local<v8::Object> v8_obj = v8_value.As<v8::Object>();
    v8::Local<v8::Context> current_context = isolate->GetCurrentContext();

    // From async itertable: "Let |asyncIteratorMethodRecord| be ?
    // GetMethod(value, %Symbol.asyncIterator%)."
    v8::Local<v8::Value> method;
    if (!v8_obj->Get(current_context, v8::Symbol::GetAsyncIterator(isolate))
             .ToLocal(&method)) {
      CHECK(rethrow_scope.HasCaught());
      return nullptr;
    }

    // "If |asyncIteratorMethodRecord|'s [[Value]] is undefined or null, then
    // jump to the step labeled 'From iterable'."
    if (!method->IsNullOrUndefined()) {
      // "If IsCallable(|asyncIteratorMethodRecord|'s [[Value]]) is false, then
      // throw a TypeError."
      if (!method->IsFunction()) {
        exception_state.ThrowTypeError("@@asyncIterator must be a callable.");
        return nullptr;
      }

      // "Otherwise, ..."
      //
      // TODO(crbug.com/363015168): Consider pulling the @@asyncIterator method
      // off of `value` and storing it alongside `value`, to avoid the
      // subscription-time side effects of re-grabbing the method. See [1].
      //
      // [1]: https://github.com/WICG/observable/issues/127.
      return MakeGarbageCollected<Observable>(
          ExecutionContext::From(script_state),
          MakeGarbageCollected<OperatorFromAsyncIterableSubscribeDelegate>(
              value));
    }

    // From iterable: "Let |iteratorMethodRecord| be ? GetMethod(value,
    // %Symbol.iterator%)."
    if (!v8_obj->Get(current_context, v8::Symbol::GetIterator(isolate))
             .ToLocal(&method)) {
      CHECK(rethrow_scope.HasCaught());
      return nullptr;
    }

    // "If |iteratorMethodRecord|'s [[Value]] is undefined or null, then jump to
    // the step labeled 'From Promise'."
    //
    // This indicates that the passed in object just does not implement the
    // iterator protocol, in which case we silently move on to the next type of
    // conversion.
    if (!method->IsNullOrUndefined()) {
      // "If IsCallable(iteratorMethodRecord's [[Value]]) is false, then throw a
      // TypeError."
      if (!method->IsFunction()) {
        exception_state.ThrowTypeError("@@iterator must be a callable.");
        return nullptr;
      }

      // "Otherwise, return a new Observable whose subscribe callback is an
      // algorithm that takes a Subscriber subscriber and does the following:"
      //
      // See the continued documentation in below classes.
      return MakeGarbageCollected<Observable>(
          ExecutionContext::From(script_state),
          MakeGarbageCollected<OperatorFromIterableSubscribeDelegate>(value));
    }
  }

  // 4. Try to convert to a Promise.
  //
  // "From Promise: If IsPromise(value) is true, then:". See the continued
  // documentation in the below classes.
  if (v8_value->IsPromise()) {
    ScriptPromise<IDLAny> promise = ScriptPromise<IDLAny>::FromV8Promise(
        script_state->GetIsolate(), v8_value.As<v8::Promise>());
    return MakeGarbageCollected<Observable>(
        ExecutionContext::From(script_state),
        MakeGarbageCollected<OperatorFromPromiseSubscribeDelegate>(promise));
  }

  exception_state.ThrowTypeError(
      "Cannot convert value to an Observable. Input value must be an "
      "Observable, async iterable, iterable, or Promise.");
  return nullptr;
}

Observable* Observable::takeUntil(ScriptState*, Observable* notifier) {
  // This method is just a loose wrapper that returns another `Observable`,
  // whose logic is defined by `OperatorTakeUntilSubscribeDelegate`. When
  // subscribed to, `return_observable` will simply mirror `this` until
  // `notifier` emits either a `next` or `error` value.
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorTakeUntilSubscribeDelegate>(this, notifier));
  return return_observable;
}

Observable* Observable::map(ScriptState*, V8Mapper* mapper) {
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorMapSubscribeDelegate>(this, mapper));
  return return_observable;
}

Observable* Observable::filter(ScriptState*, V8Predicate* predicate) {
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorFilterSubscribeDelegate>(this, predicate));
  return return_observable;
}

Observable* Observable::take(ScriptState*, uint64_t number_to_take) {
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorTakeSubscribeDelegate>(this,
                                                          number_to_take));
  return return_observable;
}

Observable* Observable::drop(ScriptState*, uint64_t number_to_drop) {
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorDropSubscribeDelegate>(this,
                                                          number_to_drop));
  return return_observable;
}

Observable* Observable::flatMap(ScriptState*,
                                V8Mapper* mapper,
                                ExceptionState& exception_state) {
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorFlatMapSubscribeDelegate>(this, mapper));
  return return_observable;
}

Observable* Observable::switchMap(ScriptState*,
                                  V8Mapper* mapper,
                                  ExceptionState& exception_state) {
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorSwitchMapSubscribeDelegate>(this, mapper));
  return return_observable;
}

Observable* Observable::inspect(
    ScriptState* script_state,
    V8UnionObservableInspectorOrObserverCallback* inspector_union) {
  V8VoidFunction* subscribe_callback = nullptr;
  V8ObserverCallback* next_callback = nullptr;
  V8ObserverCallback* error_callback = nullptr;
  V8ObserverCompleteCallback* complete_callback = nullptr;
  V8ObservableInspectorAbortHandler* abort_callback = nullptr;

  if (inspector_union) {
    switch (inspector_union->GetContentType()) {
      case V8UnionObservableInspectorOrObserverCallback::ContentType::
          kObservableInspector: {
        ObservableInspector* inspector =
            inspector_union->GetAsObservableInspector();
        if (inspector->hasSubscribe()) {
          subscribe_callback = inspector->subscribe();
        }
        if (inspector->hasNext()) {
          next_callback = inspector->next();
        }
        if (inspector->hasError()) {
          error_callback = inspector->error();
        }
        if (inspector->hasComplete()) {
          complete_callback = inspector->complete();
        }
        if (inspector->hasAbort()) {
          abort_callback = inspector->abort();
        }
        break;
      }
      case V8UnionObservableInspectorOrObserverCallback::ContentType::
          kObserverCallback:
        next_callback = inspector_union->GetAsObserverCallback();
        break;
    }
  }

  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorInspectSubscribeDelegate>(
          this, next_callback, error_callback, complete_callback,
          subscribe_callback, abort_callback));
  return return_observable;
}

Observable* Observable::catchImpl(ScriptState*,
                                  V8CatchCallback* callback,
                                  ExceptionState& exception_state) {
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorCatchSubscribeDelegate>(this, callback));
  return return_observable;
}

Observable* Observable::finally(ScriptState*, V8VoidFunction* callback) {
  Observable* return_observable = MakeGarbageCollected<Observable>(
      GetExecutionContext(),
      MakeGarbageCollected<OperatorFinallySubscribeDelegate>(this, callback));
  return return_observable;
}

ScriptPromise<IDLSequence<IDLAny>> Observable::toArray(
    ScriptState* script_state,
    SubscribeOptions* options) {
  ScriptPromiseResolver<IDLSequence<IDLAny>>* resolver =
      MakeGarbageCollected<ScriptPromiseResolver<IDLSequence<IDLAny>>>(
          script_state);
  ScriptPromise<IDLSequence<IDLAny>> promise = resolver->Promise();

  AbortSignal::AlgorithmHandle* algorithm_handle = nullptr;

  if (options->hasSignal()) {
    if (options->signal()->aborted()) {
      resolver->Reject(options->signal()->reason(script_state));

      return promise;
    }

    algorithm_handle = options->signal()->AddAlgorithm(
        MakeGarbageCollected<RejectPromiseAbortAlgorithm>(resolver,
                                                          options->signal()));
  }

  ToArrayInternalObserver* internal_observer =
      MakeGarbageCollected<ToArrayInternalObserver>(resolver, algorithm_handle);

  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    options);

  return promise;
}

ScriptPromise<IDLUndefined> Observable::forEach(ScriptState* script_state,
                                                V8Visitor* callback,
                                                SubscribeOptions* options) {
  ScriptPromiseResolver<IDLUndefined>* resolver =
      MakeGarbageCollected<ScriptPromiseResolver<IDLUndefined>>(script_state);
  ScriptPromise<IDLUndefined> promise = resolver->Promise();

  AbortController* visitor_callback_controller =
      AbortController::Create(script_state);
  HeapVector<Member<AbortSignal>> signals;
  signals.push_back(visitor_callback_controller->signal());
  if (options->hasSignal()) {
    signals.push_back(options->signal());
  }

  // The internal observer associated with this operator must have the ability
  // to unsubscribe from `this`. This is important in the internal observer's
  // `next()` handler, which invokes `callback` with each passed-in value. If
  // `callback` throws an error, we must unsubscribe from `this` and reject
  // `promise`.
  //
  // This means we have to maintain a separate, internal `AbortController` that
  // will abort the subscription in that case. Consequently, this means we have
  // to subscribe with an internal `SubscribeOptions`, whose signal is always
  // present, and is a composite signal derived from the aforementioned
  // controller, and the given `options`'s signal, if present.
  SubscribeOptions* internal_options = MakeGarbageCollected<SubscribeOptions>();
  internal_options->setSignal(
      MakeGarbageCollected<AbortSignal>(script_state, signals));

  if (internal_options->signal()->aborted()) {
    resolver->Reject(internal_options->signal()->reason(script_state));
    return promise;
  }

  AbortSignal::AlgorithmHandle* algorithm_handle =
      internal_options->signal()->AddAlgorithm(
          MakeGarbageCollected<RejectPromiseAbortAlgorithm>(
              resolver, internal_options->signal()));

  OperatorForEachInternalObserver* internal_observer =
      MakeGarbageCollected<OperatorForEachInternalObserver>(
          resolver, visitor_callback_controller, callback, algorithm_handle);

  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    internal_options);

  return promise;
}

ScriptPromise<IDLAny> Observable::first(ScriptState* script_state,
                                        SubscribeOptions* options) {
  ScriptPromiseResolver<IDLAny>* resolver =
      MakeGarbageCollected<ScriptPromiseResolver<IDLAny>>(script_state);
  ScriptPromise<IDLAny> promise = resolver->Promise();

  AbortController* controller = AbortController::Create(script_state);
  HeapVector<Member<AbortSignal>> signals;

  // The internal observer associated with this operator must have the ability
  // to unsubscribe from `this`. This happens in the internal observer's
  // `next()` handler, when the first value is emitted.
  //
  // This means we have to maintain a separate, internal `AbortController` that
  // will abort the subscription. Consequently, this means we have to subscribe
  // with an internal `SubscribeOptions`, whose signal is always present, and is
  // a composite signal derived from:
  //   1. The aforementioned controller.
  signals.push_back(controller->signal());
  //   2. The given `options`'s signal, if present.
  if (options->hasSignal()) {
    signals.push_back(options->signal());
  }

  SubscribeOptions* internal_options = MakeGarbageCollected<SubscribeOptions>();
  internal_options->setSignal(
      MakeGarbageCollected<AbortSignal>(script_state, signals));

  if (internal_options->signal()->aborted()) {
    resolver->Reject(options->signal()->reason(script_state));
    return promise;
  }

  AbortSignal::AlgorithmHandle* algorithm_handle =
      internal_options->signal()->AddAlgorithm(
          MakeGarbageCollected<RejectPromiseAbortAlgorithm>(
              resolver, internal_options->signal()));

  OperatorFirstInternalObserver* internal_observer =
      MakeGarbageCollected<OperatorFirstInternalObserver>(resolver, controller,
                                                          algorithm_handle);

  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    internal_options);

  return promise;
}

ScriptPromise<IDLAny> Observable::last(ScriptState* script_state,
                                       SubscribeOptions* options) {
  ScriptPromiseResolver<IDLAny>* resolver =
      MakeGarbageCollected<ScriptPromiseResolver<IDLAny>>(script_state);
  ScriptPromise<IDLAny> promise = resolver->Promise();

  AbortSignal::AlgorithmHandle* algorithm_handle = nullptr;

  if (options->hasSignal()) {
    if (options->signal()->aborted()) {
      resolver->Reject(options->signal()->reason(script_state));
      return promise;
    }

    algorithm_handle = options->signal()->AddAlgorithm(
        MakeGarbageCollected<RejectPromiseAbortAlgorithm>(resolver,
                                                          options->signal()));
  }

  OperatorLastInternalObserver* internal_observer =
      MakeGarbageCollected<OperatorLastInternalObserver>(resolver,
                                                         algorithm_handle);

  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    options);

  return promise;
}

ScriptPromise<IDLBoolean> Observable::some(ScriptState* script_state,
                                           V8Predicate* predicate,
                                           SubscribeOptions* options) {
  ScriptPromiseResolver<IDLBoolean>* resolver =
      MakeGarbageCollected<ScriptPromiseResolver<IDLBoolean>>(script_state);
  ScriptPromise<IDLBoolean> promise = resolver->Promise();

  AbortController* controller = AbortController::Create(script_state);
  HeapVector<Member<AbortSignal>> signals;
  signals.push_back(controller->signal());
  if (options->hasSignal()) {
    signals.push_back(options->signal());
  }

  SubscribeOptions* internal_options = MakeGarbageCollected<SubscribeOptions>();
  internal_options->setSignal(
      MakeGarbageCollected<AbortSignal>(script_state, signals));

  if (internal_options->signal()->aborted()) {
    resolver->Reject(options->signal()->reason(script_state));
    return promise;
  }

  AbortSignal::AlgorithmHandle* algorithm_handle =
      internal_options->signal()->AddAlgorithm(
          MakeGarbageCollected<RejectPromiseAbortAlgorithm>(
              resolver, internal_options->signal()));

  OperatorSomeInternalObserver* internal_observer =
      MakeGarbageCollected<OperatorSomeInternalObserver>(
          resolver, controller, predicate, algorithm_handle);
  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    internal_options);

  return promise;
}

ScriptPromise<IDLBoolean> Observable::every(ScriptState* script_state,
                                            V8Predicate* predicate,
                                            SubscribeOptions* options) {
  ScriptPromiseResolver<IDLBoolean>* resolver =
      MakeGarbageCollected<ScriptPromiseResolver<IDLBoolean>>(script_state);
  ScriptPromise<IDLBoolean> promise = resolver->Promise();

  AbortController* controller = AbortController::Create(script_state);
  HeapVector<Member<AbortSignal>> signals;
  signals.push_back(controller->signal());
  if (options->hasSignal()) {
    signals.push_back(options->signal());
  }

  SubscribeOptions* internal_options = MakeGarbageCollected<SubscribeOptions>();
  internal_options->setSignal(
      MakeGarbageCollected<AbortSignal>(script_state, signals));

  if (internal_options->signal()->aborted()) {
    resolver->Reject(options->signal()->reason(script_state));
    return promise;
  }

  AbortSignal::AlgorithmHandle* algorithm_handle =
      internal_options->signal()->AddAlgorithm(
          MakeGarbageCollected<RejectPromiseAbortAlgorithm>(
              resolver, internal_options->signal()));

  OperatorEveryInternalObserver* internal_observer =
      MakeGarbageCollected<OperatorEveryInternalObserver>(
          resolver, controller, predicate, algorithm_handle);
  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    internal_options);

  return promise;
}

ScriptPromise<IDLAny> Observable::find(ScriptState* script_state,
                                       V8Predicate* predicate,
                                       SubscribeOptions* options) {
  ScriptPromiseResolver<IDLAny>* resolver =
      MakeGarbageCollected<ScriptPromiseResolver<IDLAny>>(script_state);
  ScriptPromise<IDLAny> promise = resolver->Promise();

  AbortController* controller = AbortController::Create(script_state);
  HeapVector<Member<AbortSignal>> signals;
  signals.push_back(controller->signal());
  if (options->hasSignal()) {
    signals.push_back(options->signal());
  }

  SubscribeOptions* internal_options = MakeGarbageCollected<SubscribeOptions>();
  internal_options->setSignal(
      MakeGarbageCollected<AbortSignal>(script_state, signals));

  if (internal_options->signal()->aborted()) {
    resolver->Reject(options->signal()->reason(script_state));
    return promise;
  }

  AbortSignal::AlgorithmHandle* algorithm_handle =
      internal_options->signal()->AddAlgorithm(
          MakeGarbageCollected<RejectPromiseAbortAlgorithm>(
              resolver, internal_options->signal()));

  OperatorFindInternalObserver* internal_observer =
      MakeGarbageCollected<OperatorFindInternalObserver>(
          resolver, controller, predicate, algorithm_handle);
  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    internal_options);

  return promise;
}

ScriptPromise<IDLAny> Observable::reduce(ScriptState* script_state,
                                         V8Reducer* reducer) {
  return ReduceInternal(script_state, reducer, std::nullopt,
                        MakeGarbageCollected<SubscribeOptions>());
}

ScriptPromise<IDLAny> Observable::reduce(ScriptState* script_state,
                                         V8Reducer* reducer,
                                         v8::Local<v8::Value> initialValue,
                                         SubscribeOptions* options) {
  DCHECK(options);
  return ReduceInternal(
      script_state, reducer,
      std::make_optional(ScriptValue(script_state->GetIsolate(), initialValue)),
      options);
}

ScriptPromise<IDLAny> Observable::ReduceInternal(
    ScriptState* script_state,
    V8Reducer* reducer,
    std::optional<ScriptValue> initial_value,
    SubscribeOptions* options) {
  ScriptPromiseResolver<IDLAny>* resolver =
      MakeGarbageCollected<ScriptPromiseResolver<IDLAny>>(script_state);
  ScriptPromise<IDLAny> promise = resolver->Promise();

  AbortController* controller = AbortController::Create(script_state);
  HeapVector<Member<AbortSignal>> signals;
  signals.push_back(controller->signal());
  if (options->hasSignal()) {
    signals.push_back(options->signal());
  }

  SubscribeOptions* internal_options = MakeGarbageCollected<SubscribeOptions>();
  internal_options->setSignal(
      MakeGarbageCollected<AbortSignal>(script_state, signals));

  if (internal_options->signal()->aborted()) {
    resolver->Reject(options->signal()->reason(script_state));
    return promise;
  }

  AbortSignal::AlgorithmHandle* algorithm_handle =
      internal_options->signal()->AddAlgorithm(
          MakeGarbageCollected<RejectPromiseAbortAlgorithm>(
              resolver, internal_options->signal()));

  OperatorReduceInternalObserver* internal_observer =
      MakeGarbageCollected<OperatorReduceInternalObserver>(
          resolver, controller, reducer, initial_value, algorithm_handle);
  SubscribeInternal(script_state, /*observer_union=*/nullptr, internal_observer,
                    internal_options);

  return promise;
}

void Observable::Trace(Visitor* visitor) const {
  visitor->Trace(subscribe_callback_);
  visitor->Trace(subscribe_delegate_);
  visitor->Trace(weak_subscriber_);

  ScriptWrappable::Trace(visitor);
  ExecutionContextClient::Trace(visitor);
}

}  // namespace blink