File: observable-from.any.js

package info (click to toggle)
firefox 144.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,637,504 kB
  • sloc: cpp: 7,576,692; javascript: 6,430,831; ansic: 3,748,119; python: 1,398,978; xml: 628,810; asm: 438,679; java: 186,194; sh: 63,212; makefile: 19,159; objc: 13,086; perl: 12,986; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 53; csh: 10
file content (1741 lines) | stat: -rw-r--r-- 52,280 bytes parent folder | download | duplicates (11)
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
// Because we test that the global error handler is called at various times.
setup({allow_uncaught_exception: true});

test(() => {
  assert_equals(typeof Observable.from, "function",
      "Observable.from() is a function");
}, "from(): Observable.from() is a function");

test(() => {
  assert_throws_js(TypeError, () => Observable.from(10),
      "Number cannot convert to an Observable");
  assert_throws_js(TypeError, () => Observable.from(true),
      "Boolean cannot convert to an Observable");
  assert_throws_js(TypeError, () => Observable.from("String"),
      "String cannot convert to an Observable");
  assert_throws_js(TypeError, () => Observable.from({a: 10}),
      "Object cannot convert to an Observable");
  assert_throws_js(TypeError, () => Observable.from(Symbol.iterator),
      "Bare Symbol.iterator cannot convert to an Observable");
  assert_throws_js(TypeError, () => Observable.from(Promise),
      "Promise constructor cannot convert to an Observable");
}, "from(): Failed conversions");

test(() => {
  const target = new EventTarget();
  const observable = target.when('custom');
  const from_observable = Observable.from(observable);
  assert_equals(observable, from_observable);
}, "from(): Given an observable, it returns that exact observable");

test(() => {
  let completeCalled = false;
  const results = [];
  const array = [1, 2, 3, 'a', new Date(), 15, [12]];
  const observable = Observable.from(array);
  observable.subscribe({
    next: v => results.push(v),
    error: e => assert_unreached('error is not called'),
    complete: () => completeCalled = true
  });

  assert_array_equals(results, array);
  assert_true(completeCalled);
}, "from(): Given an array");

test(() => {
  const iterable = {
    [Symbol.iterator]() {
      let n = 0;
      return {
        next() {
          n++;
          if (n <= 3) {
            return { value: n, done: false };
          }
          return { value: undefined, done: true };
        },
      };
    },
  };

  const observable = Observable.from(iterable);

  assert_true(observable instanceof Observable, "Observable.from() returns an Observable");

  const results = [];

  observable.subscribe({
    next: (value) => results.push(value),
    error: () => assert_unreached("should not error"),
    complete: () => results.push("complete"),
  });

  assert_array_equals(results, [1, 2, 3, "complete"],
      "Subscription pushes iterable values out to Observable");

  // A second subscription should restart iteration.
  observable.subscribe({
    next: (value) => results.push(value),
    error: () => assert_unreached("should not error"),
    complete: () => results.push("complete2"),
  });

  assert_array_equals(results, [1, 2, 3, "complete", 1, 2, 3, "complete2"],
      "Subscribing again causes another fresh iteration on an un-exhausted iterable");
}, "from(): Iterable converts to Observable");

// This test, and the variants below it, test the web-observable side-effects of
// converting an iterable object to an Observable. Specifically, it tracks
// exactly when the %Symbol.iterator% method is *retrieved* from the object,
// invoked, and what its error-throwing side-effects are.
//
// Even more specifically, we assert that the %Symbol.iterator% method is
// retrieved a single time when converting to an Observable, and then again when
// subscribing to the converted Observable. This makes it possible for the
// %Symbol.iterator% method getter to change return values in between conversion
// and subscription. See https://github.com/WICG/observable/issues/127 for
// related discussion.
test(() => {
  const results = [];

  const iterable = {
    get [Symbol.iterator]() {
      results.push("[Symbol.iterator] method GETTER");
      return function() {
        results.push("[Symbol.iterator implementation]");
        return {
          get next() {
            results.push("next() method GETTER");
            return function() {
              results.push("next() implementation");
              return {value: undefined, done: true};
            };
          },
        };
      };
    },
  };

  const observable = Observable.from(iterable);
  assert_array_equals(results, ["[Symbol.iterator] method GETTER"]);

  let thrownError = null;
  observable.subscribe();
  assert_array_equals(results, [
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator implementation]",
    "next() method GETTER",
    "next() implementation"
  ]);
}, "from(): [Symbol.iterator] side-effects (one observable)");

// This tests that once `Observable.from()` detects a non-null and non-undefined
// `[Symbol.iterator]` property, we've committed to converting as an iterable.
// If the value of that property is then not callable, we don't silently move on
// to the next conversion type — we throw a TypeError.
//
// That's because that's what TC39's `GetMethod()` [1] calls for, which is what
// `Observable.from()` first uses in the iterable conversion branch [2].
//
// [1]: https://tc39.es/ecma262/multipage/abstract-operations.html#sec-getmethod
// [2]: http://wicg.github.io/observable/#from-iterable-conversion
test(() => {
  let results = [];
  const iterable = {
    [Symbol.iterator]: 10,
  };

  let errorThrown = null;
  try {
    Observable.from(iterable);
  } catch(e) {
    errorThrown = e;
  }

  assert_true(errorThrown instanceof TypeError);
}, "from(): [Symbol.iterator] not callable");

test(() => {
  let results = [];
  const iterable = {
    calledOnce: false,
    get [Symbol.iterator]() {
      if (this.calledOnce) {
        // Return a non-callable primitive the second time `@@iterator` is
        // called.
        return 10;
      }

      this.calledOnce = true;
      return this.validImplementation;
    },
    validImplementation: () => {
      return {
        next() { return {done: true}; }
      }
    }
  };

  let errorThrown = null;

  const observable = Observable.from(iterable);
  observable.subscribe({
    next: v => results.push("should not be called"),
    error: e => {
      errorThrown = e;
      results.push(e);
    },
  });

  assert_array_equals(results, [errorThrown],
      "An error was plumbed through the Observable");
  assert_true(errorThrown instanceof TypeError);
}, "from(): [Symbol.iterator] not callable AFTER SUBSCRIBE throws");

