summaryrefslogtreecommitdiffstats
path: root/comm/chat/protocols/matrix/lib/matrix-sdk/models/room.js
blob: d1bc8379712c569f8f57d141dacd36cfe4857bba (plain)
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
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RoomNameType = exports.RoomEvent = exports.Room = exports.NotificationCountType = exports.KNOWN_SAFE_ROOM_VERSION = void 0;
var _matrixEventsSdk = require("matrix-events-sdk");
var _eventTimelineSet = require("./event-timeline-set");
var _eventTimeline = require("./event-timeline");
var _contentRepo = require("../content-repo");
var _utils = require("../utils");
var _event = require("./event");
var _eventStatus = require("./event-status");
var _roomMember = require("./room-member");
var _roomSummary = require("./room-summary");
var _logger = require("../logger");
var _ReEmitter = require("../ReEmitter");
var _event2 = require("../@types/event");
var _client = require("../client");
var _filter = require("../filter");
var _roomState = require("./room-state");
var _beacon = require("./beacon");
var _thread = require("./thread");
var _read_receipts = require("../@types/read_receipts");
var _relationsContainer = require("./relations-container");
var _readReceipt = require("./read-receipt");
var _poll = require("./poll");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
                                                                                                                                                                                                                                                                                                                                                                                          Copyright 2015 - 2023 The Matrix.org Foundation C.I.C.
                                                                                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                                                          Licensed under the Apache License, Version 2.0 (the "License");
                                                                                                                                                                                                                                                                                                                                                                                          you may not use this file except in compliance with the License.
                                                                                                                                                                                                                                                                                                                                                                                          You may obtain a copy of the License at
                                                                                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                                                              http://www.apache.org/licenses/LICENSE-2.0
                                                                                                                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                                                                                                                          Unless required by applicable law or agreed to in writing, software
                                                                                                                                                                                                                                                                                                                                                                                          distributed under the License is distributed on an "AS IS" BASIS,
                                                                                                                                                                                                                                                                                                                                                                                          WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                                                                                                                                                                                                                                                                                                                                                                                          See the License for the specific language governing permissions and
                                                                                                                                                                                                                                                                                                                                                                                          limitations under the License.
                                                                                                                                                                                                                                                                                                                                                                                          */
// These constants are used as sane defaults when the homeserver doesn't support
// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be
// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the
// room versions which are considered okay for people to run without being asked
// to upgrade (ie: "stable"). Eventually, we should remove these when all homeservers
// return an m.room_versions capability.
const KNOWN_SAFE_ROOM_VERSION = "10";
exports.KNOWN_SAFE_ROOM_VERSION = KNOWN_SAFE_ROOM_VERSION;
const SAFE_ROOM_VERSIONS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
// When inserting a visibility event affecting event `eventId`, we
// need to scan through existing visibility events for `eventId`.
// In theory, this could take an unlimited amount of time if:
//
// - the visibility event was sent by a moderator; and
// - `eventId` already has many visibility changes (usually, it should
//   be 2 or less); and
// - for some reason, the visibility changes are received out of order
//   (usually, this shouldn't happen at all).
//
// For this reason, we limit the number of events to scan through,
// expecting that a broken visibility change for a single event in
// an extremely uncommon case (possibly a DoS) is a small
// price to pay to keep matrix-js-sdk responsive.
const MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30;
let NotificationCountType = /*#__PURE__*/function (NotificationCountType) {
  NotificationCountType["Highlight"] = "highlight";
  NotificationCountType["Total"] = "total";
  return NotificationCountType;
}({});
exports.NotificationCountType = NotificationCountType;
let RoomEvent = /*#__PURE__*/function (RoomEvent) {
  RoomEvent["MyMembership"] = "Room.myMembership";
  RoomEvent["Tags"] = "Room.tags";
  RoomEvent["AccountData"] = "Room.accountData";
  RoomEvent["Receipt"] = "Room.receipt";
  RoomEvent["Name"] = "Room.name";
  RoomEvent["Redaction"] = "Room.redaction";
  RoomEvent["RedactionCancelled"] = "Room.redactionCancelled";
  RoomEvent["LocalEchoUpdated"] = "Room.localEchoUpdated";
  RoomEvent["Timeline"] = "Room.timeline";
  RoomEvent["TimelineReset"] = "Room.timelineReset";
  RoomEvent["TimelineRefresh"] = "Room.TimelineRefresh";
  RoomEvent["OldStateUpdated"] = "Room.OldStateUpdated";
  RoomEvent["CurrentStateUpdated"] = "Room.CurrentStateUpdated";
  RoomEvent["HistoryImportedWithinTimeline"] = "Room.historyImportedWithinTimeline";
  RoomEvent["UnreadNotifications"] = "Room.UnreadNotifications";
  return RoomEvent;
}({});
exports.RoomEvent = RoomEvent;
class Room extends _readReceipt.ReadReceipt {
  /**
   * Construct a new Room.
   *
   * <p>For a room, we store an ordered sequence of timelines, which may or may not
   * be continuous. Each timeline lists a series of events, as well as tracking
   * the room state at the start and the end of the timeline. It also tracks
   * forward and backward pagination tokens, as well as containing links to the
   * next timeline in the sequence.
   *
   * <p>There is one special timeline - the 'live' timeline, which represents the
   * timeline to which events are being added in real-time as they are received
   * from the /sync API. Note that you should not retain references to this
   * timeline - even if it is the current timeline right now, it may not remain
   * so if the server gives us a timeline gap in /sync.
   *
   * <p>In order that we can find events from their ids later, we also maintain a
   * map from event_id to timeline and index.
   *
   * @param roomId - Required. The ID of this room.
   * @param client - Required. The client, used to lazy load members.
   * @param myUserId - Required. The ID of the syncing user.
   * @param opts - Configuration options
   */
  constructor(roomId, client, myUserId, opts = {}) {
    super();
    // In some cases, we add listeners for every displayed Matrix event, so it's
    // common to have quite a few more than the default limit.
    this.roomId = roomId;
    this.client = client;
    this.myUserId = myUserId;
    this.opts = opts;
    _defineProperty(this, "reEmitter", void 0);
    _defineProperty(this, "txnToEvent", new Map());
    // Pending in-flight requests { string: MatrixEvent }
    _defineProperty(this, "notificationCounts", {});
    _defineProperty(this, "threadNotifications", new Map());
    _defineProperty(this, "cachedThreadReadReceipts", new Map());
    // Useful to know at what point the current user has started using threads in this room
    _defineProperty(this, "oldestThreadedReceiptTs", Infinity);
    /**
     * A record of the latest unthread receipts per user
     * This is useful in determining whether a user has read a thread or not
     */
    _defineProperty(this, "unthreadedReceipts", new Map());
    _defineProperty(this, "timelineSets", void 0);
    _defineProperty(this, "polls", new Map());
    /**
     * Empty array if the timeline sets have not been initialised. After initialisation:
     * 0: All threads
     * 1: Threads the current user has participated in
     */
    _defineProperty(this, "threadsTimelineSets", []);
    // any filtered timeline sets we're maintaining for this room
    _defineProperty(this, "filteredTimelineSets", {});
    // filter_id: timelineSet
    _defineProperty(this, "timelineNeedsRefresh", false);
    _defineProperty(this, "pendingEventList", void 0);
    // read by megolm via getter; boolean value - null indicates "use global value"
    _defineProperty(this, "blacklistUnverifiedDevices", void 0);
    _defineProperty(this, "selfMembership", void 0);
    _defineProperty(this, "summaryHeroes", null);
    // flags to stop logspam about missing m.room.create events
    _defineProperty(this, "getTypeWarning", false);
    _defineProperty(this, "getVersionWarning", false);
    _defineProperty(this, "membersPromise", void 0);
    // XXX: These should be read-only
    /**
     * The human-readable display name for this room.
     */
    _defineProperty(this, "name", void 0);
    /**
     * The un-homoglyphed name for this room.
     */
    _defineProperty(this, "normalizedName", void 0);
    /**
     * Dict of room tags; the keys are the tag name and the values
     * are any metadata associated with the tag - e.g. `{ "fav" : { order: 1 } }`
     */
    _defineProperty(this, "tags", {});
    // $tagName: { $metadata: $value }
    /**
     * accountData Dict of per-room account_data events; the keys are the
     * event type and the values are the events.
     */
    _defineProperty(this, "accountData", new Map());
    // $eventType: $event
    /**
     * The room summary.
     */
    _defineProperty(this, "summary", null);
    /**
     * The live event timeline for this room, with the oldest event at index 0.
     *
     * @deprecated Present for backwards compatibility.
     *             Use getLiveTimeline().getEvents() instead
     */
    _defineProperty(this, "timeline", void 0);
    /**
     * oldState The state of the room at the time of the oldest event in the live timeline.
     *
     * @deprecated Present for backwards compatibility.
     *             Use getLiveTimeline().getState(EventTimeline.BACKWARDS) instead
     */
    _defineProperty(this, "oldState", void 0);
    /**
     * currentState The state of the room at the time of the newest event in the timeline.
     *
     * @deprecated Present for backwards compatibility.
     *             Use getLiveTimeline().getState(EventTimeline.FORWARDS) instead.
     */
    _defineProperty(this, "currentState", void 0);
    _defineProperty(this, "relations", new _relationsContainer.RelationsContainer(this.client, this));
    /**
     * A collection of events known by the client
     * This is not a comprehensive list of the threads that exist in this room
     */
    _defineProperty(this, "threads", new Map());
    /**
     * @deprecated This value is unreliable. It may not contain the last thread.
     *             Use {@link Room.getLastThread} instead.
     */
    _defineProperty(this, "lastThread", void 0);
    /**
     * A mapping of eventId to all visibility changes to apply
     * to the event, by chronological order, as per
     * https://github.com/matrix-org/matrix-doc/pull/3531
     *
     * # Invariants
     *
     * - within each list, all events are classed by
     *   chronological order;
     * - all events are events such that
     *  `asVisibilityEvent()` returns a non-null `IVisibilityChange`;
     * - within each list with key `eventId`, all events
     *   are in relation to `eventId`.
     *
     * @experimental
     */
    _defineProperty(this, "visibilityEvents", new Map());
    _defineProperty(this, "threadTimelineSetsPromise", null);
    _defineProperty(this, "threadsReady", false);
    _defineProperty(this, "updateThreadRootEvents", (thread, toStartOfTimeline, recreateEvent) => {
      if (thread.length) {
        this.updateThreadRootEvent(this.threadsTimelineSets?.[0], thread, toStartOfTimeline, recreateEvent);
        if (thread.hasCurrentUserParticipated) {
          this.updateThreadRootEvent(this.threadsTimelineSets?.[1], thread, toStartOfTimeline, recreateEvent);
        }
      }
    });
    _defineProperty(this, "updateThreadRootEvent", (timelineSet, thread, toStartOfTimeline, recreateEvent) => {
      if (timelineSet && thread.rootEvent) {
        if (recreateEvent) {
          timelineSet.removeEvent(thread.id);
        }
        if (_thread.Thread.hasServerSideSupport) {
          timelineSet.addLiveEvent(thread.rootEvent, {
            duplicateStrategy: _eventTimelineSet.DuplicateStrategy.Replace,
            fromCache: false,
            roomState: this.currentState
          });
        } else {
          timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), {
            toStartOfTimeline
          });
        }
      }
    });
    _defineProperty(this, "applyRedaction", event => {
      if (event.isRedaction()) {
        const redactId = event.event.redacts;

        // if we know about this event, redact its contents now.
        const redactedEvent = redactId ? this.findEventById(redactId) : undefined;
        if (redactedEvent) {
          redactedEvent.makeRedacted(event);

          // If this is in the current state, replace it with the redacted version
          if (redactedEvent.isState()) {
            const currentStateEvent = this.currentState.getStateEvents(redactedEvent.getType(), redactedEvent.getStateKey());
            if (currentStateEvent?.getId() === redactedEvent.getId()) {
              this.currentState.setStateEvents([redactedEvent]);
            }
          }
          this.emit(RoomEvent.Redaction, event, this);

          // TODO: we stash user displaynames (among other things) in
          // RoomMember objects which are then attached to other events
          // (in the sender and target fields). We should get those
          // RoomMember objects to update themselves when the events that
          // they are based on are changed.

          // Remove any visibility change on this event.
          this.visibilityEvents.delete(redactId);

          // If this event is a visibility change event, remove it from the
          // list of visibility changes and update any event affected by it.
          if (redactedEvent.isVisibilityEvent()) {
            this.redactVisibilityChangeEvent(event);
          }
        }

        // FIXME: apply redactions to notification list

        // NB: We continue to add the redaction event to the timeline so
        // clients can say "so and so redacted an event" if they wish to. Also
        // this may be needed to trigger an update.
      }
    });
    this.setMaxListeners(100);
    this.reEmitter = new _ReEmitter.TypedReEmitter(this);
    opts.pendingEventOrdering = opts.pendingEventOrdering || _client.PendingEventOrdering.Chronological;
    this.name = roomId;
    this.normalizedName = roomId;

    // all our per-room timeline sets. the first one is the unfiltered ones;
    // the subsequent ones are the filtered ones in no particular order.
    this.timelineSets = [new _eventTimelineSet.EventTimelineSet(this, opts)];
    this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);
    this.fixUpLegacyTimelineFields();
    if (this.opts.pendingEventOrdering === _client.PendingEventOrdering.Detached) {
      this.pendingEventList = [];
      this.client.store.getPendingEvents(this.roomId).then(events => {
        const mapper = this.client.getEventMapper({
          toDevice: false,
          decrypt: false
        });
        events.forEach(async serializedEvent => {
          const event = mapper(serializedEvent);
          await client.decryptEventIfNeeded(event);
          event.setStatus(_eventStatus.EventStatus.NOT_SENT);
          this.addPendingEvent(event, event.getTxnId());
        });
      });
    }

    // awaited by getEncryptionTargetMembers while room members are loading
    if (!this.opts.lazyLoadMembers) {
      this.membersPromise = Promise.resolve(false);
    } else {
      this.membersPromise = undefined;
    }
  }
  async createThreadsTimelineSets() {
    if (this.threadTimelineSetsPromise) {
      return this.threadTimelineSetsPromise;
    }
    if (this.client?.supportsThreads()) {
      try {
        this.threadTimelineSetsPromise = Promise.all([this.createThreadTimelineSet(), this.createThreadTimelineSet(_thread.ThreadFilterType.My)]);
        const timelineSets = await this.threadTimelineSetsPromise;
        this.threadsTimelineSets[0] = timelineSets[0];
        this.threadsTimelineSets[1] = timelineSets[1];
        return timelineSets;
      } catch (e) {
        this.threadTimelineSetsPromise = null;
        return null;
      }
    }
    return null;
  }

  /**
   * Bulk decrypt critical events in a room
   *
   * Critical events represents the minimal set of events to decrypt
   * for a typical UI to function properly
   *
   * - Last event of every room (to generate likely message preview)
   * - All events up to the read receipt (to calculate an accurate notification count)
   *
   * @returns Signals when all events have been decrypted
   */
  async decryptCriticalEvents() {
    if (!this.client.isCryptoEnabled()) return;
    const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId(), true);
    const events = this.getLiveTimeline().getEvents();
    const readReceiptTimelineIndex = events.findIndex(matrixEvent => {
      return matrixEvent.event.event_id === readReceiptEventId;
    });
    const decryptionPromises = events.slice(readReceiptTimelineIndex).reverse().map(event => this.client.decryptEventIfNeeded(event, {
      isRetry: true
    }));
    await Promise.allSettled(decryptionPromises);
  }

  /**
   * Bulk decrypt events in a room
   *
   * @returns Signals when all events have been decrypted
   */
  async decryptAllEvents() {
    if (!this.client.isCryptoEnabled()) return;
    const decryptionPromises = this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0) // copy before reversing
    .reverse().map(event => this.client.decryptEventIfNeeded(event, {
      isRetry: true
    }));
    await Promise.allSettled(decryptionPromises);
  }

  /**
   * Gets the creator of the room
   * @returns The creator of the room, or null if it could not be determined
   */
  getCreator() {
    const createEvent = this.currentState.getStateEvents(_event2.EventType.RoomCreate, "");
    return createEvent?.getContent()["creator"] ?? null;
  }

  /**
   * Gets the version of the room
   * @returns The version of the room, or null if it could not be determined
   */
  getVersion() {
    const createEvent = this.currentState.getStateEvents(_event2.EventType.RoomCreate, "");
    if (!createEvent) {
      if (!this.getVersionWarning) {
        _logger.logger.warn("[getVersion] Room " + this.roomId + " does not have an m.room.create event");
        this.getVersionWarning = true;
      }
      return "1";
    }
    return createEvent.getContent()["room_version"] ?? "1";
  }

  /**
   * Determines whether this room needs to be upgraded to a new version
   * @returns What version the room should be upgraded to, or null if
   *     the room does not require upgrading at this time.
   * @deprecated Use #getRecommendedVersion() instead
   */
  shouldUpgradeToVersion() {
    // TODO: Remove this function.
    // This makes assumptions about which versions are safe, and can easily
    // be wrong. Instead, people are encouraged to use getRecommendedVersion
    // which determines a safer value. This function doesn't use that function
    // because this is not async-capable, and to avoid breaking the contract
    // we're deprecating this.

    if (!SAFE_ROOM_VERSIONS.includes(this.getVersion())) {
      return KNOWN_SAFE_ROOM_VERSION;
    }
    return null;
  }

  /**
   * Determines the recommended room version for the room. This returns an
   * object with 3 properties: `version` as the new version the
   * room should be upgraded to (may be the same as the current version);
   * `needsUpgrade` to indicate if the room actually can be
   * upgraded (ie: does the current version not match?); and `urgent`
   * to indicate if the new version patches a vulnerability in a previous
   * version.
   * @returns
   * Resolves to the version the room should be upgraded to.
   */
  async getRecommendedVersion() {
    const capabilities = await this.client.getCapabilities();
    let versionCap = capabilities["m.room_versions"];
    if (!versionCap) {
      versionCap = {
        default: KNOWN_SAFE_ROOM_VERSION,
        available: {}
      };
      for (const safeVer of SAFE_ROOM_VERSIONS) {
        versionCap.available[safeVer] = _client.RoomVersionStability.Stable;
      }
    }
    let result = this.checkVersionAgainstCapability(versionCap);
    if (result.urgent && result.needsUpgrade) {
      // Something doesn't feel right: we shouldn't need to update
      // because the version we're on should be in the protocol's
      // namespace. This usually means that the server was updated
      // before the client was, making us think the newest possible
      // room version is not stable. As a solution, we'll refresh
      // the capability we're using to determine this.
      _logger.logger.warn("Refreshing room version capability because the server looks " + "to be supporting a newer room version we don't know about.");
      const caps = await this.client.getCapabilities(true);
      versionCap = caps["m.room_versions"];
      if (!versionCap) {
        _logger.logger.warn("No room version capability - assuming upgrade required.");
        return result;
      } else {
        result = this.checkVersionAgainstCapability(versionCap);
      }
    }
    return result;
  }
  checkVersionAgainstCapability(versionCap) {
    const currentVersion = this.getVersion();
    _logger.logger.log(`[${this.roomId}] Current version: ${currentVersion}`);
    _logger.logger.log(`[${this.roomId}] Version capability: `, versionCap);
    const result = {
      version: currentVersion,
      needsUpgrade: false,
      urgent: false
    };

    // If the room is on the default version then nothing needs to change
    if (currentVersion === versionCap.default) return result;
    const stableVersions = Object.keys(versionCap.available).filter(v => versionCap.available[v] === "stable");

    // Check if the room is on an unstable version. We determine urgency based
    // off the version being in the Matrix spec namespace or not (if the version
    // is in the current namespace and unstable, the room is probably vulnerable).
    if (!stableVersions.includes(currentVersion)) {
      result.version = versionCap.default;
      result.needsUpgrade = true;
      result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);
      if (result.urgent) {
        _logger.logger.warn(`URGENT upgrade required on ${this.roomId}`);
      } else {
        _logger.logger.warn(`Non-urgent upgrade required on ${this.roomId}`);
      }
      return result;
    }

    // The room is on a stable, but non-default, version by this point.
    // No upgrade needed.
    return result;
  }

  /**
   * Determines whether the given user is permitted to perform a room upgrade
   * @param userId - The ID of the user to test against
   * @returns True if the given user is permitted to upgrade the room
   */
  userMayUpgradeRoom(userId) {
    return this.currentState.maySendStateEvent(_event2.EventType.RoomTombstone, userId);
  }

  /**
   * Get the list of pending sent events for this room
   *
   * @returns A list of the sent events
   * waiting for remote echo.
   *
   * @throws If `opts.pendingEventOrdering` was not 'detached'
   */
  getPendingEvents() {
    if (!this.pendingEventList) {
      throw new Error("Cannot call getPendingEvents with pendingEventOrdering == " + this.opts.pendingEventOrdering);
    }
    return this.pendingEventList;
  }

  /**
   * Removes a pending event for this room
   *
   * @returns True if an element was removed.
   */
  removePendingEvent(eventId) {
    if (!this.pendingEventList) {
      throw new Error("Cannot call removePendingEvent with pendingEventOrdering == " + this.opts.pendingEventOrdering);
    }
    const removed = (0, _utils.removeElement)(this.pendingEventList, function (ev) {
      return ev.getId() == eventId;
    }, false);
    this.savePendingEvents();
    return removed;
  }

  /**
   * Check whether the pending event list contains a given event by ID.
   * If pending event ordering is not "detached" then this returns false.
   *
   * @param eventId - The event ID to check for.
   */
  hasPendingEvent(eventId) {
    return this.pendingEventList?.some(event => event.getId() === eventId) ?? false;
  }

  /**
   * Get a specific event from the pending event list, if configured, null otherwise.
   *
   * @param eventId - The event ID to check for.
   */
  getPendingEvent(eventId) {
    return this.pendingEventList?.find(event => event.getId() === eventId) ?? null;
  }

  /**
   * Get the live unfiltered timeline for this room.
   *
   * @returns live timeline
   */
  getLiveTimeline() {
    return this.getUnfilteredTimelineSet().getLiveTimeline();
  }

  /**
   * Get the timestamp of the last message in the room
   *
   * @returns the timestamp of the last message in the room
   */
  getLastActiveTimestamp() {
    const timeline = this.getLiveTimeline();
    const events = timeline.getEvents();
    if (events.length) {
      const lastEvent = events[events.length - 1];
      return lastEvent.getTs();
    } else {
      return Number.MIN_SAFE_INTEGER;
    }
  }

  /**
   * Returns the last live event of this room.
   * "last" means latest timestamp.
   * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.
   * Unfortunately, this information is currently not available in the client.
   * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.
   * "live of this room" means from all live timelines: the room and the threads.
   *
   * @returns MatrixEvent if there is a last event; else undefined.
   */
  getLastLiveEvent() {
    const roomEvents = this.getLiveTimeline().getEvents();
    const lastRoomEvent = roomEvents[roomEvents.length - 1];
    const lastThread = this.getLastThread();
    if (!lastThread) return lastRoomEvent;
    const lastThreadEvent = lastThread.events[lastThread.events.length - 1];
    return (lastRoomEvent?.getTs() ?? 0) > (lastThreadEvent?.getTs() ?? 0) ? lastRoomEvent : lastThreadEvent;
  }

  /**
   * Returns the last thread of this room.
   * "last" means latest timestamp of the last thread event.
   * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.
   * Unfortunately, this information is currently not available in the client.
   * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.
   *
   * @returns the thread with the most recent event in its live time line. undefined if there is no thread.
   */
  getLastThread() {
    return this.getThreads().reduce((lastThread, thread) => {
      if (!lastThread) return thread;
      const threadEvent = thread.events[thread.events.length - 1];
      const lastThreadEvent = lastThread.events[lastThread.events.length - 1];
      if ((threadEvent?.getTs() ?? 0) >= (lastThreadEvent?.getTs() ?? 0)) {
        // Last message of current thread is newer → new last thread.
        // Equal also means newer, because it was added to the thread map later.
        return thread;
      }
      return lastThread;
    }, undefined);
  }

  /**
   * @returns the membership type (join | leave | invite) for the logged in user
   */
  getMyMembership() {
    return this.selfMembership ?? "leave";
  }

  /**
   * If this room is a DM we're invited to,
   * try to find out who invited us
   * @returns user id of the inviter
   */
  getDMInviter() {
    const me = this.getMember(this.myUserId);
    if (me) {
      return me.getDMInviter();
    }
    if (this.selfMembership === "invite") {
      // fall back to summary information
      const memberCount = this.getInvitedAndJoinedMemberCount();
      if (memberCount === 2) {
        return this.summaryHeroes?.[0];
      }
    }
  }

  /**
   * Assuming this room is a DM room, tries to guess with which user.
   * @returns user id of the other member (could be syncing user)
   */
  guessDMUserId() {
    const me = this.getMember(this.myUserId);
    if (me) {
      const inviterId = me.getDMInviter();
      if (inviterId) {
        return inviterId;
      }
    }
    // Remember, we're assuming this room is a DM, so returning the first member we find should be fine
    if (Array.isArray(this.summaryHeroes) && this.summaryHeroes.length) {
      return this.summaryHeroes[0];
    }
    const members = this.currentState.getMembers();
    const anyMember = members.find(m => m.userId !== this.myUserId);
    if (anyMember) {
      return anyMember.userId;
    }
    // it really seems like I'm the only user in the room
    // so I probably created a room with just me in it
    // and marked it as a DM. Ok then
    return this.myUserId;
  }
  getAvatarFallbackMember() {
    const memberCount = this.getInvitedAndJoinedMemberCount();
    if (memberCount > 2) {
      return;
    }
    const hasHeroes = Array.isArray(this.summaryHeroes) && this.summaryHeroes.length;
    if (hasHeroes) {
      const availableMember = this.summaryHeroes.map(userId => {
        return this.getMember(userId);
      }).find(member => !!member);
      if (availableMember) {
        return availableMember;
      }
    }
    const members = this.currentState.getMembers();
    // could be different than memberCount
    // as this includes left members
    if (members.length <= 2) {
      const availableMember = members.find(m => {
        return m.userId !== this.myUserId;
      });
      if (availableMember) {
        return availableMember;
      }
    }
    // if all else fails, try falling back to a user,
    // and create a one-off member for it
    if (hasHeroes) {
      const availableUser = this.summaryHeroes.map(userId => {
        return this.client.getUser(userId);
      }).find(user => !!user);
      if (availableUser) {
        const member = new _roomMember.RoomMember(this.roomId, availableUser.userId);
        member.user = availableUser;
        return member;
      }
    }
  }

  /**
   * Sets the membership this room was received as during sync
   * @param membership - join | leave | invite
   */
  updateMyMembership(membership) {
    const prevMembership = this.selfMembership;
    this.selfMembership = membership;
    if (prevMembership !== membership) {
      if (membership === "leave") {
        this.cleanupAfterLeaving();
      }
      this.emit(RoomEvent.MyMembership, this, membership, prevMembership);
    }
  }
  async loadMembersFromServer() {
    const lastSyncToken = this.client.store.getSyncToken();
    const response = await this.client.members(this.roomId, undefined, "leave", lastSyncToken ?? undefined);
    return response.chunk;
  }
  async loadMembers() {
    // were the members loaded from the server?
    let fromServer = false;
    let rawMembersEvents = await this.client.store.getOutOfBandMembers(this.roomId);
    // If the room is encrypted, we always fetch members from the server at
    // least once, in case the latest state wasn't persisted properly. Note
    // that this function is only called once (unless loading the members
    // fails), since loadMembersIfNeeded always returns this.membersPromise
    // if set, which will be the result of the first (successful) call.
    if (rawMembersEvents === null || this.client.isCryptoEnabled() && this.client.isRoomEncrypted(this.roomId)) {
      fromServer = true;
      rawMembersEvents = await this.loadMembersFromServer();
      _logger.logger.log(`LL: got ${rawMembersEvents.length} ` + `members from server for room ${this.roomId}`);
    }
    const memberEvents = rawMembersEvents.filter(_utils.noUnsafeEventProps).map(this.client.getEventMapper());
    return {
      memberEvents,
      fromServer
    };
  }

  /**
   * Check if loading of out-of-band-members has completed
   *
   * @returns true if the full membership list of this room has been loaded (including if lazy-loading is disabled).
   *    False if the load is not started or is in progress.
   */
  membersLoaded() {
    if (!this.opts.lazyLoadMembers) {
      return true;
    }
    return this.currentState.outOfBandMembersReady();
  }

  /**
   * Preloads the member list in case lazy loading
   * of memberships is in use. Can be called multiple times,
   * it will only preload once.
   * @returns when preloading is done and
   * accessing the members on the room will take
   * all members in the room into account
   */
  loadMembersIfNeeded() {
    if (this.membersPromise) {
      return this.membersPromise;
    }

    // mark the state so that incoming messages while
    // the request is in flight get marked as superseding
    // the OOB members
    this.currentState.markOutOfBandMembersStarted();
    const inMemoryUpdate = this.loadMembers().then(result => {
      this.currentState.setOutOfBandMembers(result.memberEvents);
      return result.fromServer;
    }).catch(err => {
      // allow retries on fail
      this.membersPromise = undefined;
      this.currentState.markOutOfBandMembersFailed();
      throw err;
    });
    // update members in storage, but don't wait for it
    inMemoryUpdate.then(fromServer => {
      if (fromServer) {
        const oobMembers = this.currentState.getMembers().filter(m => m.isOutOfBand()).map(m => m.events.member?.event);
        _logger.logger.log(`LL: telling store to write ${oobMembers.length}` + ` members for room ${this.roomId}`);
        const store = this.client.store;
        return store.setOutOfBandMembers(this.roomId, oobMembers)
        // swallow any IDB error as we don't want to fail
        // because of this
        .catch(err => {
          _logger.logger.log("LL: storing OOB room members failed, oh well", err);
        });
      }
    }).catch(err => {
      // as this is not awaited anywhere,
      // at least show the error in the console
      _logger.logger.error(err);
    });
    this.membersPromise = inMemoryUpdate;
    return this.membersPromise;
  }

  /**
   * Removes the lazily loaded members from storage if needed
   */
  async clearLoadedMembersIfNeeded() {
    if (this.opts.lazyLoadMembers && this.membersPromise) {
      await this.loadMembersIfNeeded();
      await this.client.store.clearOutOfBandMembers(this.roomId);
      this.currentState.clearOutOfBandMembers();
      this.membersPromise = undefined;
    }
  }

  /**
   * called when sync receives this room in the leave section
   * to do cleanup after leaving a room. Possibly called multiple times.
   */
  cleanupAfterLeaving() {
    this.clearLoadedMembersIfNeeded().catch(err => {
      _logger.logger.error(`error after clearing loaded members from ` + `room ${this.roomId} after leaving`);
      _logger.logger.log(err);
    });
  }

  /**
   * Empty out the current live timeline and re-request it. This is used when
   * historical messages are imported into the room via MSC2716 `/batch_send`
   * because the client may already have that section of the timeline loaded.
   * We need to force the client to throw away their current timeline so that
   * when they back paginate over the area again with the historical messages
   * in between, it grabs the newly imported messages. We can listen for
   * `UNSTABLE_MSC2716_MARKER`, in order to tell when historical messages are ready
   * to be discovered in the room and the timeline needs a refresh. The SDK
   * emits a `RoomEvent.HistoryImportedWithinTimeline` event when we detect a
   * valid marker and can check the needs refresh status via
   * `room.getTimelineNeedsRefresh()`.
   */
  async refreshLiveTimeline() {
    const liveTimelineBefore = this.getLiveTimeline();
    const forwardPaginationToken = liveTimelineBefore.getPaginationToken(_eventTimeline.EventTimeline.FORWARDS);
    const backwardPaginationToken = liveTimelineBefore.getPaginationToken(_eventTimeline.EventTimeline.BACKWARDS);
    const eventsBefore = liveTimelineBefore.getEvents();
    const mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];
    _logger.logger.log(`[refreshLiveTimeline for ${this.roomId}] at ` + `mostRecentEventInTimeline=${mostRecentEventInTimeline && mostRecentEventInTimeline.getId()} ` + `liveTimelineBefore=${liveTimelineBefore.toString()} ` + `forwardPaginationToken=${forwardPaginationToken} ` + `backwardPaginationToken=${backwardPaginationToken}`);

    // Get the main TimelineSet
    const timelineSet = this.getUnfilteredTimelineSet();
    let newTimeline;
    // If there isn't any event in the timeline, let's go fetch the latest
    // event and construct a timeline from it.
    //
    // This should only really happen if the user ran into an error
    // with refreshing the timeline before which left them in a blank
    // timeline from `resetLiveTimeline`.
    if (!mostRecentEventInTimeline) {
      newTimeline = await this.client.getLatestTimeline(timelineSet);
    } else {
      // Empty out all of `this.timelineSets`. But we also need to keep the
      // same `timelineSet` references around so the React code updates
      // properly and doesn't ignore the room events we emit because it checks
      // that the `timelineSet` references are the same. We need the
      // `timelineSet` empty so that the `client.getEventTimeline(...)` call
      // later, will call `/context` and create a new timeline instead of
      // returning the same one.
      this.resetLiveTimeline(null, null);

      // Make the UI timeline show the new blank live timeline we just
      // reset so that if the network fails below it's showing the
      // accurate state of what we're working with instead of the
      // disconnected one in the TimelineWindow which is just hanging
      // around by reference.
      this.emit(RoomEvent.TimelineRefresh, this, timelineSet);

      // Use `client.getEventTimeline(...)` to construct a new timeline from a
      // `/context` response state and events for the most recent event before
      // we reset everything. The `timelineSet` we pass in needs to be empty
      // in order for this function to call `/context` and generate a new
      // timeline.
      newTimeline = await this.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId());
    }

    // If a racing `/sync` beat us to creating a new timeline, use that
    // instead because it's the latest in the room and any new messages in
    // the scrollback will include the history.
    const liveTimeline = timelineSet.getLiveTimeline();
    if (!liveTimeline || liveTimeline.getPaginationToken(_eventTimeline.Direction.Forward) === null && liveTimeline.getPaginationToken(_eventTimeline.Direction.Backward) === null && liveTimeline.getEvents().length === 0) {
      _logger.logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`);
      // Set the pagination token back to the live sync token (`null`) instead
      // of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`)
      // so that it matches the next response from `/sync` and we can properly
      // continue the timeline.
      newTimeline.setPaginationToken(forwardPaginationToken, _eventTimeline.EventTimeline.FORWARDS);

      // Set our new fresh timeline as the live timeline to continue syncing
      // forwards and back paginating from.
      timelineSet.setLiveTimeline(newTimeline);
      // Fixup `this.oldstate` so that `scrollback` has the pagination tokens
      // available
      this.fixUpLegacyTimelineFields();
    } else {
      _logger.logger.log(`[refreshLiveTimeline for ${this.roomId}] \`/sync\` or some other request beat us to creating a new ` + `live timeline after we reset it. We'll use that instead since any events in the scrollback from ` + `this timeline will include the history.`);
    }

    // The timeline has now been refreshed ✅
    this.setTimelineNeedsRefresh(false);

    // Emit an event which clients can react to and re-load the timeline
    // from the SDK
    this.emit(RoomEvent.TimelineRefresh, this, timelineSet);
  }

  /**
   * Reset the live timeline of all timelineSets, and start new ones.
   *
   * <p>This is used when /sync returns a 'limited' timeline.
   *
   * @param backPaginationToken -   token for back-paginating the new timeline
   * @param forwardPaginationToken - token for forward-paginating the old live timeline,
   * if absent or null, all timelines are reset, removing old ones (including the previous live
   * timeline which would otherwise be unable to paginate forwards without this token).
   * Removing just the old live timeline whilst preserving previous ones is not supported.
   */
  resetLiveTimeline(backPaginationToken, forwardPaginationToken) {
    for (const timelineSet of this.timelineSets) {
      timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);
    }
    for (const thread of this.threads.values()) {
      thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken);
    }
    this.fixUpLegacyTimelineFields();
  }

  /**
   * Fix up this.timeline, this.oldState and this.currentState
   *
   * @internal
   */
  fixUpLegacyTimelineFields() {
    const previousOldState = this.oldState;
    const previousCurrentState = this.currentState;

    // maintain this.timeline as a reference to the live timeline,
    // and this.oldState and this.currentState as references to the
    // state at the start and end of that timeline. These are more
    // for backwards-compatibility than anything else.
    this.timeline = this.getLiveTimeline().getEvents();
    this.oldState = this.getLiveTimeline().getState(_eventTimeline.EventTimeline.BACKWARDS);
    this.currentState = this.getLiveTimeline().getState(_eventTimeline.EventTimeline.FORWARDS);

    // Let people know to register new listeners for the new state
    // references. The reference won't necessarily change every time so only
    // emit when we see a change.
    if (previousOldState !== this.oldState) {
      this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);
    }
    if (previousCurrentState !== this.currentState) {
      this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);

      // Re-emit various events on the current room state
      // TODO: If currentState really only exists for backwards
      // compatibility, shouldn't we be doing this some other way?
      this.reEmitter.stopReEmitting(previousCurrentState, [_roomState.RoomStateEvent.Events, _roomState.RoomStateEvent.Members, _roomState.RoomStateEvent.NewMember, _roomState.RoomStateEvent.Update, _roomState.RoomStateEvent.Marker, _beacon.BeaconEvent.New, _beacon.BeaconEvent.Update, _beacon.BeaconEvent.Destroy, _beacon.BeaconEvent.LivenessChange]);
      this.reEmitter.reEmit(this.currentState, [_roomState.RoomStateEvent.Events, _roomState.RoomStateEvent.Members, _roomState.RoomStateEvent.NewMember, _roomState.RoomStateEvent.Update, _roomState.RoomStateEvent.Marker, _beacon.BeaconEvent.New, _beacon.BeaconEvent.Update, _beacon.BeaconEvent.Destroy, _beacon.BeaconEvent.LivenessChange]);
    }
  }

  /**
   * Returns whether there are any devices in the room that are unverified
   *
   * Note: Callers should first check if crypto is enabled on this device. If it is
   * disabled, then we aren't tracking room devices at all, so we can't answer this, and an
   * error will be thrown.
   *
   * @returns the result
   */
  async hasUnverifiedDevices() {
    if (!this.client.isRoomEncrypted(this.roomId)) {
      return false;
    }
    const e2eMembers = await this.getEncryptionTargetMembers();
    for (const member of e2eMembers) {
      const devices = this.client.getStoredDevicesForUser(member.userId);
      if (devices.some(device => device.isUnverified())) {
        return true;
      }
    }
    return false;
  }

  /**
   * Return the timeline sets for this room.
   * @returns array of timeline sets for this room
   */
  getTimelineSets() {
    return this.timelineSets;
  }

  /**
   * Helper to return the main unfiltered timeline set for this room
   * @returns room's unfiltered timeline set
   */
  getUnfilteredTimelineSet() {
    return this.timelineSets[0];
  }

  /**
   * Get the timeline which contains the given event from the unfiltered set, if any
   *
   * @param eventId -  event ID to look for
   * @returns timeline containing
   * the given event, or null if unknown
   */
  getTimelineForEvent(eventId) {
    const event = this.findEventById(eventId);
    const thread = this.findThreadForEvent(event);
    if (thread) {
      return thread.timelineSet.getTimelineForEvent(eventId);
    } else {
      return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);
    }
  }

  /**
   * Add a new timeline to this room's unfiltered timeline set
   *
   * @returns newly-created timeline
   */
  addTimeline() {
    return this.getUnfilteredTimelineSet().addTimeline();
  }

  /**
   * Whether the timeline needs to be refreshed in order to pull in new
   * historical messages that were imported.
   * @param value - The value to set
   */
  setTimelineNeedsRefresh(value) {
    this.timelineNeedsRefresh = value;
  }

  /**
   * Whether the timeline needs to be refreshed in order to pull in new
   * historical messages that were imported.
   * @returns .
   */
  getTimelineNeedsRefresh() {
    return this.timelineNeedsRefresh;
  }

  /**
   * Get an event which is stored in our unfiltered timeline set, or in a thread
   *
   * @param eventId - event ID to look for
   * @returns the given event, or undefined if unknown
   */
  findEventById(eventId) {
    let event = this.getUnfilteredTimelineSet().findEventById(eventId);
    if (!event) {
      const threads = this.getThreads();
      for (let i = 0; i < threads.length; i++) {
        const thread = threads[i];
        event = thread.findEventById(eventId);
        if (event) {
          return event;
        }
      }
    }
    return event;
  }

  /**
   * Get one of the notification counts for this room
   * @param type - The type of notification count to get. default: 'total'
   * @returns The notification count, or undefined if there is no count
   *                  for this type.
   */
  getUnreadNotificationCount(type = NotificationCountType.Total) {
    let count = this.getRoomUnreadNotificationCount(type);
    for (const threadNotification of this.threadNotifications.values()) {
      count += threadNotification[type] ?? 0;
    }
    return count;
  }

  /**
   * Get the notification for the event context (room or thread timeline)
   */
  getUnreadCountForEventContext(type = NotificationCountType.Total, event) {
    const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;
    return (isThreadEvent ? this.getThreadUnreadNotificationCount(event.threadRootId, type) : this.getRoomUnreadNotificationCount(type)) ?? 0;
  }

  /**
   * Get one of the notification counts for this room
   * @param type - The type of notification count to get. default: 'total'
   * @returns The notification count, or undefined if there is no count
   *                  for this type.
   */
  getRoomUnreadNotificationCount(type = NotificationCountType.Total) {
    return this.notificationCounts[type] ?? 0;
  }

  /**
   * Get one of the notification counts for a thread
   * @param threadId - the root event ID
   * @param type - The type of notification count to get. default: 'total'
   * @returns The notification count, or undefined if there is no count
   *          for this type.
   */
  getThreadUnreadNotificationCount(threadId, type = NotificationCountType.Total) {
    return this.threadNotifications.get(threadId)?.[type] ?? 0;
  }

  /**
   * Checks if the current room has unread thread notifications
   * @returns
   */
  hasThreadUnreadNotification() {
    for (const notification of this.threadNotifications.values()) {
      if ((notification.highlight ?? 0) > 0 || (notification.total ?? 0) > 0) {
        return true;
      }
    }
    return false;
  }

  /**
   * Swet one of the notification count for a thread
   * @param threadId - the root event ID
   * @param type - The type of notification count to get. default: 'total'
   * @returns
   */
  setThreadUnreadNotificationCount(threadId, type, count) {
    const notification = _objectSpread({
      highlight: this.threadNotifications.get(threadId)?.highlight,
      total: this.threadNotifications.get(threadId)?.total
    }, {
      [type]: count
    });
    this.threadNotifications.set(threadId, notification);
    this.emit(RoomEvent.UnreadNotifications, notification, threadId);
  }

  /**
   * @returns the notification count type for all the threads in the room
   */
  get threadsAggregateNotificationType() {
    let type = null;
    for (const threadNotification of this.threadNotifications.values()) {
      if ((threadNotification.highlight ?? 0) > 0) {
        return NotificationCountType.Highlight;
      } else if ((threadNotification.total ?? 0) > 0 && !type) {
        type = NotificationCountType.Total;
      }
    }
    return type;
  }

  /**
   * Resets the thread notifications for this room
   */
  resetThreadUnreadNotificationCount(notificationsToKeep) {
    if (notificationsToKeep) {
      for (const [threadId] of this.threadNotifications) {
        if (!notificationsToKeep.includes(threadId)) {
          this.threadNotifications.delete(threadId);
        }
      }
    } else {
      this.threadNotifications.clear();
    }
    this.emit(RoomEvent.UnreadNotifications);
  }

  /**
   * Set one of the notification counts for this room
   * @param type - The type of notification count to set.
   * @param count - The new count
   */
  setUnreadNotificationCount(type, count) {
    this.notificationCounts[type] = count;
    this.emit(RoomEvent.UnreadNotifications, this.notificationCounts);
  }
  setUnread(type, count) {
    return this.setUnreadNotificationCount(type, count);
  }
  setSummary(summary) {
    const heroes = summary["m.heroes"];
    const joinedCount = summary["m.joined_member_count"];
    const invitedCount = summary["m.invited_member_count"];
    if (Number.isInteger(joinedCount)) {
      this.currentState.setJoinedMemberCount(joinedCount);
    }
    if (Number.isInteger(invitedCount)) {
      this.currentState.setInvitedMemberCount(invitedCount);
    }
    if (Array.isArray(heroes)) {
      // be cautious about trusting server values,
      // and make sure heroes doesn't contain our own id
      // just to be sure
      this.summaryHeroes = heroes.filter(userId => {
        return userId !== this.myUserId;
      });
    }
  }

  /**
   * Whether to send encrypted messages to devices within this room.
   * @param value - true to blacklist unverified devices, null
   * to use the global value for this room.
   */
  setBlacklistUnverifiedDevices(value) {
    this.blacklistUnverifiedDevices = value;
  }

  /**
   * Whether to send encrypted messages to devices within this room.
   * @returns true if blacklisting unverified devices, null
   * if the global value should be used for this room.
   */
  getBlacklistUnverifiedDevices() {
    if (this.blacklistUnverifiedDevices === undefined) return null;
    return this.blacklistUnverifiedDevices;
  }

  /**
   * Get the avatar URL for a room if one was set.
   * @param baseUrl - The homeserver base URL. See
   * {@link MatrixClient#getHomeserverUrl}.
   * @param width - The desired width of the thumbnail.
   * @param height - The desired height of the thumbnail.
   * @param resizeMethod - The thumbnail resize method to use, either
   * "crop" or "scale".
   * @param allowDefault - True to allow an identicon for this room if an
   * avatar URL wasn't explicitly set. Default: true. (Deprecated)
   * @returns the avatar URL or null.
   */
  getAvatarUrl(baseUrl, width, height, resizeMethod, allowDefault = true) {
    const roomAvatarEvent = this.currentState.getStateEvents(_event2.EventType.RoomAvatar, "");
    if (!roomAvatarEvent && !allowDefault) {
      return null;
    }
    const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;
    if (mainUrl) {
      return (0, _contentRepo.getHttpUriForMxc)(baseUrl, mainUrl, width, height, resizeMethod);
    }
    return null;
  }

  /**
   * Get the mxc avatar url for the room, if one was set.
   * @returns the mxc avatar url or falsy
   */
  getMxcAvatarUrl() {
    return this.currentState.getStateEvents(_event2.EventType.RoomAvatar, "")?.getContent()?.url || null;
  }

  /**
   * Get this room's canonical alias
   * The alias returned by this function may not necessarily
   * still point to this room.
   * @returns The room's canonical alias, or null if there is none
   */
  getCanonicalAlias() {
    const canonicalAlias = this.currentState.getStateEvents(_event2.EventType.RoomCanonicalAlias, "");
    if (canonicalAlias) {
      return canonicalAlias.getContent().alias || null;
    }
    return null;
  }

  /**
   * Get this room's alternative aliases
   * @returns The room's alternative aliases, or an empty array
   */
  getAltAliases() {
    const canonicalAlias = this.currentState.getStateEvents(_event2.EventType.RoomCanonicalAlias, "");
    if (canonicalAlias) {
      return canonicalAlias.getContent().alt_aliases || [];
    }
    return [];
  }

  /**
   * Add events to a timeline
   *
   * <p>Will fire "Room.timeline" for each event added.
   *
   * @param events - A list of events to add.
   *
   * @param toStartOfTimeline -   True to add these events to the start
   * (oldest) instead of the end (newest) of the timeline. If true, the oldest
   * event will be the <b>last</b> element of 'events'.
   *
   * @param timeline -   timeline to
   *    add events to.
   *
   * @param paginationToken -   token for the next batch of events
   *
   * @remarks
   * Fires {@link RoomEvent.Timeline}
   */
  addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken) {
    timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken);
  }

  /**
   * Get the instance of the thread associated with the current event
   * @param eventId - the ID of the current event
   * @returns a thread instance if known
   */
  getThread(eventId) {
    return this.threads.get(eventId) ?? null;
  }

  /**
   * Get all the known threads in the room
   */
  getThreads() {
    return Array.from(this.threads.values());
  }

  /**
   * Get a member from the current room state.
   * @param userId - The user ID of the member.
   * @returns The member or `null`.
   */
  getMember(userId) {
    return this.currentState.getMember(userId);
  }

  /**
   * Get all currently loaded members from the current
   * room state.
   * @returns Room members
   */
  getMembers() {
    return this.currentState.getMembers();
  }

  /**
   * Get a list of members whose membership state is "join".
   * @returns A list of currently joined members.
   */
  getJoinedMembers() {
    return this.getMembersWithMembership("join");
  }

  /**
   * Returns the number of joined members in this room
   * This method caches the result.
   * This is a wrapper around the method of the same name in roomState, returning
   * its result for the room's current state.
   * @returns The number of members in this room whose membership is 'join'
   */
  getJoinedMemberCount() {
    return this.currentState.getJoinedMemberCount();
  }

  /**
   * Returns the number of invited members in this room
   * @returns The number of members in this room whose membership is 'invite'
   */
  getInvitedMemberCount() {
    return this.currentState.getInvitedMemberCount();
  }

  /**
   * Returns the number of invited + joined members in this room
   * @returns The number of members in this room whose membership is 'invite' or 'join'
   */
  getInvitedAndJoinedMemberCount() {
    return this.getInvitedMemberCount() + this.getJoinedMemberCount();
  }

  /**
   * Get a list of members with given membership state.
   * @param membership - The membership state.
   * @returns A list of members with the given membership state.
   */
  getMembersWithMembership(membership) {
    return this.currentState.getMembers().filter(function (m) {
      return m.membership === membership;
    });
  }

  /**
   * Get a list of members we should be encrypting for in this room
   * @returns A list of members who
   * we should encrypt messages for in this room.
   */
  async getEncryptionTargetMembers() {
    await this.loadMembersIfNeeded();
    let members = this.getMembersWithMembership("join");
    if (this.shouldEncryptForInvitedMembers()) {
      members = members.concat(this.getMembersWithMembership("invite"));
    }
    return members;
  }

  /**
   * Determine whether we should encrypt messages for invited users in this room
   * @returns if we should encrypt messages for invited users
   */
  shouldEncryptForInvitedMembers() {
    const ev = this.currentState.getStateEvents(_event2.EventType.RoomHistoryVisibility, "");
    return ev?.getContent()?.history_visibility !== "joined";
  }

  /**
   * Get the default room name (i.e. what a given user would see if the
   * room had no m.room.name)
   * @param userId - The userId from whose perspective we want
   * to calculate the default name
   * @returns The default room name
   */
  getDefaultRoomName(userId) {
    return this.calculateRoomName(userId, true);
  }

  /**
   * Check if the given user_id has the given membership state.
   * @param userId - The user ID to check.
   * @param membership - The membership e.g. `'join'`
   * @returns True if this user_id has the given membership state.
   */
  hasMembershipState(userId, membership) {
    const member = this.getMember(userId);
    if (!member) {
      return false;
    }
    return member.membership === membership;
  }

  /**
   * Add a timelineSet for this room with the given filter
   * @param filter - The filter to be applied to this timelineSet
   * @param opts - Configuration options
   * @returns The timelineSet
   */
  getOrCreateFilteredTimelineSet(filter, {
    prepopulateTimeline = true,
    useSyncEvents = true,
    pendingEvents = true
  } = {}) {
    if (this.filteredTimelineSets[filter.filterId]) {
      return this.filteredTimelineSets[filter.filterId];
    }
    const opts = Object.assign({
      filter,
      pendingEvents
    }, this.opts);
    const timelineSet = new _eventTimelineSet.EventTimelineSet(this, opts);
    this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);
    if (useSyncEvents) {
      this.filteredTimelineSets[filter.filterId] = timelineSet;
      this.timelineSets.push(timelineSet);
    }
    const unfilteredLiveTimeline = this.getLiveTimeline();
    // Not all filter are possible to replicate client-side only
    // When that's the case we do not want to prepopulate from the live timeline
    // as we would get incorrect results compared to what the server would send back
    if (prepopulateTimeline) {
      // populate up the new timelineSet with filtered events from our live
      // unfiltered timeline.
      //
      // XXX: This is risky as our timeline
      // may have grown huge and so take a long time to filter.
      // see https://github.com/vector-im/vector-web/issues/2109

      unfilteredLiveTimeline.getEvents().forEach(function (event) {
        timelineSet.addLiveEvent(event);
      });

      // find the earliest unfiltered timeline
      let timeline = unfilteredLiveTimeline;
      while (timeline.getNeighbouringTimeline(_eventTimeline.EventTimeline.BACKWARDS)) {
        timeline = timeline.getNeighbouringTimeline(_eventTimeline.EventTimeline.BACKWARDS);
      }
      timelineSet.getLiveTimeline().setPaginationToken(timeline.getPaginationToken(_eventTimeline.EventTimeline.BACKWARDS), _eventTimeline.EventTimeline.BACKWARDS);
    } else if (useSyncEvents) {
      const livePaginationToken = unfilteredLiveTimeline.getPaginationToken(_eventTimeline.Direction.Forward);
      timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, _eventTimeline.Direction.Backward);
    }

    // alternatively, we could try to do something like this to try and re-paginate
    // in the filtered events from nothing, but Mark says it's an abuse of the API
    // to do so:
    //
    // timelineSet.resetLiveTimeline(
    //      unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)
    // );

    return timelineSet;
  }
  async getThreadListFilter(filterType = _thread.ThreadFilterType.All) {
    const myUserId = this.client.getUserId();
    const filter = new _filter.Filter(myUserId);
    const definition = {
      room: {
        timeline: {
          [_thread.FILTER_RELATED_BY_REL_TYPES.name]: [_thread.THREAD_RELATION_TYPE.name]
        }
      }
    };
    if (filterType === _thread.ThreadFilterType.My) {
      definition.room.timeline[_thread.FILTER_RELATED_BY_SENDERS.name] = [myUserId];
    }
    filter.setDefinition(definition);
    const filterId = await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${filterType}`, filter);
    filter.filterId = filterId;
    return filter;
  }
  async createThreadTimelineSet(filterType) {
    let timelineSet;
    if (_thread.Thread.hasServerSideListSupport) {
      timelineSet = new _eventTimelineSet.EventTimelineSet(this, _objectSpread(_objectSpread({}, this.opts), {}, {
        pendingEvents: false
      }), undefined, undefined, filterType ?? _thread.ThreadFilterType.All);
      this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);
    } else if (_thread.Thread.hasServerSideSupport) {
      const filter = await this.getThreadListFilter(filterType);
      timelineSet = this.getOrCreateFilteredTimelineSet(filter, {
        prepopulateTimeline: false,
        useSyncEvents: false,
        pendingEvents: false
      });
    } else {
      timelineSet = new _eventTimelineSet.EventTimelineSet(this, {
        pendingEvents: false
      });
      Array.from(this.threads).forEach(([, thread]) => {
        if (thread.length === 0) return;
        const currentUserParticipated = thread.timeline.some(event => {
          return event.getSender() === this.client.getUserId();
        });
        if (filterType !== _thread.ThreadFilterType.My || currentUserParticipated) {
          timelineSet.getLiveTimeline().addEvent(thread.rootEvent, {
            toStartOfTimeline: false
          });
        }
      });
    }
    return timelineSet;
  }
  /**
   * Takes the given thread root events and creates threads for them.
   */
  processThreadRoots(events, toStartOfTimeline) {
    for (const rootEvent of events) {
      _eventTimeline.EventTimeline.setEventMetadata(rootEvent, this.currentState, toStartOfTimeline);
      if (!this.getThread(rootEvent.getId())) {
        this.createThread(rootEvent.getId(), rootEvent, [], toStartOfTimeline);
      }
    }
  }

  /**
   * Fetch the bare minimum of room threads required for the thread list to work reliably.
   * With server support that means fetching one page.
   * Without server support that means fetching as much at once as the server allows us to.
   */
  async fetchRoomThreads() {
    if (this.threadsReady || !this.client.supportsThreads()) {
      return;
    }
    if (_thread.Thread.hasServerSideListSupport) {
      await Promise.all([this.fetchRoomThreadList(_thread.ThreadFilterType.All), this.fetchRoomThreadList(_thread.ThreadFilterType.My)]);
    } else {
      const allThreadsFilter = await this.getThreadListFilter();
      const {
        chunk: events
      } = await this.client.createMessagesRequest(this.roomId, "", Number.MAX_SAFE_INTEGER, _eventTimeline.Direction.Backward, allThreadsFilter);
      if (!events.length) return;

      // Sorted by last_reply origin_server_ts
      const threadRoots = events.map(this.client.getEventMapper()).sort((eventA, eventB) => {
        /**
         * `origin_server_ts` in a decentralised world is far from ideal
         * but for lack of any better, we will have to use this
         * Long term the sorting should be handled by homeservers and this
         * is only meant as a short term patch
         */
        const threadAMetadata = eventA.getServerAggregatedRelation(_thread.THREAD_RELATION_TYPE.name);
        const threadBMetadata = eventB.getServerAggregatedRelation(_thread.THREAD_RELATION_TYPE.name);
        return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts;
      });
      let latestMyThreadsRootEvent;
      const roomState = this.getLiveTimeline().getState(_eventTimeline.EventTimeline.FORWARDS);
      for (const rootEvent of threadRoots) {
        const opts = {
          duplicateStrategy: _eventTimelineSet.DuplicateStrategy.Ignore,
          fromCache: false,
          roomState
        };
        this.threadsTimelineSets[0]?.addLiveEvent(rootEvent, opts);
        const threadRelationship = rootEvent.getServerAggregatedRelation(_thread.THREAD_RELATION_TYPE.name);
        if (threadRelationship?.current_user_participated) {
          this.threadsTimelineSets[1]?.addLiveEvent(rootEvent, opts);
          latestMyThreadsRootEvent = rootEvent;
        }
      }
      this.processThreadRoots(threadRoots, true);
      this.client.decryptEventIfNeeded(threadRoots[threadRoots.length - 1]);
      if (latestMyThreadsRootEvent) {
        this.client.decryptEventIfNeeded(latestMyThreadsRootEvent);
      }
    }
    this.on(_thread.ThreadEvent.NewReply, this.onThreadNewReply);
    this.on(_thread.ThreadEvent.Delete, this.onThreadDelete);
    this.threadsReady = true;
  }

  /**
   * Calls {@link processPollEvent} for a list of events.
   *
   * @param events - List of events
   */
  async processPollEvents(events) {
    for (const event of events) {
      try {
        // Continue if the event is a clear text, non-poll event.
        if (!event.isEncrypted() && !(0, _poll.isPollEvent)(event)) continue;

        /**
         * Try to decrypt the event. Promise resolution does not guarantee a successful decryption.
         * Retry is handled in {@link processPollEvent}.
         */
        await this.client.decryptEventIfNeeded(event);
        this.processPollEvent(event);
      } catch (err) {
        _logger.logger.warn("Error processing poll event", event.getId(), err);
      }
    }
  }

  /**
   * Processes poll events:
   * If the event has a decryption failure, it will listen for decryption and tries again.
   * If it is a poll start event (`m.poll.start`),
   * it creates and stores a Poll model and emits a PollEvent.New event.
   * If the event is related to a poll, it will add it to the poll.
   * Noop for other cases.
   *
   * @param event - Event that could be a poll event
   */
  async processPollEvent(event) {
    if (event.isDecryptionFailure()) {
      event.once(_event.MatrixEventEvent.Decrypted, maybeDecryptedEvent => {
        this.processPollEvent(maybeDecryptedEvent);
      });
      return;
    }
    if (_matrixEventsSdk.M_POLL_START.matches(event.getType())) {
      try {
        const poll = new _poll.Poll(event, this.client, this);
        this.polls.set(event.getId(), poll);
        this.emit(_poll.PollEvent.New, poll);
      } catch {}
      // poll creation can fail for malformed poll start events
      return;
    }
    const relationEventId = event.relationEventId;
    if (relationEventId && this.polls.has(relationEventId)) {
      const poll = this.polls.get(relationEventId);
      poll?.onNewRelation(event);
    }
  }

  /**
   * Fetch a single page of threadlist messages for the specific thread filter
   * @internal
   */
  async fetchRoomThreadList(filter) {
    if (this.threadsTimelineSets.length === 0) return;
    const timelineSet = filter === _thread.ThreadFilterType.My ? this.threadsTimelineSets[1] : this.threadsTimelineSets[0];
    const {
      chunk: events,
      end
    } = await this.client.createThreadListMessagesRequest(this.roomId, null, undefined, _eventTimeline.Direction.Backward, timelineSet.threadListType, timelineSet.getFilter());
    timelineSet.getLiveTimeline().setPaginationToken(end ?? null, _eventTimeline.Direction.Backward);
    if (!events.length) return;
    const matrixEvents = events.map(this.client.getEventMapper());
    this.processThreadRoots(matrixEvents, true);
    const roomState = this.getLiveTimeline().getState(_eventTimeline.EventTimeline.FORWARDS);
    for (const rootEvent of matrixEvents) {
      timelineSet.addLiveEvent(rootEvent, {
        duplicateStrategy: _eventTimelineSet.DuplicateStrategy.Replace,
        fromCache: false,
        roomState
      });
    }
  }
  onThreadNewReply(thread) {
    this.updateThreadRootEvents(thread, false, true);
  }
  onThreadDelete(thread) {
    this.threads.delete(thread.id);
    const timeline = this.getTimelineForEvent(thread.id);
    const roomEvent = timeline?.getEvents()?.find(it => it.getId() === thread.id);
    if (roomEvent) {
      thread.clearEventMetadata(roomEvent);
    } else {
      _logger.logger.debug("onThreadDelete: Could not find root event in room timeline");
    }
    for (const timelineSet of this.threadsTimelineSets) {
      timelineSet.removeEvent(thread.id);
    }
  }

  /**
   * Forget the timelineSet for this room with the given filter
   *
   * @param filter - the filter whose timelineSet is to be forgotten
   */
  removeFilteredTimelineSet(filter) {
    const timelineSet = this.filteredTimelineSets[filter.filterId];
    delete this.filteredTimelineSets[filter.filterId];
    const i = this.timelineSets.indexOf(timelineSet);
    if (i > -1) {
      this.timelineSets.splice(i, 1);
    }
  }
  eventShouldLiveIn(event, events, roots) {
    if (!this.client?.supportsThreads()) {
      return {
        shouldLiveInRoom: true,
        shouldLiveInThread: false
      };
    }

    // A thread root is always shown in both timelines
    if (event.isThreadRoot || roots?.has(event.getId())) {
      return {
        shouldLiveInRoom: true,
        shouldLiveInThread: true,
        threadId: event.getId()
      };
    }

    // A thread relation is always only shown in a thread
    if (event.isRelation(_thread.THREAD_RELATION_TYPE.name)) {
      return {
        shouldLiveInRoom: false,
        shouldLiveInThread: true,
        threadId: event.threadRootId
      };
    }
    const parentEventId = event.getAssociatedId();
    let parentEvent;
    if (parentEventId) {
      parentEvent = this.findEventById(parentEventId) ?? events?.find(e => e.getId() === parentEventId);
    }

    // Treat relations and redactions as extensions of their parents so evaluate parentEvent instead
    if (parentEvent && (event.isRelation() || event.isRedaction())) {
      return this.eventShouldLiveIn(parentEvent, events, roots);
    }
    if (!event.isRelation()) {
      return {
        shouldLiveInRoom: true,
        shouldLiveInThread: false
      };
    }

    // Edge case where we know the event is a relation but don't have the parentEvent
    if (roots?.has(event.relationEventId)) {
      return {
        shouldLiveInRoom: true,
        shouldLiveInThread: true,
        threadId: event.relationEventId
      };
    }
    const unsigned = event.getUnsigned();
    if (typeof unsigned[_event2.UNSIGNED_THREAD_ID_FIELD.name] === "string") {
      return {
        shouldLiveInRoom: false,
        shouldLiveInThread: true,
        threadId: unsigned[_event2.UNSIGNED_THREAD_ID_FIELD.name]
      };
    }

    // We've exhausted all scenarios,
    // we cannot assume that it lives in the main timeline as this may be a relation for an unknown thread
    // adding the event in the wrong timeline causes stuck notifications and can break ability to send read receipts
    return {
      shouldLiveInRoom: false,
      shouldLiveInThread: false
    };
  }
  findThreadForEvent(event) {
    if (!event) return null;
    const {
      threadId
    } = this.eventShouldLiveIn(event);
    return threadId ? this.getThread(threadId) : null;
  }
  addThreadedEvents(threadId, events, toStartOfTimeline = false) {
    const thread = this.getThread(threadId);
    if (thread) {
      thread.addEvents(events, toStartOfTimeline);
    } else {
      const rootEvent = this.findEventById(threadId) ?? events.find(e => e.getId() === threadId);
      this.createThread(threadId, rootEvent, events, toStartOfTimeline);
    }
  }

  /**
   * Adds events to a thread's timeline. Will fire "Thread.update"
   */
  processThreadedEvents(events, toStartOfTimeline) {
    events.forEach(this.applyRedaction);
    const eventsByThread = {};
    for (const event of events) {
      const {
        threadId,
        shouldLiveInThread
      } = this.eventShouldLiveIn(event);
      if (shouldLiveInThread && !eventsByThread[threadId]) {
        eventsByThread[threadId] = [];
      }
      eventsByThread[threadId]?.push(event);
    }
    Object.entries(eventsByThread).map(([threadId, threadEvents]) => this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline));
  }
  createThread(threadId, rootEvent, events = [], toStartOfTimeline) {
    if (this.threads.has(threadId)) {
      return this.threads.get(threadId);
    }
    if (rootEvent) {
      const relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId());
      if (relatedEvents?.length) {
        // Include all relations of the root event, given it'll be visible in both timelines,
        // except `m.replace` as that will already be applied atop the event using `MatrixEvent::makeReplaced`
        events = events.concat(relatedEvents.filter(e => !e.isRelation(_event2.RelationType.Replace)));
      }
    }
    const thread = new _thread.Thread(threadId, rootEvent, {
      room: this,
      client: this.client,
      pendingEventOrdering: this.opts.pendingEventOrdering,
      receipts: this.cachedThreadReadReceipts.get(threadId) ?? []
    });

    // All read receipts should now come down from sync, we do not need to keep
    // a reference to the cached receipts anymore.
    this.cachedThreadReadReceipts.delete(threadId);

    // If we managed to create a thread and figure out its `id` then we can use it
    // This has to happen before thread.addEvents, because that adds events to the eventtimeline, and the
    // eventtimeline sometimes looks up thread information via the room.
    this.threads.set(thread.id, thread);

    // This is necessary to be able to jump to events in threads:
    // If we jump to an event in a thread where neither the event, nor the root,
    // nor any thread event are loaded yet, we'll load the event as well as the thread root, create the thread,
    // and pass the event through this.
    thread.addEvents(events, false);
    this.reEmitter.reEmit(thread, [_thread.ThreadEvent.Delete, _thread.ThreadEvent.Update, _thread.ThreadEvent.NewReply, RoomEvent.Timeline, RoomEvent.TimelineReset]);
    const isNewer = this.lastThread?.rootEvent && rootEvent?.localTimestamp && this.lastThread.rootEvent?.localTimestamp < rootEvent?.localTimestamp;
    if (!this.lastThread || isNewer) {
      this.lastThread = thread;
    }
    if (this.threadsReady) {
      this.updateThreadRootEvents(thread, toStartOfTimeline, false);
    }
    this.emit(_thread.ThreadEvent.New, thread, toStartOfTimeline);
    return thread;
  }
  processLiveEvent(event) {
    this.applyRedaction(event);

    // Implement MSC3531: hiding messages.
    if (event.isVisibilityEvent()) {
      // This event changes the visibility of another event, record
      // the visibility change, inform clients if necessary.
      this.applyNewVisibilityEvent(event);
    }
    // If any pending visibility change is waiting for this (older) event,
    this.applyPendingVisibilityEvents(event);

    // Sliding Sync modifications:
    // The proxy cannot guarantee every sent event will have a transaction_id field, so we need
    // to check the event ID against the list of pending events if there is no transaction ID
    // field. Only do this for events sent by us though as it's potentially expensive to loop
    // the pending events map.
    const txnId = event.getUnsigned().transaction_id;
    if (!txnId && event.getSender() === this.myUserId) {
      // check the txn map for a matching event ID
      for (const [tid, localEvent] of this.txnToEvent) {
        if (localEvent.getId() === event.getId()) {
          _logger.logger.debug("processLiveEvent: found sent event without txn ID: ", tid, event.getId());
          // update the unsigned field so we can re-use the same codepaths
          const unsigned = event.getUnsigned();
          unsigned.transaction_id = tid;
          event.setUnsigned(unsigned);
          break;
        }
      }
    }
  }

  /**
   * Add an event to the end of this room's live timelines. Will fire
   * "Room.timeline".
   *
   * @param event - Event to be added
   * @param addLiveEventOptions - addLiveEvent options
   * @internal
   *
   * @remarks
   * Fires {@link RoomEvent.Timeline}
   */
  addLiveEvent(event, addLiveEventOptions) {
    const {
      duplicateStrategy,
      timelineWasEmpty,
      fromCache
    } = addLiveEventOptions;

    // add to our timeline sets
    for (const timelineSet of this.timelineSets) {
      timelineSet.addLiveEvent(event, {
        duplicateStrategy,
        fromCache,
        timelineWasEmpty
      });
    }

    // synthesize and inject implicit read receipts
    // Done after adding the event because otherwise the app would get a read receipt
    // pointing to an event that wasn't yet in the timeline
    // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.
    if (event.sender && event.getType() !== _event2.EventType.RoomRedaction) {
      this.addReceipt((0, _readReceipt.synthesizeReceipt)(event.sender.userId, event, _read_receipts.ReceiptType.Read), true);

      // Any live events from a user could be taken as implicit
      // presence information: evidence that they are currently active.
      // ...except in a world where we use 'user.currentlyActive' to reduce
      // presence spam, this isn't very useful - we'll get a transition when
      // they are no longer currently active anyway. So don't bother to
      // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.
    }
  }

  /**
   * Add a pending outgoing event to this room.
   *
   * <p>The event is added to either the pendingEventList, or the live timeline,
   * depending on the setting of opts.pendingEventOrdering.
   *
   * <p>This is an internal method, intended for use by MatrixClient.
   *
   * @param event - The event to add.
   *
   * @param txnId - Transaction id for this outgoing event
   *
   * @throws if the event doesn't have status SENDING, or we aren't given a
   * unique transaction id.
   *
   * @remarks
   * Fires {@link RoomEvent.LocalEchoUpdated}
   */
  addPendingEvent(event, txnId) {
    if (event.status !== _eventStatus.EventStatus.SENDING && event.status !== _eventStatus.EventStatus.NOT_SENT) {
      throw new Error("addPendingEvent called on an event with status " + event.status);
    }
    if (this.txnToEvent.get(txnId)) {
      throw new Error("addPendingEvent called on an event with known txnId " + txnId);
    }

    // call setEventMetadata to set up event.sender etc
    // as event is shared over all timelineSets, we set up its metadata based
    // on the unfiltered timelineSet.
    _eventTimeline.EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(_eventTimeline.EventTimeline.FORWARDS), false);
    this.txnToEvent.set(txnId, event);
    if (this.pendingEventList) {
      if (this.pendingEventList.some(e => e.status === _eventStatus.EventStatus.NOT_SENT)) {
        _logger.logger.warn("Setting event as NOT_SENT due to messages in the same state");
        event.setStatus(_eventStatus.EventStatus.NOT_SENT);
      }
      this.pendingEventList.push(event);
      this.savePendingEvents();
      if (event.isRelation()) {
        // For pending events, add them to the relations collection immediately.
        // (The alternate case below already covers this as part of adding to
        // the timeline set.)
        this.aggregateNonLiveRelation(event);
      }
      if (event.isRedaction()) {
        const redactId = event.event.redacts;
        let redactedEvent = this.pendingEventList.find(e => e.getId() === redactId);
        if (!redactedEvent && redactId) {
          redactedEvent = this.findEventById(redactId);
        }
        if (redactedEvent) {
          redactedEvent.markLocallyRedacted(event);
          this.emit(RoomEvent.Redaction, event, this);
        }
      }
    } else {
      for (const timelineSet of this.timelineSets) {
        if (timelineSet.getFilter()) {
          if (timelineSet.getFilter().filterRoomTimeline([event]).length) {
            timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {
              toStartOfTimeline: false
            });
          }
        } else {
          timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {
            toStartOfTimeline: false
          });
        }
      }
    }
    this.emit(RoomEvent.LocalEchoUpdated, event, this);
  }

  /**
   * Persists all pending events to local storage
   *
   * If the current room is encrypted only encrypted events will be persisted
   * all messages that are not yet encrypted will be discarded
   *
   * This is because the flow of EVENT_STATUS transition is
   * `queued => sending => encrypting => sending => sent`
   *
   * Steps 3 and 4 are skipped for unencrypted room.
   * It is better to discard an unencrypted message rather than persisting
   * it locally for everyone to read
   */
  savePendingEvents() {
    if (this.pendingEventList) {
      const pendingEvents = this.pendingEventList.map(event => {
        return _objectSpread(_objectSpread({}, event.event), {}, {
          txn_id: event.getTxnId()
        });
      }).filter(event => {
        // Filter out the unencrypted messages if the room is encrypted
        const isEventEncrypted = event.type === _event2.EventType.RoomMessageEncrypted;
        const isRoomEncrypted = this.client.isRoomEncrypted(this.roomId);
        return isEventEncrypted || !isRoomEncrypted;
      });
      this.client.store.setPendingEvents(this.roomId, pendingEvents);
    }
  }

  /**
   * Used to aggregate the local echo for a relation, and also
   * for re-applying a relation after it's redaction has been cancelled,
   * as the local echo for the redaction of the relation would have
   * un-aggregated the relation. Note that this is different from regular messages,
   * which are just kept detached for their local echo.
   *
   * Also note that live events are aggregated in the live EventTimelineSet.
   * @param event - the relation event that needs to be aggregated.
   */
  aggregateNonLiveRelation(event) {
    this.relations.aggregateChildEvent(event);
  }
  getEventForTxnId(txnId) {
    return this.txnToEvent.get(txnId);
  }

  /**
   * Deal with the echo of a message we sent.
   *
   * <p>We move the event to the live timeline if it isn't there already, and
   * update it.
   *
   * @param remoteEvent -   The event received from
   *    /sync
   * @param localEvent -    The local echo, which
   *    should be either in the pendingEventList or the timeline.
   *
   * @internal
   *
   * @remarks
   * Fires {@link RoomEvent.LocalEchoUpdated}
   */
  handleRemoteEcho(remoteEvent, localEvent) {
    const oldEventId = localEvent.getId();
    const newEventId = remoteEvent.getId();
    const oldStatus = localEvent.status;
    _logger.logger.debug(`Got remote echo for event ${oldEventId} -> ${newEventId} old status ${oldStatus}`);

    // no longer pending
    this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id);

    // if it's in the pending list, remove it
    if (this.pendingEventList) {
      this.removePendingEvent(oldEventId);
    }

    // replace the event source (this will preserve the plaintext payload if
    // any, which is good, because we don't want to try decoding it again).
    localEvent.handleRemoteEcho(remoteEvent.event);
    const {
      shouldLiveInRoom,
      threadId
    } = this.eventShouldLiveIn(remoteEvent);
    const thread = threadId ? this.getThread(threadId) : null;
    thread?.setEventMetadata(localEvent);
    thread?.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);
    if (shouldLiveInRoom) {
      for (const timelineSet of this.timelineSets) {
        // if it's already in the timeline, update the timeline map. If it's not, add it.
        timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);
      }
    }
    this.emit(RoomEvent.LocalEchoUpdated, localEvent, this, oldEventId, oldStatus);
  }

  /**
   * Update the status / event id on a pending event, to reflect its transmission
   * progress.
   *
   * <p>This is an internal method.
   *
   * @param event -      local echo event
   * @param newStatus -  status to assign
   * @param newEventId -      new event id to assign. Ignored unless newStatus == EventStatus.SENT.
   *
   * @remarks
   * Fires {@link RoomEvent.LocalEchoUpdated}
   */
  updatePendingEvent(event, newStatus, newEventId) {
    _logger.logger.log(`setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` + `event ID ${event.getId()} -> ${newEventId}`);

    // if the message was sent, we expect an event id
    if (newStatus == _eventStatus.EventStatus.SENT && !newEventId) {
      throw new Error("updatePendingEvent called with status=SENT, but no new event id");
    }

    // SENT races against /sync, so we have to special-case it.
    if (newStatus == _eventStatus.EventStatus.SENT) {
      const timeline = this.getTimelineForEvent(newEventId);
      if (timeline) {
        // we've already received the event via the event stream.
        // nothing more to do here, assuming the transaction ID was correctly matched.
        // Let's check that.
        const remoteEvent = this.findEventById(newEventId);
        const remoteTxnId = remoteEvent?.getUnsigned().transaction_id;
        if (!remoteTxnId && remoteEvent) {
          // This code path is mostly relevant for the Sliding Sync proxy.
          // The remote event did not contain a transaction ID, so we did not handle
          // the remote echo yet. Handle it now.
          const unsigned = remoteEvent.getUnsigned();
          unsigned.transaction_id = event.getTxnId();
          remoteEvent.setUnsigned(unsigned);
          // the remote event is _already_ in the timeline, so we need to remove it so
          // we can convert the local event into the final event.
          this.removeEvent(remoteEvent.getId());
          this.handleRemoteEcho(remoteEvent, event);
        }
        return;
      }
    }
    const oldStatus = event.status;
    const oldEventId = event.getId();
    if (!oldStatus) {
      throw new Error("updatePendingEventStatus called on an event which is not a local echo.");
    }
    const allowed = ALLOWED_TRANSITIONS[oldStatus];
    if (!allowed?.includes(newStatus)) {
      throw new Error(`Invalid EventStatus transition ${oldStatus}->${newStatus}`);
    }
    event.setStatus(newStatus);
    if (newStatus == _eventStatus.EventStatus.SENT) {
      // update the event id
      event.replaceLocalEventId(newEventId);
      const {
        shouldLiveInRoom,
        threadId
      } = this.eventShouldLiveIn(event);
      const thread = threadId ? this.getThread(threadId) : undefined;
      thread?.setEventMetadata(event);
      thread?.timelineSet.replaceEventId(oldEventId, newEventId);
      if (shouldLiveInRoom) {
        // if the event was already in the timeline (which will be the case if
        // opts.pendingEventOrdering==chronological), we need to update the
        // timeline map.
        for (const timelineSet of this.timelineSets) {
          timelineSet.replaceEventId(oldEventId, newEventId);
        }
      }
    } else if (newStatus == _eventStatus.EventStatus.CANCELLED) {
      // remove it from the pending event list, or the timeline.
      if (this.pendingEventList) {
        const removedEvent = this.getPendingEvent(oldEventId);
        this.removePendingEvent(oldEventId);
        if (removedEvent?.isRedaction()) {
          this.revertRedactionLocalEcho(removedEvent);
        }
      }
      this.removeEvent(oldEventId);
    }
    this.savePendingEvents();
    this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus);
  }
  revertRedactionLocalEcho(redactionEvent) {
    const redactId = redactionEvent.event.redacts;
    if (!redactId) {
      return;
    }
    const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);
    if (redactedEvent) {
      redactedEvent.unmarkLocallyRedacted();
      // re-render after undoing redaction
      this.emit(RoomEvent.RedactionCancelled, redactionEvent, this);
      // reapply relation now redaction failed
      if (redactedEvent.isRelation()) {
        this.aggregateNonLiveRelation(redactedEvent);
      }
    }
  }

  /**
   * Add some events to this room. This can include state events, message
   * events and typing notifications. These events are treated as "live" so
   * they will go to the end of the timeline.
   *
   * @param events - A list of events to add.
   * @param addLiveEventOptions - addLiveEvent options
   * @throws If `duplicateStrategy` is not falsey, 'replace' or 'ignore'.
   */

  /**
   * @deprecated In favor of the overload with `IAddLiveEventOptions`
   */

  async addLiveEvents(events, duplicateStrategyOrOpts, fromCache = false) {
    let duplicateStrategy = duplicateStrategyOrOpts;
    let timelineWasEmpty = false;
    if (typeof duplicateStrategyOrOpts === "object") {
      ({
        duplicateStrategy,
        fromCache = false,
        /* roomState, (not used here) */
        timelineWasEmpty
      } = duplicateStrategyOrOpts);
    } else if (duplicateStrategyOrOpts !== undefined) {
      // Deprecation warning
      // FIXME: Remove after 2023-06-01 (technical debt)
      _logger.logger.warn("Overload deprecated: " + "`Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` " + "is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`");
    }
    if (duplicateStrategy && ["replace", "ignore"].indexOf(duplicateStrategy) === -1) {
      throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");
    }

    // sanity check that the live timeline is still live
    for (let i = 0; i < this.timelineSets.length; i++) {
      const liveTimeline = this.timelineSets[i].getLiveTimeline();
      if (liveTimeline.getPaginationToken(_eventTimeline.EventTimeline.FORWARDS)) {
        throw new Error("live timeline " + i + " is no longer live - it has a pagination token " + "(" + liveTimeline.getPaginationToken(_eventTimeline.EventTimeline.FORWARDS) + ")");
      }
      if (liveTimeline.getNeighbouringTimeline(_eventTimeline.EventTimeline.FORWARDS)) {
        throw new Error(`live timeline ${i} is no longer live - it has a neighbouring timeline`);
      }
    }
    const threadRoots = this.findThreadRoots(events);
    const eventsByThread = {};
    const options = {
      duplicateStrategy,
      fromCache,
      timelineWasEmpty
    };

    // List of extra events to check for being parents of any relations encountered
    const neighbouringEvents = [...events];
    for (const event of events) {
      // TODO: We should have a filter to say "only add state event types X Y Z to the timeline".
      this.processLiveEvent(event);
      if (event.getUnsigned().transaction_id) {
        const existingEvent = this.txnToEvent.get(event.getUnsigned().transaction_id);
        if (existingEvent) {
          // remote echo of an event we sent earlier
          this.handleRemoteEcho(event, existingEvent);
          continue; // we can skip adding the event to the timeline sets, it is already there
        }
      }

      let {
        shouldLiveInRoom,
        shouldLiveInThread,
        threadId
      } = this.eventShouldLiveIn(event, neighbouringEvents, threadRoots);
      if (!shouldLiveInThread && !shouldLiveInRoom && event.isRelation()) {
        try {
          const parentEvent = new _event.MatrixEvent(await this.client.fetchRoomEvent(this.roomId, event.relationEventId));
          neighbouringEvents.push(parentEvent);
          if (parentEvent.threadRootId) {
            threadRoots.add(parentEvent.threadRootId);
            const unsigned = event.getUnsigned();
            unsigned[_event2.UNSIGNED_THREAD_ID_FIELD.name] = parentEvent.threadRootId;
            event.setUnsigned(unsigned);
          }
          ({
            shouldLiveInRoom,
            shouldLiveInThread,
            threadId
          } = this.eventShouldLiveIn(event, neighbouringEvents, threadRoots));
        } catch (e) {
          _logger.logger.error("Failed to load parent event of unhandled relation", e);
        }
      }
      if (shouldLiveInThread && !eventsByThread[threadId ?? ""]) {
        eventsByThread[threadId ?? ""] = [];
      }
      eventsByThread[threadId ?? ""]?.push(event);
      if (shouldLiveInRoom) {
        this.addLiveEvent(event, options);
      } else if (!shouldLiveInThread && event.isRelation()) {
        this.relations.aggregateChildEvent(event);
      }
    }
    Object.entries(eventsByThread).forEach(([threadId, threadEvents]) => {
      this.addThreadedEvents(threadId, threadEvents, false);
    });
  }
  partitionThreadedEvents(events) {
    // Indices to the events array, for readability
    const ROOM = 0;
    const THREAD = 1;
    const UNKNOWN_RELATION = 2;
    if (this.client.supportsThreads()) {
      const threadRoots = this.findThreadRoots(events);
      return events.reduce((memo, event) => {
        const {
          shouldLiveInRoom,
          shouldLiveInThread,
          threadId
        } = this.eventShouldLiveIn(event, events, threadRoots);
        if (shouldLiveInRoom) {
          memo[ROOM].push(event);
        }
        if (shouldLiveInThread) {
          event.setThreadId(threadId ?? "");
          memo[THREAD].push(event);
        }
        if (!shouldLiveInThread && !shouldLiveInRoom) {
          memo[UNKNOWN_RELATION].push(event);
        }
        return memo;
      }, [[], [], []]);
    } else {
      // When `experimentalThreadSupport` is disabled treat all events as timelineEvents
      return [events, [], []];
    }
  }

  /**
   * Given some events, find the IDs of all the thread roots that are referred to by them.
   */
  findThreadRoots(events) {
    const threadRoots = new Set();
    for (const event of events) {
      if (event.isRelation(_thread.THREAD_RELATION_TYPE.name)) {
        threadRoots.add(event.relationEventId ?? "");
      }
      const unsigned = event.getUnsigned();
      if (typeof unsigned[_event2.UNSIGNED_THREAD_ID_FIELD.name] === "string") {
        threadRoots.add(unsigned[_event2.UNSIGNED_THREAD_ID_FIELD.name]);
      }
    }
    return threadRoots;
  }

  /**
   * Add a receipt event to the room.
   * @param event - The m.receipt event.
   * @param synthetic - True if this event is implicit.
   */
  addReceipt(event, synthetic = false) {
    const content = event.getContent();
    Object.keys(content).forEach(eventId => {
      Object.keys(content[eventId]).forEach(receiptType => {
        Object.keys(content[eventId][receiptType]).forEach(userId => {
          const receipt = content[eventId][receiptType][userId];
          const receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === _read_receipts.MAIN_ROOM_TIMELINE;
          const receiptDestination = receiptForMainTimeline ? this : this.threads.get(receipt.thread_id ?? "");
          if (receiptDestination) {
            receiptDestination.addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic);

            // If the read receipt sent for the logged in user matches
            // the last event of the live timeline, then we know for a fact
            // that the user has read that message.
            // We can mark the room as read and not wait for the local echo
            // from synapse
            // This needs to be done after the initial sync as we do not want this
            // logic to run whilst the room is being initialised
            if (this.client.isInitialSyncComplete() && userId === this.client.getUserId()) {
              const lastEvent = receiptDestination.timeline[receiptDestination.timeline.length - 1];
              if (lastEvent && eventId === lastEvent.getId() && userId === lastEvent.getSender()) {
                receiptDestination.setUnread(NotificationCountType.Total, 0);
                receiptDestination.setUnread(NotificationCountType.Highlight, 0);
              }
            }
          } else {
            // The thread does not exist locally, keep the read receipt
            // in a cache locally, and re-apply  the `addReceipt` logic
            // when the thread is created
            this.cachedThreadReadReceipts.set(receipt.thread_id, [...(this.cachedThreadReadReceipts.get(receipt.thread_id) ?? []), {
              eventId,
              receiptType,
              userId,
              receipt,
              synthetic
            }]);
          }
          const me = this.client.getUserId();
          // Track the time of the current user's oldest threaded receipt in the room.
          if (userId === me && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) {
            this.oldestThreadedReceiptTs = receipt.ts;
          }

          // Track each user's unthreaded read receipt.
          if (!receipt.thread_id && receipt.ts > (this.unthreadedReceipts.get(userId)?.ts ?? 0)) {
            this.unthreadedReceipts.set(userId, receipt);
          }
        });
      });
    });

    // send events after we've regenerated the structure & cache, otherwise things that
    // listened for the event would read stale data.
    this.emit(RoomEvent.Receipt, event, this);
  }

  /**
   * Adds/handles ephemeral events such as typing notifications and read receipts.
   * @param events - A list of events to process
   */
  addEphemeralEvents(events) {
    for (const event of events) {
      if (event.getType() === _event2.EventType.Typing) {
        this.currentState.setTypingEvent(event);
      } else if (event.getType() === _event2.EventType.Receipt) {
        this.addReceipt(event);
      } // else ignore - life is too short for us to care about these events
    }
  }

  /**
   * Removes events from this room.
   * @param eventIds - A list of eventIds to remove.
   */
  removeEvents(eventIds) {
    for (const eventId of eventIds) {
      this.removeEvent(eventId);
    }
  }

  /**
   * Removes a single event from this room.
   *
   * @param eventId -  The id of the event to remove
   *
   * @returns true if the event was removed from any of the room's timeline sets
   */
  removeEvent(eventId) {
    let removedAny = false;
    for (const timelineSet of this.timelineSets) {
      const removed = timelineSet.removeEvent(eventId);
      if (removed) {
        if (removed.isRedaction()) {
          this.revertRedactionLocalEcho(removed);
        }
        removedAny = true;
      }
    }
    return removedAny;
  }

  /**
   * Recalculate various aspects of the room, including the room name and
   * room summary. Call this any time the room's current state is modified.
   * May fire "Room.name" if the room name is updated.
   *
   * @remarks
   * Fires {@link RoomEvent.Name}
   */
  recalculate() {
    // set fake stripped state events if this is an invite room so logic remains
    // consistent elsewhere.
    const membershipEvent = this.currentState.getStateEvents(_event2.EventType.RoomMember, this.myUserId);
    if (membershipEvent) {
      const membership = membershipEvent.getContent().membership;
      this.updateMyMembership(membership);
      if (membership === "invite") {
        const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];
        strippedStateEvents.forEach(strippedEvent => {
          const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);
          if (!existingEvent) {
            // set the fake stripped event instead
            this.currentState.setStateEvents([new _event.MatrixEvent({
              type: strippedEvent.type,
              state_key: strippedEvent.state_key,
              content: strippedEvent.content,
              event_id: "$fake" + Date.now(),
              room_id: this.roomId,
              user_id: this.myUserId // technically a lie
            })]);
          }
        });
      }
    }

    const oldName = this.name;
    this.name = this.calculateRoomName(this.myUserId);
    this.normalizedName = (0, _utils.normalize)(this.name);
    this.summary = new _roomSummary.RoomSummary(this.roomId, {
      title: this.name
    });
    if (oldName !== this.name) {
      this.emit(RoomEvent.Name, this);
    }
  }

  /**
   * Update the room-tag event for the room.  The previous one is overwritten.
   * @param event - the m.tag event
   */
  addTags(event) {
    // event content looks like:
    // content: {
    //    tags: {
    //       $tagName: { $metadata: $value },
    //       $tagName: { $metadata: $value },
    //    }
    // }

    // XXX: do we need to deep copy here?
    this.tags = event.getContent().tags || {};

    // XXX: we could do a deep-comparison to see if the tags have really
    // changed - but do we want to bother?
    this.emit(RoomEvent.Tags, event, this);
  }

  /**
   * Update the account_data events for this room, overwriting events of the same type.
   * @param events - an array of account_data events to add
   */
  addAccountData(events) {
    for (const event of events) {
      if (event.getType() === "m.tag") {
        this.addTags(event);
      }
      const eventType = event.getType();
      const lastEvent = this.accountData.get(eventType);
      this.accountData.set(eventType, event);
      this.emit(RoomEvent.AccountData, event, this, lastEvent);
    }
  }

  /**
   * Access account_data event of given event type for this room
   * @param type - the type of account_data event to be accessed
   * @returns the account_data event in question
   */
  getAccountData(type) {
    return this.accountData.get(type);
  }

  /**
   * Returns whether the syncing user has permission to send a message in the room
   * @returns true if the user should be permitted to send
   *                   message events into the room.
   */
  maySendMessage() {
    return this.getMyMembership() === "join" && (this.client.isRoomEncrypted(this.roomId) ? this.currentState.maySendEvent(_event2.EventType.RoomMessageEncrypted, this.myUserId) : this.currentState.maySendEvent(_event2.EventType.RoomMessage, this.myUserId));
  }

  /**
   * Returns whether the given user has permissions to issue an invite for this room.
   * @param userId - the ID of the Matrix user to check permissions for
   * @returns true if the user should be permitted to issue invites for this room.
   */
  canInvite(userId) {
    let canInvite = this.getMyMembership() === "join";
    const powerLevelsEvent = this.currentState.getStateEvents(_event2.EventType.RoomPowerLevels, "");
    const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();
    const me = this.getMember(userId);
    if (powerLevels && me && powerLevels.invite > me.powerLevel) {
      canInvite = false;
    }
    return canInvite;
  }

  /**
   * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.
   * @returns the join_rule applied to this room
   */
  getJoinRule() {
    return this.currentState.getJoinRule();
  }

  /**
   * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.
   * @returns the history_visibility applied to this room
   */
  getHistoryVisibility() {
    return this.currentState.getHistoryVisibility();
  }

  /**
   * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.
   * @returns the history_visibility applied to this room
   */
  getGuestAccess() {
    return this.currentState.getGuestAccess();
  }

  /**
   * Returns the type of the room from the `m.room.create` event content or undefined if none is set
   * @returns the type of the room.
   */
  getType() {
    const createEvent = this.currentState.getStateEvents(_event2.EventType.RoomCreate, "");
    if (!createEvent) {
      if (!this.getTypeWarning) {
        _logger.logger.warn("[getType] Room " + this.roomId + " does not have an m.room.create event");
        this.getTypeWarning = true;
      }
      return undefined;
    }
    return createEvent.getContent()[_event2.RoomCreateTypeField];
  }

  /**
   * Returns whether the room is a space-room as defined by MSC1772.
   * @returns true if the room's type is RoomType.Space
   */
  isSpaceRoom() {
    return this.getType() === _event2.RoomType.Space;
  }

  /**
   * Returns whether the room is a call-room as defined by MSC3417.
   * @returns true if the room's type is RoomType.UnstableCall
   */
  isCallRoom() {
    return this.getType() === _event2.RoomType.UnstableCall;
  }

  /**
   * Returns whether the room is a video room.
   * @returns true if the room's type is RoomType.ElementVideo
   */
  isElementVideoRoom() {
    return this.getType() === _event2.RoomType.ElementVideo;
  }

  /**
   * Find the predecessor of this room.
   *
   * @param msc3946ProcessDynamicPredecessor - if true, look for an
   * m.room.predecessor state event and use it if found (MSC3946).
   * @returns null if this room has no predecessor. Otherwise, returns
   * the roomId, last eventId and viaServers of the predecessor room.
   *
   * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events
   * as well as m.room.create events to find predecessors.
   *
   * Note: if an m.predecessor event is used, eventId may be undefined
   * since last_known_event_id is optional.
   *
   * Note: viaServers may be undefined, and will definitely be undefined if
   * this predecessor comes from a RoomCreate event (rather than a
   * RoomPredecessor, which has the optional via_servers property).
   */
  findPredecessor(msc3946ProcessDynamicPredecessor = false) {
    const currentState = this.getLiveTimeline().getState(_eventTimeline.EventTimeline.FORWARDS);
    if (!currentState) {
      return null;
    }
    return currentState.findPredecessor(msc3946ProcessDynamicPredecessor);
  }
  roomNameGenerator(state) {
    if (this.client.roomNameGenerator) {
      const name = this.client.roomNameGenerator(this.roomId, state);
      if (name !== null) {
        return name;
      }
    }
    switch (state.type) {
      case RoomNameType.Actual:
        return state.name;
      case RoomNameType.Generated:
        switch (state.subtype) {
          case "Inviting":
            return `Inviting ${memberNamesToRoomName(state.names, state.count)}`;
          default:
            return memberNamesToRoomName(state.names, state.count);
        }
      case RoomNameType.EmptyRoom:
        if (state.oldName) {
          return `Empty room (was ${state.oldName})`;
        } else {
          return "Empty room";
        }
    }
  }

  /**
   * This is an internal method. Calculates the name of the room from the current
   * room state.
   * @param userId - The client's user ID. Used to filter room members
   * correctly.
   * @param ignoreRoomNameEvent - Return the implicit room name that we'd see if there
   * was no m.room.name event.
   * @returns The calculated room name.
   */
  calculateRoomName(userId, ignoreRoomNameEvent = false) {
    if (!ignoreRoomNameEvent) {
      // check for an alias, if any. for now, assume first alias is the
      // official one.
      const mRoomName = this.currentState.getStateEvents(_event2.EventType.RoomName, "");
      if (mRoomName?.getContent().name) {
        return this.roomNameGenerator({
          type: RoomNameType.Actual,
          name: mRoomName.getContent().name
        });
      }
    }
    const alias = this.getCanonicalAlias();
    if (alias) {
      return this.roomNameGenerator({
        type: RoomNameType.Actual,
        name: alias
      });
    }
    const joinedMemberCount = this.currentState.getJoinedMemberCount();
    const invitedMemberCount = this.currentState.getInvitedMemberCount();
    // -1 because these numbers include the syncing user
    let inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;

    // get service members (e.g. helper bots) for exclusion
    let excludedUserIds = [];
    const mFunctionalMembers = this.currentState.getStateEvents(_event2.UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, "");
    if (Array.isArray(mFunctionalMembers?.getContent().service_members)) {
      excludedUserIds = mFunctionalMembers.getContent().service_members;
    }

    // get members that are NOT ourselves and are actually in the room.
    let otherNames = [];
    if (this.summaryHeroes) {
      // if we have a summary, the member state events should be in the room state
      this.summaryHeroes.forEach(userId => {
        // filter service members
        if (excludedUserIds.includes(userId)) {
          inviteJoinCount--;
          return;
        }
        const member = this.getMember(userId);
        otherNames.push(member ? member.name : userId);
      });
    } else {
      let otherMembers = this.currentState.getMembers().filter(m => {
        return m.userId !== userId && (m.membership === "invite" || m.membership === "join");
      });
      otherMembers = otherMembers.filter(({
        userId
      }) => {
        // filter service members
        if (excludedUserIds.includes(userId)) {
          inviteJoinCount--;
          return false;
        }
        return true;
      });
      // make sure members have stable order
      otherMembers.sort((a, b) => (0, _utils.compare)(a.userId, b.userId));
      // only 5 first members, immitate summaryHeroes
      otherMembers = otherMembers.slice(0, 5);
      otherNames = otherMembers.map(m => m.name);
    }
    if (inviteJoinCount) {
      return this.roomNameGenerator({
        type: RoomNameType.Generated,
        names: otherNames,
        count: inviteJoinCount
      });
    }
    const myMembership = this.getMyMembership();
    // if I have created a room and invited people through
    // 3rd party invites
    if (myMembership == "join") {
      const thirdPartyInvites = this.currentState.getStateEvents(_event2.EventType.RoomThirdPartyInvite);
      if (thirdPartyInvites?.length) {
        const thirdPartyNames = thirdPartyInvites.map(i => {
          return i.getContent().display_name;
        });
        return this.roomNameGenerator({
          type: RoomNameType.Generated,
          subtype: "Inviting",
          names: thirdPartyNames,
          count: thirdPartyNames.length + 1
        });
      }
    }

    // let's try to figure out who was here before
    let leftNames = otherNames;
    // if we didn't have heroes, try finding them in the room state
    if (!leftNames.length) {
      leftNames = this.currentState.getMembers().filter(m => {
        return m.userId !== userId && m.membership !== "invite" && m.membership !== "join";
      }).map(m => m.name);
    }
    let oldName;
    if (leftNames.length) {
      oldName = this.roomNameGenerator({
        type: RoomNameType.Generated,
        names: leftNames,
        count: leftNames.length + 1
      });
    }
    return this.roomNameGenerator({
      type: RoomNameType.EmptyRoom,
      oldName
    });
  }

  /**
   * When we receive a new visibility change event:
   *
   * - store this visibility change alongside the timeline, in case we
   *   later need to apply it to an event that we haven't received yet;
   * - if we have already received the event whose visibility has changed,
   *   patch it to reflect the visibility change and inform listeners.
   */
  applyNewVisibilityEvent(event) {
    const visibilityChange = event.asVisibilityChange();
    if (!visibilityChange) {
      // The event is ill-formed.
      return;
    }

    // Ignore visibility change events that are not emitted by moderators.
    const userId = event.getSender();
    if (!userId) {
      return;
    }
    const isPowerSufficient = _event2.EVENT_VISIBILITY_CHANGE_TYPE.name && this.currentState.maySendStateEvent(_event2.EVENT_VISIBILITY_CHANGE_TYPE.name, userId) || _event2.EVENT_VISIBILITY_CHANGE_TYPE.altName && this.currentState.maySendStateEvent(_event2.EVENT_VISIBILITY_CHANGE_TYPE.altName, userId);
    if (!isPowerSufficient) {
      // Powerlevel is insufficient.
      return;
    }

    // Record this change in visibility.
    // If the event is not in our timeline and we only receive it later,
    // we may need to apply the visibility change at a later date.

    const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId);
    if (visibilityEventsOnOriginalEvent) {
      // It would be tempting to simply erase the latest visibility change
      // but we need to record all of the changes in case the latest change
      // is ever redacted.
      //
      // In practice, linear scans through `visibilityEvents` should be fast.
      // However, to protect against a potential DoS attack, we limit the
      // number of iterations in this loop.
      let index = visibilityEventsOnOriginalEvent.length - 1;
      const min = Math.max(0, visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH);
      for (; index >= min; --index) {
        const target = visibilityEventsOnOriginalEvent[index];
        if (target.getTs() < event.getTs()) {
          break;
        }
      }
      if (index === -1) {
        visibilityEventsOnOriginalEvent.unshift(event);
      } else {
        visibilityEventsOnOriginalEvent.splice(index + 1, 0, event);
      }
    } else {
      this.visibilityEvents.set(visibilityChange.eventId, [event]);
    }

    // Finally, let's check if the event is already in our timeline.
    // If so, we need to patch it and inform listeners.

    const originalEvent = this.findEventById(visibilityChange.eventId);
    if (!originalEvent) {
      return;
    }
    originalEvent.applyVisibilityEvent(visibilityChange);
  }
  redactVisibilityChangeEvent(event) {
    // Sanity checks.
    if (!event.isVisibilityEvent) {
      throw new Error("expected a visibility change event");
    }
    const relation = event.getRelation();
    const originalEventId = relation?.event_id;
    const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId);
    if (!visibilityEventsOnOriginalEvent) {
      // No visibility changes on the original event.
      // In particular, this change event was not recorded,
      // most likely because it was ill-formed.
      return;
    }
    const index = visibilityEventsOnOriginalEvent.findIndex(change => change.getId() === event.getId());
    if (index === -1) {
      // This change event was not recorded, most likely because
      // it was ill-formed.
      return;
    }
    // Remove visibility change.
    visibilityEventsOnOriginalEvent.splice(index, 1);

    // If we removed the latest visibility change event, propagate changes.
    if (index === visibilityEventsOnOriginalEvent.length) {
      const originalEvent = this.findEventById(originalEventId);
      if (!originalEvent) {
        return;
      }
      if (index === 0) {
        // We have just removed the only visibility change event.
        this.visibilityEvents.delete(originalEventId);
        originalEvent.applyVisibilityEvent();
      } else {
        const newEvent = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1];
        const newVisibility = newEvent.asVisibilityChange();
        if (!newVisibility) {
          // Event is ill-formed.
          // This breaks our invariant.
          throw new Error("at this stage, visibility changes should be well-formed");
        }
        originalEvent.applyVisibilityEvent(newVisibility);
      }
    }
  }

  /**
   * When we receive an event whose visibility has been altered by
   * a (more recent) visibility change event, patch the event in
   * place so that clients now not to display it.
   *
   * @param event - Any matrix event. If this event has at least one a
   * pending visibility change event, apply the latest visibility
   * change event.
   */
  applyPendingVisibilityEvents(event) {
    const visibilityEvents = this.visibilityEvents.get(event.getId());
    if (!visibilityEvents || visibilityEvents.length == 0) {
      // No pending visibility change in store.
      return;
    }
    const visibilityEvent = visibilityEvents[visibilityEvents.length - 1];
    const visibilityChange = visibilityEvent.asVisibilityChange();
    if (!visibilityChange) {
      return;
    }
    if (visibilityChange.visible) {
      // Events are visible by default, no need to apply a visibility change.
      // Note that we need to keep the visibility changes in `visibilityEvents`,
      // in case we later fetch an older visibility change event that is superseded
      // by `visibilityChange`.
    }
    if (visibilityEvent.getTs() < event.getTs()) {
      // Something is wrong, the visibility change cannot happen before the
      // event. Presumably an ill-formed event.
      return;
    }
    event.applyVisibilityEvent(visibilityChange);
  }

  /**
   * Find when a client has gained thread capabilities by inspecting the oldest
   * threaded receipt
   * @returns the timestamp of the oldest threaded receipt
   */
  getOldestThreadedReceiptTs() {
    return this.oldestThreadedReceiptTs;
  }

  /**
   * Returns the most recent unthreaded receipt for a given user
   * @param userId - the MxID of the User
   * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled
   * or a user chooses to use private read receipts (or we have simply not received
   * a receipt from this user yet).
   */
  getLastUnthreadedReceiptFor(userId) {
    return this.unthreadedReceipts.get(userId);
  }

  /**
   * This issue should also be addressed on synapse's side and is tracked as part
   * of https://github.com/matrix-org/synapse/issues/14837
   *
   *
   * We consider a room  fully read if the current user has sent
   * the last event in the live timeline of that context and if the read receipt
   * we have on record matches.
   * This also detects all unread threads and applies the same logic to those
   * contexts
   */
  fixupNotifications(userId) {
    super.fixupNotifications(userId);
    const unreadThreads = this.getThreads().filter(thread => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0);
    for (const thread of unreadThreads) {
      thread.fixupNotifications(userId);
    }
  }
}