test(() => {
  let results = [];
  const iterable = {
    calledOnce: false,
    validImplementation: () => {
      return {
        next() { return {done: true}; }
      }
    },
    get [Symbol.iterator]() {
      if (this.calledOnce) {
        // Return null the second time `@@iterator` is called.
        return null;
      }

      this.calledOnce = true;
      return this.validImplementation;
    }
  };

  let errorThrown = null;

  const observable = Observable.from(iterable);
  observable.subscribe({
    next: v => results.push("should not be called"),
    error: e => {
      errorThrown = e;
      results.push(e);
    },
  });

  assert_array_equals(results, [errorThrown],
      "An error was plumbed through the Observable");
  assert_true(errorThrown instanceof TypeError);
}, "from(): [Symbol.iterator] returns null AFTER SUBSCRIBE throws");

test(() => {
  let results = [];
  const customError = new Error("@@iterator override error");

  const iterable = {
    numTimesCalled: 0,

    // The first time this getter is called, it returns a legitimate function
    // that, when called, returns an iterator. Every other time it returns an
    // error-throwing function that does not return an iterator.
    get [Symbol.iterator]() {
      this.numTimesCalled++;
      results.push("[Symbol.iterator] method GETTER");

      if (this.numTimesCalled === 1) {
        return this.validIteratorImplementation;
      } else {
        return this.errorThrowingIteratorImplementation;
      }
    },

    validIteratorImplementation: function() {
      results.push("[Symbol.iterator implementation]");
      return {
        get next() {
          results.push("next() method GETTER");
          return function() {
            results.push("next() implementation");
            return {value: undefined, done: true};
          }
        }
      };
    },
    errorThrowingIteratorImplementation: function() {
      results.push("Error-throwing [Symbol.iterator] implementation");
      throw customError;
    },
  };

  const observable = Observable.from(iterable);
  assert_array_equals(results, [
    "[Symbol.iterator] method GETTER",
  ]);

  // Override iterable's `[Symbol.iterator]` protocol with an error-throwing
  // function. We assert that on subscription, this method (the new `@@iterator`
  // implementation), is called because only the raw JS object gets stored in
  // the Observable that results in conversion. This raw value must get
  // re-converted to an iterable once iteration is about to start.

  let thrownError = null;
  observable.subscribe({
    error: e => thrownError = e,
  });

  assert_equals(thrownError, customError,
      "Error thrown from next() is passed to the error() handler");
  assert_array_equals(results, [
    // Old:
    "[Symbol.iterator] method GETTER",
    // New:
    "[Symbol.iterator] method GETTER",
    "Error-throwing [Symbol.iterator] implementation"
  ]);
}, "from(): [Symbol.iterator] is not cached");

// Similar to the above test, but with more Observables!
test(() => {
  const results = [];
  let numTimesSymbolIteratorCalled = 0;
  let numTimesNextCalled = 0;

  const iterable = {
    get [Symbol.iterator]() {
      results.push("[Symbol.iterator] method GETTER");
      return this.internalIteratorImplementation;
    },
    set [Symbol.iterator](func) {
      this.internalIteratorImplementation = func;
    },

    internalIteratorImplementation: function() {
      results.push("[Symbol.iterator] implementation");
      return {
        get next() {
          results.push("next() method GETTER");
          return function() {
            results.push("next() implementation");
            return {value: undefined, done: true};
          };
        },
      };
    },
  };

  const obs1 = Observable.from(iterable);
  const obs2 = Observable.from(iterable);
  const obs3 = Observable.from(iterable);
  const obs4 = Observable.from(obs3);
  assert_equals(obs3, obs4);

  assert_array_equals(results, [
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] method GETTER",
  ]);

  obs1.subscribe();
  assert_array_equals(results, [
    // Old:
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] method GETTER",
    // New:
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] implementation",
    "next() method GETTER",
    "next() implementation",
  ]);

  iterable[Symbol.iterator] = () => {
    results.push("Error-throwing [Symbol.iterator] implementation");
    throw new Error('Symbol.iterator override error');
  };

  let errorCount = 0;

  const observer = {error: e => errorCount++};
  obs2.subscribe(observer);
  obs3.subscribe(observer);
  obs4.subscribe(observer);
  assert_equals(errorCount, 3,
      "Error-throwing `@@iterator` implementation is called once per " +
      "subscription");

  assert_array_equals(results, [
    // Old:
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] method GETTER",
    "[Symbol.iterator] implementation",
    "next() method GETTER",
    "next() implementation",
    // New:
    "[Symbol.iterator] method GETTER",
    "Error-throwing [Symbol.iterator] implementation",
    "[Symbol.iterator] method GETTER",
    "Error-throwing [Symbol.iterator] implementation",
    "[Symbol.iterator] method GETTER",
    "Error-throwing [Symbol.iterator] implementation",
  ]);
}, "from(): [Symbol.iterator] side-effects (many observables)");

test(() => {
  const customError = new Error('@@iterator next() error');
  const iterable = {
    [Symbol.iterator]() {
      return {
        next() {
          throw customError;
        }
      };
    }
  };

  let thrownError = null;
  Observable.from(iterable).subscribe({
    error: e => thrownError = e,
  });

  assert_equals(thrownError, customError,
      "Error thrown from next() is passed to the error() handler");
}, "from(): [Symbol.iterator] next() throws error");

promise_test(async () => {
  const promise = Promise.resolve('value');
  const observable = Observable.from(promise);

  assert_true(observable instanceof Observable, "Converts to Observable");

  const results = [];

  observable.subscribe({
    next: (value) => results.push(value),
    error: () => assert_unreached("error() is not called"),
    complete: () => results.push("complete()"),
  });

  assert_array_equals(results, [], "Observable does not emit synchronously");

  await promise;

  assert_array_equals(results, ["value", "complete()"],
      "Observable emits and completes after Promise resolves");
}, "from(): Converts Promise to Observable");

promise_test(async t => {
  let unhandledRejectionHandlerCalled = false;
  const unhandledRejectionHandler = () => {
    unhandledRejectionHandlerCalled = true;
  };

  self.addEventListener("unhandledrejection", unhandledRejectionHandler);
  t.add_cleanup(() => self.removeEventListener("unhandledrejection", unhandledRejectionHandler));

  const promise = Promise.reject("reason");
  const observable = Observable.from(promise);

  assert_true(observable instanceof Observable, "Converts to Observable");

  const results = [];

  observable.subscribe({
    next: (value) => assert_unreached("next() not called"),
    error: (error) => results.push(error),
    complete: () => assert_unreached("complete() not called"),
  });

  assert_array_equals(results, [], "Observable does not emit synchronously");

  let catchBlockEntered = false;
  try {
    await promise;
  } catch {
    catchBlockEntered = true;
  }

  assert_true(catchBlockEntered, "Catch block entered");
  assert_false(unhandledRejectionHandlerCalled, "No unhandledrejection event");
  assert_array_equals(results, ["reason"],
      "Observable emits error() after Promise rejects");
}, "from(): Converts rejected Promise to Observable. No " +
   "`unhandledrejection` event when error is handled by subscription");

promise_test(async t => {
  let unhandledRejectionHandlerCalled = false;
  const unhandledRejectionHandler = () => {
    unhandledRejectionHandlerCalled = true;
  };

  self.addEventListener("unhandledrejection", unhandledRejectionHandler);
  t.add_cleanup(() => self.removeEventListener("unhandledrejection", unhandledRejectionHandler));

  let errorReported = null;
  self.addEventListener("error", e => errorReported = e, { once: true });

  let catchBlockEntered = false;
  try {
    const promise = Promise.reject("custom reason");
    const observable = Observable.from(promise);

    observable.subscribe();
    await promise;
  } catch {
    catchBlockEntered = true;
  }

  assert_true(catchBlockEntered, "Catch block entered");
  assert_false(unhandledRejectionHandlerCalled,
      "No unhandledrejection event, because error got reported to global");
  assert_not_equals(errorReported, null, "Error was reported to the global");

  assert_true(errorReported.message.includes("custom reason"),
      "Error message matches");
  assert_equals(errorReported.lineno, 0, "Error lineno is 0");
  assert_equals(errorReported.colno, 0, "Error lineno is 0");
  assert_equals(errorReported.error, "custom reason",
      "Error object is equivalent");
}, "from(): Rejections not handled by subscription are reported to the " +
   "global, and still not sent as an unhandledrejection event");

test(() => {
  const results = [];
  const observable = new Observable(subscriber => {
    subscriber.next('from Observable');
    subscriber.complete();
  });

  observable[Symbol.iterator] = () => {
    results.push('Symbol.iterator() called');
    return {
      next() {
        return {value: 'from @@iterator', done: true};
      }
    };
  };

  Observable.from(observable).subscribe({
    next: v => results.push(v),
    complete: () => results.push("complete"),
  });

  assert_array_equals(results, ["from Observable", "complete"]);
}, "from(): Observable that implements @@iterator protocol gets converted " +
   "as an Observable, not iterator");

test(() => {
  const results = [];
  const promise = new Promise(resolve => {
    resolve('from Promise');
  });

  promise[Symbol.iterator] = () => {
    let done = false;
    return {
      next() {
        if (!done) {
          done = true;
          return {value: 'from @@iterator', done: false};
        } else {
          return {value: undefined, done: true};
        }
      }
    };
  };

  Observable.from(promise).subscribe({
    next: v => results.push(v),
    complete: () => results.push("complete"),
  });

  assert_array_equals(results, ["from @@iterator", "complete"]);
}, "from(): Promise that implements @@iterator protocol gets converted as " +
   "an iterable, not Promise");

// When the [Symbol.iterator] method on a given object is undefined, we don't
// try to convert the object to an Observable via the iterable protocol. The
// Observable specification *also* does the same thing if the [Symbol.iterator]
// method is *null*. That is, in that case we also skip the conversion via
// iterable protocol, and continue to try and convert the object as another type
// (in this case, a Promise).
promise_test(async () => {
  const promise = new Promise(resolve => resolve('from Promise'));
  assert_equals(promise[Symbol.iterator], undefined);
  promise[Symbol.iterator] = null;
  assert_equals(promise[Symbol.iterator], null);

  const value = await new Promise(resolve => {
    Observable.from(promise).subscribe(value => resolve(value));
  });

  assert_equals(value, 'from Promise');
}, "from(): Promise whose [Symbol.iterator] returns null converts as Promise");

// This is a more sensitive test, which asserts that even just trying to reach
// for the [Symbol.iterator] method on an object whose *getter* for the
// [Symbol.iterator] method throws an error, results in `Observable#from()`
// rethrowing that error.
test(() => {
  const error = new Error('thrown from @@iterator getter');
  const obj = {
    get [Symbol.iterator]() {
      throw error;
    }
  }

  try {
    Observable.from(obj);
    assert_unreached("from() conversion throws");
  } catch(e) {
    assert_equals(e, error);
  }
}, "from(): Rethrows the error when Converting an object whose @@iterator " +
   "method *getter* throws an error");

// This test exercises the line of spec prose that says:
//
// "If |asyncIteratorMethodRecord|'s [[Value]] is undefined or null, then jump
// to the step labeled 'From iterable'."
test(() => {
  const sync_iterable = {
    [Symbol.asyncIterator]: null,
    [Symbol.iterator]() {
      return {
        value: 0,
        next() {
          if (this.value === 2)
            return {value: undefined, done: true};
          else
            return {value: this.value++, done: false};
        }
      }
    },
  };

  const results = [];
  const source = Observable.from(sync_iterable).subscribe(v => results.push(v));
  assert_array_equals(results, [0, 1]);
}, "from(): Async iterable protocol null, converts as iterator");