// a map from current event status to a list of allowed next statuses
exports.Room = Room;
const ALLOWED_TRANSITIONS = {
  [_eventStatus.EventStatus.ENCRYPTING]: [_eventStatus.EventStatus.SENDING, _eventStatus.EventStatus.NOT_SENT, _eventStatus.EventStatus.CANCELLED],
  [_eventStatus.EventStatus.SENDING]: [_eventStatus.EventStatus.ENCRYPTING, _eventStatus.EventStatus.QUEUED, _eventStatus.EventStatus.NOT_SENT, _eventStatus.EventStatus.SENT],
  [_eventStatus.EventStatus.QUEUED]: [_eventStatus.EventStatus.SENDING, _eventStatus.EventStatus.NOT_SENT, _eventStatus.EventStatus.CANCELLED],
  [_eventStatus.EventStatus.SENT]: [],
  [_eventStatus.EventStatus.NOT_SENT]: [_eventStatus.EventStatus.SENDING, _eventStatus.EventStatus.QUEUED, _eventStatus.EventStatus.CANCELLED],
  [_eventStatus.EventStatus.CANCELLED]: []
};
let RoomNameType = /*#__PURE__*/function (RoomNameType) {
  RoomNameType[RoomNameType["EmptyRoom"] = 0] = "EmptyRoom";
  RoomNameType[RoomNameType["Generated"] = 1] = "Generated";
  RoomNameType[RoomNameType["Actual"] = 2] = "Actual";
  return RoomNameType;
}({});
exports.RoomNameType = RoomNameType;
// Can be overriden by IMatrixClientCreateOpts::memberNamesToRoomNameFn
function memberNamesToRoomName(names, count) {
  const countWithoutMe = count - 1;
  if (!names.length) {
    return "Empty room";
  } else if (names.length === 1 && countWithoutMe <= 1) {
    return names[0];
  } else if (names.length === 2 && countWithoutMe <= 2) {
    return `${names[0]} and ${names[1]}`;
  } else {
    const plural = countWithoutMe > 1;
    if (plural) {
      return `${names[0]} and ${countWithoutMe} others`;
    } else {
      return `${names[0]} and 1 other`;
    }
  }
}