promise_test(async t => {
  const results = [];
  const async_iterable = {
    [Symbol.asyncIterator]() {
      results.push("[Symbol.asyncIterator]() invoked");
      return {
        val: 0,
        next() {
          return new Promise(resolve => {
            t.step_timeout(() => {
              resolve({
                value: this.val,
                done: this.val++ === 4 ? true : false,
              });
            }, 400);
          });
        },
      };
    },
  };

  const source = Observable.from(async_iterable);
  assert_array_equals(results, []);

  await new Promise(resolve => {
    source.subscribe({
      next: v => {
        results.push(`Observing ${v}`);
        queueMicrotask(() => results.push(`next() microtask interleaving (v=${v})`));
      },
      complete: () => {
        results.push('complete()');
        resolve();
      },
    });
  });

  assert_array_equals(results, [
    "[Symbol.asyncIterator]() invoked",
    "Observing 0",
    "next() microtask interleaving (v=0)",
    "Observing 1",
    "next() microtask interleaving (v=1)",
    "Observing 2",
    "next() microtask interleaving (v=2)",
    "Observing 3",
    "next() microtask interleaving (v=3)",
    "complete()",
  ]);
}, "from(): Asynchronous iterable conversion");

// This test is a more chaotic version of the above. It ensures that a single
// Observable can handle multiple in-flight subscriptions to the same underlying
// async iterable without the two subscriptions competing. It asserts that the
// asynchronous values are pushed to the observers in the correct order.
promise_test(async t => {
  const async_iterable = {
    [Symbol.asyncIterator]() {
      return {
        val: 0,
        next() {
          // Returns a Promise that resolves in a random amount of time less
          // than a second.
          return new Promise(resolve => {
            t.step_timeout(() => resolve({
              value: this.val,
              done: this.val++ === 4 ? true : false,
            }), 200);
          });
        },
      };
    },
  };

  const results = [];
  const source = Observable.from(async_iterable);

  const promise = new Promise(resolve => {
    source.subscribe({
      next: v => {
        results.push(`${v}-first-sub`);

        // Half-way through the first subscription, start another subscription.
        if (v === 0) {
          source.subscribe({
            next: v => results.push(`${v}-second-sub`),
            complete: () => {
              results.push('complete-second-sub');
              resolve();
            }
          });
        }
      },
      complete: () => {
        results.push('complete-first-sub');
        resolve();
      }
    });
  });

  await promise;
  assert_array_equals(results, [
    '0-first-sub',

    '1-first-sub',
    '1-second-sub',

    '2-first-sub',
    '2-second-sub',

    '3-first-sub',
    '3-second-sub',

    'complete-first-sub',
    'complete-second-sub',
  ]);
}, "from(): Asynchronous iterable multiple in-flight subscriptions");
// This test is like the above, ensuring that multiple subscriptions to the same
// sync-iterable-converted-Observable can exist at a time. Since sync iterables
// push all of their values to the Observable synchronously, the way to do this
// is subscribe to the sync iterable Observable *inside* the next handler of the
// same Observable.
test(() => {
  const results = [];

  const array = [1, 2, 3, 4, 5];
  const source = Observable.from(array);
  source.subscribe({
    next: v => {
      results.push(`${v}-first-sub`);
      if (v === 3) {
        // Pushes all 5 values to `results` right after the first instance of `3`.
        source.subscribe({
          next: v => results.push(`${v}-second-sub`),
          complete: () => results.push('complete-second-sub'),
        });
      }
    },
    complete: () => results.push('complete-first-sub'),
  });

  assert_array_equals(results, [
    // These values are pushed when there is only a single subscription.
    '1-first-sub', '2-first-sub', '3-first-sub',
    // These values are pushed in the correct order, for two subscriptions.
    '4-first-sub', '4-second-sub',
    '5-first-sub', '5-second-sub',
    'complete-first-sub', 'complete-second-sub',
  ]);
}, "from(): Sync iterable multiple in-flight subscriptions");

promise_test(async () => {
  const async_generator = async function*() {
    yield 1;
    yield 2;
    yield 3;
  };

  const results = [];
  const source = Observable.from(async_generator());

  const subscribeFunction = function(resolve) {
    source.subscribe({
      next: v => results.push(v),
      complete: () => resolve(),
    });
  }
  await new Promise(subscribeFunction);
  assert_array_equals(results, [1, 2, 3]);
  await new Promise(subscribeFunction);
  assert_array_equals(results, [1, 2, 3]);
}, "from(): Asynchronous generator conversion: can only be used once");

// The value returned by an async iterator object's `next()` method is supposed
// to be a Promise. But this requirement "isn't enforced": see [1]. Therefore,
// the Observable spec unconditionally wraps the return value in a resolved
// Promise, as is standard practice [2].
//
// This test ensures that even if the object returned from an async iterator's
// `next()` method is a synchronously-available object with `done: true`
// (instead of a Promise), the `done` property is STILL not retrieved
// synchronously. In other words, we test that the Promise-wrapping is
// implemented.
//
// [1]: https://tc39.es/ecma262/#table-async-iterator-r
// [2]: https://matrixlogs.bakkot.com/WHATWG/2024-08-30#L30
promise_test(async () => {
  const results = [];

  const async_iterable = {
    [Symbol.asyncIterator]() {
      return {
        next() {
          return {
            value: undefined,
            get done() {
              results.push('done() GETTER called');
              return true;
            },
          };
        },
      };
    },
  };

  const source = Observable.from(async_iterable);
  assert_array_equals(results, []);

  queueMicrotask(() => results.push('Microtask queued before subscription'));
  source.subscribe();
  assert_array_equals(results, []);

  await Promise.resolve();
  assert_array_equals(results, [
    "Microtask queued before subscription",
    "done() GETTER called",
  ]);
}, "from(): Promise-wrapping semantics of IteratorResult interface");

// Errors thrown from [Symbol.asyncIterator] are propagated to the observer
// synchronously. This is because in language constructs (i.e., for-await of
// loops) that invoke [Symbol.asyncIterator]() that throw errors, the errors are
// synchronously propagated to script outside of the loop, and are catchable.
// Observables follow this precedent.
test(() => {
  const error = new Error("[Symbol.asyncIterator] error");
  const results = [];
  const async_iterable = {
    [Symbol.asyncIterator]() {
      results.push("[Symbol.asyncIterator]() invoked");
      throw error;
    }
  };

  Observable.from(async_iterable).subscribe({
    error: e => results.push(e),
  });

  assert_array_equals(results, [
    "[Symbol.asyncIterator]() invoked",
    error,
  ]);
}, "from(): Errors thrown in Symbol.asyncIterator() are propagated synchronously");

// AsyncIterable: next() throws exception instead of return Promise. Any errors
// that occur during the retrieval of `next()` always result in a rejected
// Promise. Therefore, the error makes it to the Observer with microtask timing.
promise_test(async () => {
  const nextError = new Error('next error');
  const async_iterable = {
    [Symbol.asyncIterator]() {
      return {
        get next() {
          throw nextError;
        }
      };
    }
  };

  const results = [];
  Observable.from(async_iterable).subscribe({
    error: e => results.push(e),
  });

  assert_array_equals(results, []);
  // Wait one microtask since the error will be propagated through a rejected
  // Promise managed by the async iterable conversion semantics.
  await Promise.resolve();
  assert_array_equals(results, [nextError]);
}, "from(): Errors thrown in async iterator's next() GETTER are propagated " +
   "in a microtask");
promise_test(async () => {
  const nextError = new Error('next error');
  const async_iterable = {
    [Symbol.asyncIterator]() {
      return {
        next() {
          throw nextError;
        }
      };
    }
  };

  const results = [];
  Observable.from(async_iterable).subscribe({
    error: e => results.push(e),
  });

  assert_array_equals(results, []);
  await Promise.resolve();
  assert_array_equals(results, [nextError]);
}, "from(): Errors thrown in async iterator's next() are propagated in a microtask");

test(() => {
  const results = [];
  const iterable = {
    [Symbol.iterator]() {
      return {
        val: 0,
        next() {
          results.push(`IteratorRecord#next() pushing ${this.val}`);
          return {
            value: this.val,
            done: this.val++ === 10 ? true : false,
          };
        },
        return() {
          results.push(`IteratorRecord#return() called with this.val=${this.val}`);
        },
      };
    },
  };

  const ac = new AbortController();
  Observable.from(iterable).subscribe(v => {
    results.push(`Observing ${v}`);
    if (v === 3) {
      ac.abort();
    }
  }, {signal: ac.signal});

  assert_array_equals(results, [
    "IteratorRecord#next() pushing 0",
    "Observing 0",
    "IteratorRecord#next() pushing 1",
    "Observing 1",
    "IteratorRecord#next() pushing 2",
    "Observing 2",
    "IteratorRecord#next() pushing 3",
    "Observing 3",
    "IteratorRecord#return() called with this.val=4",
  ]);
}, "from(): Aborting sync iterable midway through iteration both stops iteration " +
   "and invokes `IteratorRecord#return()");
// Like the above test, but for async iterables.
promise_test(async t => {
  const results = [];
  const iterable = {
    [Symbol.asyncIterator]() {
      return {
        val: 0,
        next() {
          results.push(`IteratorRecord#next() pushing ${this.val}`);
          return {
            value: this.val,
            done: this.val++ === 10 ? true : false,
          };
        },
        return(reason) {
          results.push(`IteratorRecord#return() called with reason=${reason}`);
          return {done: true};
        },
      };
    },
  };

  const ac = new AbortController();
  await new Promise(resolve => {
    Observable.from(iterable).subscribe(v => {
      results.push(`Observing ${v}`);
      if (v === 3) {
        ac.abort(`Aborting because v=${v}`);
        resolve();
      }
    }, {signal: ac.signal});
  });

  assert_array_equals(results, [
    "IteratorRecord#next() pushing 0",
    "Observing 0",
    "IteratorRecord#next() pushing 1",
    "Observing 1",
    "IteratorRecord#next() pushing 2",
    "Observing 2",
    "IteratorRecord#next() pushing 3",
    "Observing 3",
    "IteratorRecord#return() called with reason=Aborting because v=3",
  ]);
}, "from(): Aborting async iterable midway through iteration both stops iteration " +
   "and invokes `IteratorRecord#return()");

test(() => {
  const iterable = {
    [Symbol.iterator]() {
      return {
        val: 0,
        next() {
          return {value: this.val, done: this.val++ === 10 ? true : false};
        },
        // Not returning an Object results in a TypeError being thrown.
        return(reason) {},
      };
    },
  };

  let thrownError = null;
  const ac = new AbortController();
  Observable.from(iterable).subscribe(v => {
    if (v === 3) {
      try {
        ac.abort(`Aborting because v=${v}`);
      } catch (e) {
        thrownError = e;
      }
    }
  }, {signal: ac.signal});

  assert_not_equals(thrownError, null, "abort() threw an Error");
  assert_true(thrownError instanceof TypeError);
  assert_true(thrownError.message.includes('return()'));
  assert_true(thrownError.message.includes('Object'));
}, "from(): Sync iterable: `Iterator#return()` must return an Object, or an " +
   "error is thrown");
// This test is just like the above but for async iterables. It asserts that a
// Promise is rejected when `return()` does not return an Object.
promise_test(async t => {
  const iterable = {
    [Symbol.asyncIterator]() {
      return {
        val: 0,
        next() {
          return {value: this.val, done: this.val++ === 10 ? true : false};
        },
        // Not returning an Object results in a rejected Promise.
        return(reason) {},
      };
    },
  };

  const unhandled_rejection_promise = new Promise((resolve, reject) => {
    const unhandled_rejection_handler = e => resolve(e.reason);
    self.addEventListener("unhandledrejection", unhandled_rejection_handler);
    t.add_cleanup(() =>
        self.removeEventListener("unhandledrejection", unhandled_rejection_handler));

    t.step_timeout(() => reject('Timeout'), 3000);
  });

  const ac = new AbortController();
  await new Promise(resolve => {
    Observable.from(iterable).subscribe(v => {
      if (v === 3) {
        ac.abort(`Aborting because v=${v}`);
        resolve();
      }
    }, {signal: ac.signal});
  });

  const reason = await unhandled_rejection_promise;
  assert_true(reason instanceof TypeError);
  assert_true(reason.message.includes('return()'));
  assert_true(reason.message.includes('Object'));
}, "from(): Async iterable: `Iterator#return()` must return an Object, or a " +
   "Promise rejects asynchronously");

// This test exercises the logic of `GetIterator()` async->sync fallback
// logic. Specifically, we have an object that is an async iterable — that is,
// it has a callback [Symbol.asyncIterator] implementation. Observable.from()
// detects this, and commits to converting the object from the async iterable
// protocol. Then, after conversion but before subscription, the object is
// modified such that it no longer implements the async iterable protocol.
//
// But since it still implements the *iterable* protocol, ECMAScript's
// `GetIterator()` abstract algorithm [1] is fully exercised, which is spec'd to
// fall-back to the synchronous iterable protocol if it exists, and create a
// fully async iterable out of the synchronous iterable.
//
// [1]: https://tc39.es/ecma262/#sec-getiterator
promise_test(async () => {
  const results = [];
  const async_iterable = {
    asyncIteratorGotten: false,
    get [Symbol.asyncIterator]() {
      results.push("[Symbol.asyncIterator] GETTER");
      if (this.asyncIteratorGotten) {
        return null; // Both null and undefined work here.
      }

      this.asyncIteratorGotten = true;
      // The only requirement for `this` to be converted as an async
      // iterable -> Observable is that the return value be callable (i.e., a function).
      return function() {};
    },

    [Symbol.iterator]() {
      results.push('[Symbol.iterator]() invoked as fallback');
      return {
        val: 0,
        next() {
          return {
            value: this.val,
            done: this.val++ === 4 ? true : false,
          };
        },
      };
    },
  };

  const source = Observable.from(async_iterable);
  assert_array_equals(results, [
    "[Symbol.asyncIterator] GETTER",
  ]);

  await new Promise((resolve, reject) => {
    source.subscribe({
      next: v => {
        results.push(`Observing ${v}`);
        queueMicrotask(() => results.push(`next() microtask interleaving (v=${v})`));
      },
      error: e => reject(e),
      complete: () => {
        results.push('complete()');
        resolve();
      },
    });
  });

  assert_array_equals(results, [
    // Old:
    "[Symbol.asyncIterator] GETTER",
    // New:
    "[Symbol.asyncIterator] GETTER",
    "[Symbol.iterator]() invoked as fallback",
    "Observing 0",
    "next() microtask interleaving (v=0)",
    "Observing 1",
    "next() microtask interleaving (v=1)",
    "Observing 2",
    "next() microtask interleaving (v=2)",
    "Observing 3",
    "next() microtask interleaving (v=3)",
    "complete()",
  ]);
}, "from(): Asynchronous iterable conversion, with synchronous iterable fallback");

test(() => {
  const results = [];
  let generatorFinalized = false;

  const generator = function*() {
    try {
      for (let n = 0; n < 10; n++) {
        yield n;
      }
    } finally {
      generatorFinalized = true;
    }
  };

  const observable = Observable.from(generator());
  const abortController = new AbortController();

  observable.subscribe(n => {
    results.push(n);
    if (n === 3) {
      abortController.abort();
    }
  }, {signal: abortController.signal});

  assert_array_equals(results, [0, 1, 2, 3]);
  assert_true(generatorFinalized);
}, "from(): Generator finally block runs when subscription is aborted");

test(() => {
  const results = [];
  let generatorFinalized = false;

  const generator = function*() {
    try {
      for (let n = 0; n < 10; n++) {
        yield n;
      }
    } catch {
      assert_unreached("generator should not be aborted");
    } finally {
      generatorFinalized = true;
    }
  };

  const observable = Observable.from(generator());

  observable.subscribe((n) => {
    results.push(n);
  });

  assert_array_equals(results, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
  assert_true(generatorFinalized);
}, "from(): Generator finally block run when Observable completes");

test(() => {
  const results = [];
  let generatorFinalized = false;

  const generator = function*() {
    try {
      for (let n = 0; n < 10; n++) {
        yield n;
      }
      throw new Error('from the generator');
    } finally {
      generatorFinalized = true;
    }
  };

  const observable = Observable.from(generator());

  observable.subscribe({
    next: n => results.push(n),
    error: e => results.push(e.message)
  });

  assert_array_equals(results, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "from the generator"]);
  assert_true(generatorFinalized);
}, "from(): Generator finally block run when Observable errors");

promise_test(async t => {
  const results = [];
  let generatorFinalized = false;

  async function* asyncGenerator() {
    try {
      for (let n = 0; n < 10; n++) {
        yield n;
      }
    } finally {
      generatorFinalized = true;
    }
  }

  const observable = Observable.from(asyncGenerator());
  const abortController = new AbortController();

  await new Promise((resolve) => {
    observable.subscribe((n) => {
      results.push(n);
      if (n === 3) {
        abortController.abort();
        resolve();
      }
    }, {signal: abortController.signal});
  });

  assert_array_equals(results, [0, 1, 2, 3]);
  assert_true(generatorFinalized);
}, "from(): Async generator finally block run when subscription is aborted");

promise_test(async t => {
  const results = [];
  let generatorFinalized = false;

  async function* asyncGenerator() {
    try {
      for (let n = 0; n < 10; n++) {
        yield n;
      }
    } finally {
      generatorFinalized = true;
    }
  }

  const observable = Observable.from(asyncGenerator());

  await new Promise(resolve => {
    observable.subscribe({
      next: n => results.push(n),
      complete: () => resolve(),
    });
  });

  assert_array_equals(results, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
  assert_true(generatorFinalized);
}, "from(): Async generator finally block runs when Observable completes");

promise_test(async t => {
  const results = [];
  let generatorFinalized = false;

  async function* asyncGenerator() {
    try {
      for (let n = 0; n < 10; n++) {
        if (n === 4) {
          throw new Error('from the async generator');
        }
        yield n;
      }
    } finally {
      generatorFinalized = true;
    }
  }

  const observable = Observable.from(asyncGenerator());

  await new Promise((resolve) => {
    observable.subscribe({
      next: (n) => results.push(n),
      error: (e) => {
        results.push(e.message);
        resolve();
      }
    });
  });

  assert_array_equals(results, [0, 1, 2, 3, "from the async generator"]);
  assert_true(generatorFinalized);
}, "from(): Async generator finally block run when Observable errors");

// Test what happens when `return()` throws an error upon abort.
test(() => {
  const results = [];
  const iterable = {
    [Symbol.iterator]() {
      return {
        val: 0,
        next() {
          results.push('next() called');
          return {value: this.val, done: this.val++ === 10 ? true : false};
        },
        return() {
          results.push('return() about to throw an error');
          throw new Error('return() error');
        },
      };
    }
  };

  const ac = new AbortController();
  const source = Observable.from(iterable);
  source.subscribe(v => {
    if (v === 3) {
      try {
        ac.abort();
      } catch (e) {
        results.push(`AbortController#abort() threw an error: ${e.message}`);
      }
    }
  }, {signal: ac.signal});

  assert_array_equals(results, [
    'next() called',
    'next() called',
    'next() called',
    'next() called',
    'return() about to throw an error',
    'AbortController#abort() threw an error: return() error',
  ]);
}, "from(): Sync iterable: error thrown from IteratorRecord#return() can be " +
   "synchronously caught");
promise_test(async t => {
  const results = [];
  const iterable = {
    [Symbol.asyncIterator]() {
      return {
        val: 0,
        next() {
          results.push('next() called');
          return {value: this.val, done: this.val++ === 10 ? true : false};
        },
        return() {
          results.push('return() about to throw an error');
          // For async iterables, errors thrown in `return()` end up in a
          // returned rejected Promise, so no error appears on the stack
          // immediately. See [1].
          //
          // [1]: https://whatpr.org/webidl/1397.html#async-iterator-close.
          throw new Error('return() error');
        },
      };
    }
  };

  const unhandled_rejection_promise = new Promise((resolve, reject) => {
    const unhandled_rejection_handler = e => resolve(e.reason);
    self.addEventListener("unhandledrejection", unhandled_rejection_handler);
    t.add_cleanup(() =>
        self.removeEventListener("unhandledrejection", unhandled_rejection_handler));

    t.step_timeout(() => reject('Timeout'), 1500);
  });

  const ac = new AbortController();
  const source = Observable.from(iterable);
  await new Promise((resolve, reject) => {
    source.subscribe(v => {
      if (v === 3) {
        try {
          ac.abort();
          results.push('No error thrown synchronously');
          resolve('No error thrown synchronously');
        } catch (e) {
          results.push(`AbortController#abort() threw an error: ${e.message}`);
          reject(e);
        }
      }
    }, {signal: ac.signal});
  });

  assert_array_equals(results, [
    'next() called',
    'next() called',
    'next() called',
    'next() called',
    'return() about to throw an error',
    'No error thrown synchronously',
  ]);

  const reason = await unhandled_rejection_promise;
  assert_true(reason instanceof Error);
  assert_equals(reason.message, "return() error",
      "Custom error text passed through rejected Promise");
}, "from(): Async iterable: error thrown from IteratorRecord#return() is " +
   "wrapped in rejected Promise");

test(() => {
  const results = [];
  const iterable = {
    getter() {
      results.push('GETTER called');
      return () => {
        results.push('Obtaining iterator');
        return {
          next() {
            results.push('next() running');
            return {done: true};
          }
        };
      };
    }
  };

  Object.defineProperty(iterable, Symbol.iterator, {
    get: iterable.getter
  });
  {
    const source = Observable.from(iterable);
    assert_array_equals(results, ["GETTER called"]);
    source.subscribe({}, {signal: AbortSignal.abort()});
    assert_array_equals(results, ["GETTER called"]);
  }
  iterable[Symbol.iterator] = undefined;
  Object.defineProperty(iterable, Symbol.asyncIterator, {
    get: iterable.getter
  });
  {
    const source = Observable.from(iterable);
    assert_array_equals(results, ["GETTER called", "GETTER called"]);
    source.subscribe({}, {signal: AbortSignal.abort()});
    assert_array_equals(results, ["GETTER called", "GETTER called"]);
  }
}, "from(): Subscribing to an iterable Observable with an aborted signal " +
   "does not call next()");

test(() => {
  let results = [];

  const iterable = {
    controller: null,
    calledOnce: false,
    getter() {
      results.push('GETTER called');
      if (!this.calledOnce) {
        this.calledOnce = true;
        return () => {
          results.push('NOT CALLED');
          // We don't need to return anything here. The only time this path is
          // hit is during `Observable.from()` which doesn't actually obtain an
          // iterator. It just samples the iterable protocol property to ensure
          // that it's valid.
        };
      }

      // This path is only called the second time the iterator protocol getter
      // is run.
      this.controller.abort();
      return () => {
        results.push('iterator obtained');
        return {
          val: 0,
          next() {
            results.push('next() called');
            return {done: true};
          },
          return() {
            results.push('return() called');
          }
        };
      };
    }
  };

  // Test for sync iterators.
  {
    const ac = new AbortController();
    iterable.controller = ac;
    Object.defineProperty(iterable, Symbol.iterator, {
      get: iterable.getter,
    });

    const source = Observable.from(iterable);
    assert_false(ac.signal.aborted, "[Sync iterator]: signal is not yet aborted after from() conversion");
    assert_array_equals(results, ["GETTER called"]);

    source.subscribe({
      next: n => results.push(n),
      complete: () => results.push('complete'),
    }, {signal: ac.signal});
    assert_true(ac.signal.aborted, "[Sync iterator]: signal is aborted during subscription");
    assert_array_equals(results, ["GETTER called", "GETTER called", "iterator obtained"]);
  }

  results = [];

  // Test for async iterators.
  {
    // Reset `iterable` so it can be reused.
    const ac = new AbortController();
    iterable.controller = ac;
    iterable.calledOnce = false;
    iterable[Symbol.iterator] = undefined;
    Object.defineProperty(iterable, Symbol.asyncIterator, {
      get: iterable.getter
    });

    const source = Observable.from(iterable);
    assert_false(ac.signal.aborted, "[Async iterator]: signal is not yet aborted after from() conversion");
    assert_array_equals(results, ["GETTER called"]);

    source.subscribe({
      next: n => results.push(n),
      complete: () => results.push('complete'),
    }, {signal: ac.signal});
    assert_true(ac.signal.aborted, "[Async iterator]: signal is aborted during subscription");
    assert_array_equals(results, ["GETTER called", "GETTER called", "iterator obtained"]);
  }
}, "from(): When iterable conversion aborts the subscription, next() is " +
   "never called");

// This test asserts some very subtle behavior with regard to async iterables
// and a mid-subscription signal abort. Specifically it detects that a signal
// abort ensures that the `next()` method is not called again on the iterator
// again, BUT detects that pending Promise from the *previous* `next()` call
// still has its IteratorResult object examined. I.e., the implementation
// inspecting the `done` attribute on the resolved IteratorResult is observable
// event after abort() takes place.
promise_test(async () => {
  const results = [];
  let resolveNext = null;

  const iterable = {
    [Symbol.asyncIterator]() {
      return {
        next() {
          results.push('next() called');
          return new Promise(resolve => {
            resolveNext = resolve;
          });
        },
        return() {
          results.push('return() called');
        }
      };
    }
  };

  const ac = new AbortController();
  const source = Observable.from(iterable);
  source.subscribe({
    next: v => results.push(v),
    complete: () => results.push('complete'),
  }, {signal: ac.signal});

  assert_array_equals(results, [
    "next() called",
  ]);

  // First abort, ensuring `return()` is called.
  ac.abort();

  assert_array_equals(results, [
    "next() called",
    "return() called",
  ]);

  // Then resolve the pending `next()` Promise to an object whose `done` getter
  // reports to the test whether it was accessed. We have to wait one microtask
  // for the internal Observable implementation to finish "reacting" to said
  // `next()` promise resolution, for it to grab the `done` attribute.
  await new Promise(resolveOuter => {
    resolveNext({
      get done() {
        results.push('IteratorResult.done GETTER');
        resolveOuter();
        return true;
      }
    });
  });

  assert_array_equals(results, [
    "next() called",
    "return() called",
    "IteratorResult.done GETTER",
    // Note that "next() called" does not make another appearance.
  ]);
}, "from(): Aborting an async iterable subscription stops subsequent next() " +
   "calls, but old next() Promise reactions are web-observable");

test(() => {
  const results = [];
  const iterable = {
    [Symbol.iterator]() {
      return {
        val: 0,
        next() {
          return {value: this.val, done: this.val++ === 4 ? true : false};
        },
        return() {
          results.push('return() called');
        },
      };
    }
  };

  const source = Observable.from(iterable);
  const ac = new AbortController();
  source.subscribe({
    next: v => results.push(v),
    complete: () => results.push('complete'),
  }, {signal: ac.signal});

  ac.abort(); // Must do nothing!
  assert_array_equals(results, [0, 1, 2, 3, 'complete']);
}, "from(): Abort after complete does NOT call IteratorRecord#return()");

test(() => {
  const controller = new AbortController();
  // Invalid @@asyncIterator protocol that also aborts the subscription. By the
  // time the invalid-ness of the protocol is detected, the controller has been
  // aborted, meaning that invalid-ness cannot manifest itself in the form of an
  // error that goes to the Observable's subscriber. Instead, it gets reported
  // to the global.
  const asyncIterable = {
    calledOnce: false,
    get[Symbol.asyncIterator]() {
      // This `calledOnce` path is to ensure the Observable first converts
      // correctly via `Observable.from()`, but *later* fails in the path where
      // `@@asyncIterator` is null.
      if (this.calledOnce) {
        controller.abort();
        return null;
      } else {
        this.calledOnce = true;
        return this.validImplementation;
      }
    },
    validImplementation() {
      controller.abort();
      return null;
    }
  };

  let reportedError = null;
  self.addEventListener("error", e => reportedError = e.error, {once: true});

  let errorThrown = null;
  const observable = Observable.from(asyncIterable);
  observable.subscribe({
    error: e => errorThrown = e,
  }, {signal: controller.signal});

  assert_equals(errorThrown, null, "Protocol error is not surfaced to the Subscriber");

  assert_not_equals(reportedError, null, "Protocol error is reported to the global");
  assert_true(reportedError instanceof TypeError);
}, "Invalid async iterator protocol error is surfaced before Subscriber#signal is consulted");

test(() => {
  const controller = new AbortController();
  const iterable = {
    calledOnce: false,
    get[Symbol.iterator]() {
      if (this.calledOnce) {
        controller.abort();
        return null;
      } else {
        this.calledOnce = true;
        return this.validImplementation;
      }
    },
    validImplementation() {
      controller.abort();
      return null;
    }
  };

  let reportedError = null;
  self.addEventListener("error", e => reportedError = e.error, {once: true});

  let errorThrown = null;
  const observable = Observable.from(iterable);
  observable.subscribe({
    error: e => errorThrown = e,
  }, {signal: controller.signal});

  assert_equals(errorThrown, null, "Protocol error is not surfaced to the Subscriber");

  assert_not_equals(reportedError, null, "Protocol error is reported to the global");
  assert_true(reportedError instanceof TypeError);
}, "Invalid iterator protocol error is surfaced before Subscriber#signal is consulted");

// Regression test for https://github.com/WICG/observable/issues/208.
promise_test(async () => {
  let errorReported = false;
  self.onerror = e => errorReported = true;

  // `first()` aborts the subscription after the first item is encountered.
  const value = await Observable.from([1, 2, 3]).first();
  assert_false(errorReported);
}, "No error is reported when aborting a subscription to a sync iterator " +
   "that has no `return()` implementation");