1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
use js_sys::{Object, Reflect, Uint8Array};
use lib0::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::rc::Rc;
use std::sync::Arc;
use wasm_bindgen::__rt::{Ref, RefMut};
use wasm_bindgen::convert::IntoWasmAbi;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use yrs::block::{ClientID, ItemContent, Prelim, Unused};
use yrs::types::array::ArrayEvent;
use yrs::types::map::MapEvent;
use yrs::types::text::{ChangeKind, Diff, TextEvent, YChange};
use yrs::types::xml::{XmlEvent, XmlTextEvent};
use yrs::types::{
    Attrs, Branch, BranchPtr, Change, DeepEventsSubscription, DeepObservable, Delta, EntryChange,
    Event, Events, Path, PathSegment, ToJson, TypeRefs, Value, TYPE_REFS_ARRAY, TYPE_REFS_DOC,
    TYPE_REFS_MAP, TYPE_REFS_TEXT, TYPE_REFS_XML_ELEMENT, TYPE_REFS_XML_FRAGMENT,
    TYPE_REFS_XML_TEXT,
};
use yrs::undo::{EventKind, UndoEventSubscription};
use yrs::updates::decoder::{Decode, DecoderV1};
use yrs::updates::encoder::{Encode, Encoder, EncoderV1, EncoderV2};
use yrs::{
    Array, ArrayRef, Assoc, DeleteSet, DestroySubscription, Doc, GetString, IndexScope, Map,
    MapRef, Observable, Offset, OffsetKind, Options, Origin, ReadTxn, Snapshot, StateVector,
    StickyIndex, Store, SubdocsEvent, SubdocsEventIter, SubdocsSubscription, Subscription, Text,
    TextRef, Transact, Transaction, TransactionCleanupEvent, TransactionCleanupSubscription,
    TransactionMut, UndoManager, Update, UpdateSubscription, Xml, XmlElementPrelim, XmlElementRef,
    XmlFragment, XmlFragmentRef, XmlNode, XmlTextPrelim, XmlTextRef, ID,
};

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

/// When called will call console log errors whenever internal panic is called from within
/// WebAssembly module.
#[wasm_bindgen(js_name = setPanicHook)]
pub fn set_panic_hook() {
    // When the `console_error_panic_hook` feature is enabled, we can call the
    // `set_panic_hook` function at least once during initialization, and then
    // we will get better error messages if our code ever panics.
    //
    // For more details see
    // https://github.com/rustwasm/console_error_panic_hook#readme
    #[cfg(feature = "console_error_panic_hook")]
    console_error_panic_hook::set_once();
}

/// A ywasm document type. Documents are most important units of collaborative resources management.
/// All shared collections live within a scope of their corresponding documents. All updates are
/// generated on per document basis (rather than individual shared type). All operations on shared
/// collections happen via [YTransaction], which lifetime is also bound to a document.
///
/// Document manages so called root types, which are top-level shared types definitions (as opposed
/// to recursively nested types).
///
/// A basic workflow sample:
///
/// ```javascript
/// import YDoc from 'ywasm'
///
/// const doc = new YDoc()
/// const txn = doc.beginTransaction()
/// try {
///     const text = txn.getText('name')
///     text.push(txn, 'hello world')
///     const output = text.toString(txn)
///     console.log(output)
/// } finally {
///     txn.free()
/// }
/// ```
#[wasm_bindgen]
pub struct YDoc(Doc);

impl AsRef<Doc> for YDoc {
    fn as_ref(&self) -> &Doc {
        &self.0
    }
}

impl From<Doc> for YDoc {
    fn from(doc: Doc) -> Self {
        YDoc(doc)
    }
}

#[wasm_bindgen]
impl YDoc {
    /// Creates a new ywasm document. If `id` parameter was passed it will be used as this document
    /// globally unique identifier (it's up to caller to ensure that requirement). Otherwise it will
    /// be assigned a randomly generated number.
    #[wasm_bindgen(constructor)]
    pub fn new(options: &JsValue) -> Self {
        let options = parse_options(options);
        Doc::with_options(options).into()
    }

    /// Returns a parent document of this document or null if current document is not sub-document.
    #[wasm_bindgen(method, getter, js_name = parentDoc)]
    pub fn parent_doc(&self) -> Option<YDoc> {
        let doc = self.0.parent_doc()?;
        Some(YDoc(doc))
    }

    /// Gets unique peer identifier of this `YDoc` instance.
    #[wasm_bindgen(method, getter)]
    pub fn id(&self) -> f64 {
        self.as_ref().client_id() as f64
    }

    /// Gets globally unique identifier of this `YDoc` instance.
    #[wasm_bindgen(method, getter)]
    pub fn guid(&self) -> String {
        self.as_ref().options().guid.to_string()
    }

    #[wasm_bindgen(method, getter, js_name = shouldLoad)]
    pub fn should_load(&self) -> bool {
        self.as_ref().options().should_load
    }

    #[wasm_bindgen(method, getter, js_name = autoLoad)]
    pub fn auto_load(&self) -> bool {
        self.as_ref().options().auto_load
    }

    /// Returns a new transaction for this document. Ywasm shared data types execute their
    /// operations in a context of a given transaction. Each document can have only one active
    /// transaction at the time - subsequent attempts will cause exception to be thrown.
    ///
    /// Transactions started with `doc.beginTransaction` can be released using `transaction.free`
    /// method.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// // helper function used to simplify transaction
    /// // create/release cycle
    /// YDoc.prototype.transact = callback => {
    ///     const txn = this.readTransaction()
    ///     try {
    ///         return callback(txn)
    ///     } finally {
    ///         txn.free()
    ///     }
    /// }
    ///
    /// const doc = new YDoc()
    /// const text = doc.getText('name')
    /// doc.transact(txn => text.insert(txn, 0, 'hello world'))
    /// ```
    #[wasm_bindgen(method, js_name = readTransaction)]
    pub fn read_transaction(&mut self) -> YTransaction {
        YTransaction::from(self.as_ref().transact())
    }

    /// Returns a new transaction for this document. Ywasm shared data types execute their
    /// operations in a context of a given transaction. Each document can have only one active
    /// transaction at the time - subsequent attempts will cause exception to be thrown.
    ///
    /// Transactions started with `doc.beginTransaction` can be released using `transaction.free`
    /// method.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// // helper function used to simplify transaction
    /// // create/release cycle
    /// YDoc.prototype.transact = callback => {
    ///     const txn = this.writeTransaction()
    ///     try {
    ///         return callback(txn)
    ///     } finally {
    ///         txn.free()
    ///     }
    /// }
    ///
    /// const doc = new YDoc()
    /// const text = doc.getText('name')
    /// doc.transact(txn => text.insert(txn, 0, 'hello world'))
    /// ```
    #[wasm_bindgen(method, js_name = writeTransaction)]
    pub fn write_transaction(&mut self, origin: JsValue) -> YTransaction {
        if origin.is_null() || origin.is_undefined() {
            YTransaction::from(self.as_ref().transact_mut())
        } else {
            let origin: Origin = JsValueWrapper(origin).into();
            YTransaction::from(self.as_ref().transact_mut_with(origin))
        }
    }

    /// Returns a `YText` shared data type, that's accessible for subsequent accesses using given
    /// `name`.
    ///
    /// If there was no instance with this name before, it will be created and then returned.
    ///
    /// If there was an instance with this name, but it was of different type, it will be projected
    /// onto `YText` instance.
    #[wasm_bindgen(method, js_name = getText)]
    pub fn get_text(&mut self, name: &str) -> YText {
        self.as_ref().get_or_insert_text(name).into()
    }

    /// Returns a `YArray` shared data type, that's accessible for subsequent accesses using given
    /// `name`.
    ///
    /// If there was no instance with this name before, it will be created and then returned.
    ///
    /// If there was an instance with this name, but it was of different type, it will be projected
    /// onto `YArray` instance.
    #[wasm_bindgen(method, js_name = getArray)]
    pub fn get_array(&mut self, name: &str) -> YArray {
        self.as_ref().get_or_insert_array(name).into()
    }

    /// Returns a `YMap` shared data type, that's accessible for subsequent accesses using given
    /// `name`.
    ///
    /// If there was no instance with this name before, it will be created and then returned.
    ///
    /// If there was an instance with this name, but it was of different type, it will be projected
    /// onto `YMap` instance.
    #[wasm_bindgen(method, js_name = getMap)]
    pub fn get_map(&mut self, name: &str) -> YMap {
        self.as_ref().get_or_insert_map(name).into()
    }

    /// Returns a `YXmlFragment` shared data type, that's accessible for subsequent accesses using
    /// given `name`.
    ///
    /// If there was no instance with this name before, it will be created and then returned.
    ///
    /// If there was an instance with this name, but it was of different type, it will be projected
    /// onto `YXmlFragment` instance.
    #[wasm_bindgen(method, js_name = getXmlFragment)]
    pub fn get_xml_fragment(&mut self, name: &str) -> YXmlFragment {
        YXmlFragment(self.as_ref().get_or_insert_xml_fragment(name))
    }

    /// Returns a `YXmlElement` shared data type, that's accessible for subsequent accesses using
    /// given `name`.
    ///
    /// If there was no instance with this name before, it will be created and then returned.
    ///
    /// If there was an instance with this name, but it was of different type, it will be projected
    /// onto `YXmlElement` instance.
    #[wasm_bindgen(method, js_name = getXmlElement)]
    pub fn get_xml_element(&mut self, name: &str) -> YXmlElement {
        YXmlElement(self.as_ref().get_or_insert_xml_element(name))
    }

    /// Returns a `YXmlText` shared data type, that's accessible for subsequent accesses using given
    /// `name`.
    ///
    /// If there was no instance with this name before, it will be created and then returned.
    ///
    /// If there was an instance with this name, but it was of different type, it will be projected
    /// onto `YXmlText` instance.
    #[wasm_bindgen(method, js_name = getXmlText)]
    pub fn get_xml_text(&mut self, name: &str) -> YXmlText {
        YXmlText(self.as_ref().get_or_insert_xml_text(name))
    }

    /// Subscribes given function to be called any time, a remote update is being applied to this
    /// document. Function takes an `Uint8Array` as a parameter which contains a lib0 v1 encoded
    /// update.
    ///
    /// Returns an observer, which can be freed in order to unsubscribe this callback.
    #[wasm_bindgen(method, js_name = onUpdate)]
    pub fn on_update(&mut self, f: js_sys::Function) -> YUpdateObserver {
        self.as_ref()
            .observe_update_v1(move |_, e| {
                let arg = Uint8Array::from(e.update.as_slice());
                f.call1(&JsValue::UNDEFINED, &arg).unwrap();
            })
            .unwrap()
            .into()
    }

    /// Subscribes given function to be called any time, a remote update is being applied to this
    /// document. Function takes an `Uint8Array` as a parameter which contains a lib0 v2 encoded
    /// update.
    ///
    /// Returns an observer, which can be freed in order to unsubscribe this callback.
    #[wasm_bindgen(method, js_name = onUpdateV2)]
    pub fn on_update_v2(&mut self, f: js_sys::Function) -> YUpdateObserver {
        self.as_ref()
            .observe_update_v2(move |_, e| {
                let arg = Uint8Array::from(e.update.as_slice());
                f.call1(&JsValue::UNDEFINED, &arg).unwrap();
            })
            .unwrap()
            .into()
    }

    /// Subscribes given function to be called, whenever a transaction created by this document is
    /// being committed.
    ///
    /// Returns an observer, which can be freed in order to unsubscribe this callback.
    #[wasm_bindgen(method, js_name = onAfterTransaction)]
    pub fn on_after_transaction(&mut self, f: js_sys::Function) -> YAfterTransactionObserver {
        self.as_ref()
            .observe_transaction_cleanup(move |_, e| {
                let arg: JsValue = YAfterTransactionEvent::new(e).into();
                f.call1(&JsValue::UNDEFINED, &arg).unwrap();
            })
            .unwrap()
            .into()
    }

    /// Subscribes given function to be called, whenever a subdocuments are being added, removed
    /// or loaded as children of a current document.
    ///
    /// Returns an observer, which can be freed in order to unsubscribe this callback.
    #[wasm_bindgen(method, js_name = onSubdocs)]
    pub fn on_subdocs(&mut self, f: js_sys::Function) -> YSubdocsObserver {
        self.as_ref()
            .observe_subdocs(move |_, e| {
                let arg: JsValue = YSubdocsEvent::new(e).into();
                f.call1(&JsValue::UNDEFINED, &arg).unwrap();
            })
            .unwrap()
            .into()
    }

    /// Subscribes given function to be called, whenever current document is being destroyed.
    ///
    /// Returns an observer, which can be freed in order to unsubscribe this callback.
    #[wasm_bindgen(method, js_name = onDestroy)]
    pub fn on_destroy(&mut self, f: js_sys::Function) -> YDestroyObserver {
        self.as_ref()
            .observe_destroy(move |_, e| {
                let arg: JsValue = YDoc::from(e.clone()).into();
                f.call1(&JsValue::UNDEFINED, &arg).unwrap();
            })
            .unwrap()
            .into()
    }

    /// Notify the parent document that you request to load data into this subdocument
    /// (if it is a subdocument).
    #[wasm_bindgen(method, js_name = load)]
    pub fn load(&self, parent_txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(parent_txn) {
            self.0.load(txn)
        } else {
            if let Some(parent) = self.0.parent_doc() {
                let mut txn = parent.transact_mut();
                self.0.load(&mut txn);
            }
        }
    }

    /// Emit `onDestroy` event and unregister all event handlers.
    #[wasm_bindgen(method, js_name = destroy)]
    pub fn destroy(&mut self, parent_txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(parent_txn) {
            self.0.destroy(txn)
        } else {
            if let Some(parent) = self.0.parent_doc() {
                let mut txn = parent.transact_mut();
                self.0.destroy(&mut txn);
            }
        }
    }

    /// Returns a list of sub-documents existings within the scope of this document.
    #[wasm_bindgen(method, js_name = getSubdocs)]
    pub fn subdocs(&self, txn: &ImplicitTransaction) -> js_sys::Array {
        let doc = self.as_ref();
        let buf = js_sys::Array::new();
        if let Some(txn) = get_txn(txn) {
            for doc in txn.subdocs() {
                let doc = YDoc::from(doc.clone());
                buf.push(&doc.into());
            }
        } else {
            let txn = doc.transact();
            for doc in txn.subdocs() {
                let doc = YDoc::from(doc.clone());
                buf.push(&doc.into());
            }
        }
        buf
    }

    /// Returns a list of unique identifiers of the sub-documents existings within the scope of
    /// this document.
    #[wasm_bindgen(method, js_name = getSubdocGuids)]
    pub fn subdoc_guids(&self, txn: &ImplicitTransaction) -> js_sys::Set {
        let doc = self.as_ref();
        let buf = js_sys::Set::new(&js_sys::Array::new());
        if let Some(txn) = get_txn(txn) {
            for uid in txn.subdoc_guids() {
                let str = uid.to_string();
                buf.add(&str.into());
            }
        } else {
            let txn = doc.transact();
            for uid in txn.subdoc_guids() {
                let str = uid.to_string();
                buf.add(&str.into());
            }
        }
        buf
    }
}

fn parse_options(js: &JsValue) -> Options {
    let mut options = Options::default();
    options.offset_kind = OffsetKind::Utf16;
    if js.is_object() {
        if let Some(client_id) = js_sys::Reflect::get(js, &JsValue::from_str("clientID"))
            .ok()
            .and_then(|v| v.as_f64())
        {
            options.client_id = client_id as u32 as ClientID;
        }

        if let Some(guid) = js_sys::Reflect::get(js, &JsValue::from_str("guid"))
            .ok()
            .and_then(|v| v.as_string())
        {
            options.guid = guid.into();
        }

        if let Some(collection_id) = js_sys::Reflect::get(js, &JsValue::from_str("collectionid"))
            .ok()
            .and_then(|v| v.as_string())
        {
            options.collection_id = Some(collection_id);
        }

        if let Some(gc) = js_sys::Reflect::get(js, &JsValue::from_str("gc"))
            .ok()
            .and_then(|v| v.as_bool())
        {
            options.skip_gc = !gc;
        }

        if let Some(auto_load) = js_sys::Reflect::get(js, &JsValue::from_str("autoLoad"))
            .ok()
            .and_then(|v| v.as_bool())
        {
            options.auto_load = auto_load;
        }

        if let Some(should_load) = js_sys::Reflect::get(js, &JsValue::from_str("shouldLoad"))
            .ok()
            .and_then(|v| v.as_bool())
        {
            options.should_load = should_load;
        }
    }

    options
}

/// Encodes a state vector of a given ywasm document into its binary representation using lib0 v1
/// encoding. State vector is a compact representation of updates performed on a given document and
/// can be used by `encode_state_as_update` on remote peer to generate a delta update payload to
/// synchronize changes between peers.
///
/// Example:
///
/// ```javascript
/// import {YDoc, encodeStateVector, encodeStateAsUpdate, applyUpdate} from 'ywasm'
///
/// /// document on machine A
/// const localDoc = new YDoc()
/// const localSV = encodeStateVector(localDoc)
///
/// // document on machine B
/// const remoteDoc = new YDoc()
/// const remoteDelta = encodeStateAsUpdate(remoteDoc, localSV)
///
/// applyUpdate(localDoc, remoteDelta)
/// ```
#[wasm_bindgen(method, js_name = encodeStateVector)]
pub fn encode_state_vector(doc: &mut YDoc) -> Uint8Array {
    doc.read_transaction().state_vector_v1()
}

/// Returns a string dump representation of a given `update` encoded using lib0 v1 encoding.
#[wasm_bindgen(method, js_name = debugUpdateV1)]
pub fn debug_update_v1(update: Uint8Array) -> Result<String, JsValue> {
    let update: Vec<u8> = update.to_vec();
    let mut decoder = DecoderV1::from(update.as_slice());
    match Update::decode(&mut decoder) {
        Ok(update) => Ok(format!("{:#?}", update)),
        Err(e) => Err(JsValue::from(e.to_string())),
    }
}

/// Returns a string dump representation of a given `update` encoded using lib0 v2 encoding.
#[wasm_bindgen(method, js_name = debugUpdateV2)]
pub fn debug_update_v2(update: Uint8Array) -> Result<String, JsValue> {
    let mut update: Vec<u8> = update.to_vec();
    match Update::decode_v2(update.as_mut_slice()) {
        Ok(update) => Ok(format!("{:#?}", update)),
        Err(e) => Err(JsValue::from(e.to_string())),
    }
}

/// Encodes all updates that have happened since a given version `vector` into a compact delta
/// representation using lib0 v1 encoding. If `vector` parameter has not been provided, generated
/// delta payload will contain all changes of a current ywasm document, working effectivelly as its
/// state snapshot.
///
/// Example:
///
/// ```javascript
/// import {YDoc, encodeStateVector, encodeStateAsUpdate, applyUpdate} from 'ywasm'
///
/// /// document on machine A
/// const localDoc = new YDoc()
/// const localSV = encodeStateVector(localDoc)
///
/// // document on machine B
/// const remoteDoc = new YDoc()
/// const remoteDelta = encodeStateAsUpdate(remoteDoc, localSV)
///
/// applyUpdate(localDoc, remoteDelta)
/// ```
#[wasm_bindgen(method, js_name = encodeStateAsUpdate)]
pub fn encode_state_as_update(
    doc: &mut YDoc,
    vector: Option<Uint8Array>,
) -> Result<Uint8Array, JsValue> {
    doc.read_transaction().diff_v1(vector)
}

/// Encodes all updates that have happened since a given version `vector` into a compact delta
/// representation using lib0 v2 encoding. If `vector` parameter has not been provided, generated
/// delta payload will contain all changes of a current ywasm document, working effectivelly as its
/// state snapshot.
///
/// Example:
///
/// ```javascript
/// import {YDoc, encodeStateVector, encodeStateAsUpdate, applyUpdate} from 'ywasm'
///
/// /// document on machine A
/// const localDoc = new YDoc()
/// const localSV = encodeStateVector(localDoc)
///
/// // document on machine B
/// const remoteDoc = new YDoc()
/// const remoteDelta = encodeStateAsUpdateV2(remoteDoc, localSV)
///
/// applyUpdate(localDoc, remoteDelta)
/// ```
#[wasm_bindgen(method, catch, js_name = encodeStateAsUpdateV2)]
pub fn encode_state_as_update_v2(
    doc: &mut YDoc,
    vector: Option<Uint8Array>,
) -> Result<Uint8Array, JsValue> {
    doc.read_transaction().diff_v2(vector)
}

/// Applies delta update generated by the remote document replica to a current document. This
/// method assumes that a payload maintains lib0 v1 encoding format.
///
/// Example:
///
/// ```javascript
/// import {YDoc, encodeStateVector, encodeStateAsUpdate, applyUpdate} from 'ywasm'
///
/// /// document on machine A
/// const localDoc = new YDoc()
/// const localSV = encodeStateVector(localDoc)
///
/// // document on machine B
/// const remoteDoc = new YDoc()
/// const remoteDelta = encodeStateAsUpdate(remoteDoc, localSV)
///
/// applyUpdateV2(localDoc, remoteDelta)
/// ```
#[wasm_bindgen(method, catch, js_name = applyUpdate)]
pub fn apply_update(doc: &mut YDoc, diff: Uint8Array, origin: JsValue) -> Result<(), JsValue> {
    doc.write_transaction(origin).apply_v1(diff)
}

/// Applies delta update generated by the remote document replica to a current document. This
/// method assumes that a payload maintains lib0 v2 encoding format.
///
/// Example:
///
/// ```javascript
/// import {YDoc, encodeStateVector, encodeStateAsUpdate, applyUpdate} from 'ywasm'
///
/// /// document on machine A
/// const localDoc = new YDoc()
/// const localSV = encodeStateVector(localDoc)
///
/// // document on machine B
/// const remoteDoc = new YDoc()
/// const remoteDelta = encodeStateAsUpdateV2(remoteDoc, localSV)
///
/// applyUpdateV2(localDoc, remoteDelta)
/// ```
#[wasm_bindgen(method, catch, js_name = applyUpdateV2)]
pub fn apply_update_v2(doc: &mut YDoc, diff: Uint8Array, origin: JsValue) -> Result<(), JsValue> {
    doc.write_transaction(origin).apply_v2(diff)
}

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(typescript_type = "YTransaction | null = null")]
    pub type ImplicitTransaction;
}

fn get_txn_mut<'a>(txn: &'a ImplicitTransaction) -> Option<&'a mut TransactionMut<'static>> {
    use wasm_bindgen::convert::RefMutFromWasmAbi;

    let ptr = unwrap_txn_ptr(txn).unwrap()?;
    let mut txn: RefMut<'a, YTransaction> = unsafe { YTransaction::ref_mut_from_abi(ptr) };
    let txn = txn
        .try_mut()
        .expect("Passed read-only transaction, where read-write one was expected");

    /*
      This should be safe. We never call this function more than once, per wasm_bindgen method,
      it's never escaping the context of wasm_bindgen method and ywasm is not used in
      multithreaded code. All we need to check is if YTransaction instance hasn't been already
      borrowed by another wasm_bindgen method, which is what `YTransaction::ref_mut_from_abi`
      above verifies.
    */
    Some(unsafe { std::mem::transmute(txn) })
}

fn get_txn<'a>(txn: &'a ImplicitTransaction) -> Option<&'a YTransaction> {
    use wasm_bindgen::convert::RefFromWasmAbi;

    let ptr = unwrap_txn_ptr(txn).unwrap()?;
    let txn: Ref<'a, YTransaction> = unsafe { YTransaction::ref_from_abi(ptr) };
    let txn: &YTransaction = txn.deref();

    /*
      This should be safe. We never call this function more than once, per wasm_bindgen method,
      it's never escaping the context of wasm_bindgen method and ywasm is not used in
      multithreaded code. All we need to check is if YTransaction instance hasn't been already
      borrowed by another wasm_bindgen method, which is what `YTransaction::ref_from_abi`
      above verifies.
    */
    Some(unsafe { std::mem::transmute(txn) })
}

fn unwrap_txn_ptr(value: &ImplicitTransaction) -> Result<Option<u32>, JsValue> {
    let js: &JsValue = value.as_ref();
    if js.is_undefined() || js.is_null() {
        Ok(None)
    } else {
        let ctor_name = Object::get_prototype_of(js).constructor().name();
        if ctor_name == "YTransaction" {
            let ptr = Reflect::get(js, &JsValue::from_str("ptr"))?;
            Ok(Some(ptr.as_f64().ok_or(JsValue::NULL)? as u32))
        } else {
            Err(JsValue::from_str("Passed argument was not YTransaction"))
        }
    }
}

/// A transaction that serves as a proxy to document block store. Ywasm shared data types execute
/// their operations in a context of a given transaction. Each document can have only one active
/// transaction at the time - subsequent attempts will cause exception to be thrown.
///
/// Transactions started with `doc.beginTransaction` can be released using `transaction.free`
/// method.
///
/// Example:
///
/// ```javascript
/// import YDoc from 'ywasm'
///
/// // helper function used to simplify transaction
/// // create/release cycle
/// YDoc.prototype.transact = callback => {
///     const txn = this.beginTransaction()
///     try {
///         return callback(txn)
///     } finally {
///         txn.free()
///     }
/// }
///
/// const doc = new YDoc()
/// const text = doc.getText('name')
/// doc.transact(txn => text.insert(txn, 0, 'hello world'))
/// ```
#[wasm_bindgen]
pub struct YTransaction(InnerTxn);

enum InnerTxn {
    ReadOnly(ManuallyDrop<Transaction<'static>>),
    ReadWrite(ManuallyDrop<TransactionMut<'static>>),
}

impl YTransaction {
    fn try_mut(&mut self) -> Option<&mut TransactionMut<'static>> {
        match &mut self.0 {
            InnerTxn::ReadOnly(_) => None,
            InnerTxn::ReadWrite(txn) => Some(txn),
        }
    }
}

impl Drop for InnerTxn {
    fn drop(&mut self) {
        match self {
            InnerTxn::ReadOnly(txn) => unsafe { ManuallyDrop::drop(txn) },
            InnerTxn::ReadWrite(txn) => unsafe { ManuallyDrop::drop(txn) },
        }
    }
}

impl ReadTxn for YTransaction {
    fn store(&self) -> &Store {
        match &self.0 {
            InnerTxn::ReadOnly(txn) => txn.store(),
            InnerTxn::ReadWrite(txn) => txn.store(),
        }
    }
}

impl<'doc> From<Transaction<'doc>> for YTransaction {
    fn from(txn: Transaction<'doc>) -> Self {
        let txn: Transaction<'static> = unsafe { std::mem::transmute(txn) };
        YTransaction(InnerTxn::ReadOnly(ManuallyDrop::new(txn)))
    }
}

impl<'doc> From<TransactionMut<'doc>> for YTransaction {
    fn from(txn: TransactionMut<'doc>) -> Self {
        let txn: TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        YTransaction(InnerTxn::ReadWrite(ManuallyDrop::new(txn)))
    }
}

#[wasm_bindgen]
impl YTransaction {
    /// Returns true if current transaction can be used only for read operations.
    #[wasm_bindgen(method, getter, js_name = isReadOnly)]
    pub fn is_readonly(&mut self) -> bool {
        match &self.0 {
            InnerTxn::ReadOnly(_) => true,
            InnerTxn::ReadWrite(_) => false,
        }
    }

    /// Returns true if current transaction can be used only for updating the document store.
    #[wasm_bindgen(method, getter, js_name = isWriteable)]
    pub fn is_writeable(&mut self) -> bool {
        !self.is_readonly()
    }

    /// Returns true if current transaction can be used only for updating the document store.
    #[wasm_bindgen(method, getter, js_name = origin)]
    pub fn origin(&mut self) -> JsValue {
        match &self.0 {
            InnerTxn::ReadOnly(_) => JsValue::NULL,
            InnerTxn::ReadWrite(t) => {
                if let Some(o) = t.origin() {
                    let arr = unsafe { js_sys::Uint8Array::view(o.as_ref()) };
                    arr.into()
                } else {
                    JsValue::NULL
                }
            }
        }
    }

    /// Triggers a post-update series of operations without `free`ing the transaction. This includes
    /// compaction and optimization of internal representation of updates, triggering events etc.
    /// ywasm transactions are auto-committed when they are `free`d.
    #[wasm_bindgen(method, js_name = commit)]
    pub fn commit(&mut self) {
        match &mut self.0 {
            InnerTxn::ReadOnly(_) => {}
            InnerTxn::ReadWrite(txn) => txn.commit(),
        }
    }

    /// Encodes a state vector of a given transaction document into its binary representation using
    /// lib0 v1 encoding. State vector is a compact representation of updates performed on a given
    /// document and can be used by `encode_state_as_update` on remote peer to generate a delta
    /// update payload to synchronize changes between peers.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// /// document on machine A
    /// const localDoc = new YDoc()
    /// const localTxn = localDoc.beginTransaction()
    ///
    /// // document on machine B
    /// const remoteDoc = new YDoc()
    /// const remoteTxn = localDoc.beginTransaction()
    ///
    /// try {
    ///     const localSV = localTxn.stateVectorV1()
    ///     const remoteDelta = remoteTxn.diffV1(localSv)
    ///     localTxn.applyV1(remoteDelta)
    /// } finally {
    ///     localTxn.free()
    ///     remoteTxn.free()
    /// }
    /// ```
    #[wasm_bindgen(method, js_name = stateVectorV1)]
    pub fn state_vector_v1(&self) -> Uint8Array {
        let sv = self.state_vector();
        let payload = sv.encode_v1();
        Uint8Array::from(&payload[..payload.len()])
    }

    /// Encodes all updates that have happened since a given version `vector` into a compact delta
    /// representation using lib0 v1 encoding. If `vector` parameter has not been provided, generated
    /// delta payload will contain all changes of a current ywasm document, working effectively as
    /// its state snapshot.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// /// document on machine A
    /// const localDoc = new YDoc()
    /// const localTxn = localDoc.beginTransaction()
    ///
    /// // document on machine B
    /// const remoteDoc = new YDoc()
    /// const remoteTxn = localDoc.beginTransaction()
    ///
    /// try {
    ///     const localSV = localTxn.stateVectorV1()
    ///     const remoteDelta = remoteTxn.diffV1(localSv)
    ///     localTxn.applyV1(remoteDelta)
    /// } finally {
    ///     localTxn.free()
    ///     remoteTxn.free()
    /// }
    /// ```
    #[wasm_bindgen(method, catch, js_name = diffV1)]
    pub fn diff_v1(&self, vector: Option<Uint8Array>) -> Result<Uint8Array, JsValue> {
        let mut encoder = EncoderV1::new();
        let sv = if let Some(vector) = vector {
            match StateVector::decode_v1(vector.to_vec().as_slice()) {
                Ok(sv) => sv,
                Err(e) => {
                    return Err(JsValue::from(e.to_string()));
                }
            }
        } else {
            StateVector::default()
        };
        self.encode_diff(&sv, &mut encoder);
        let payload = encoder.to_vec();
        Ok(Uint8Array::from(&payload[..payload.len()]))
    }

    /// Encodes all updates that have happened since a given version `vector` into a compact delta
    /// representation using lib0 v1 encoding. If `vector` parameter has not been provided, generated
    /// delta payload will contain all changes of a current ywasm document, working effectively as
    /// its state snapshot.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// /// document on machine A
    /// const localDoc = new YDoc()
    /// const localTxn = localDoc.beginTransaction()
    ///
    /// // document on machine B
    /// const remoteDoc = new YDoc()
    /// const remoteTxn = localDoc.beginTransaction()
    ///
    /// try {
    ///     const localSV = localTxn.stateVectorV1()
    ///     const remoteDelta = remoteTxn.diffV2(localSv)
    ///     localTxn.applyV2(remoteDelta)
    /// } finally {
    ///     localTxn.free()
    ///     remoteTxn.free()
    /// }
    /// ```
    #[wasm_bindgen(method, catch, js_name = diffV2)]
    pub fn diff_v2(&self, vector: Option<Uint8Array>) -> Result<Uint8Array, JsValue> {
        let mut encoder = EncoderV2::new();
        let sv = if let Some(vector) = vector {
            match StateVector::decode_v1(vector.to_vec().as_slice()) {
                Ok(sv) => sv,
                Err(e) => {
                    return Err(JsValue::from(e.to_string()));
                }
            }
        } else {
            StateVector::default()
        };
        self.encode_diff(&sv, &mut encoder);
        let payload = encoder.to_vec();
        Ok(Uint8Array::from(&payload[..payload.len()]))
    }

    /// Applies delta update generated by the remote document replica to a current transaction's
    /// document. This method assumes that a payload maintains lib0 v1 encoding format.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// /// document on machine A
    /// const localDoc = new YDoc()
    /// const localTxn = localDoc.beginTransaction()
    ///
    /// // document on machine B
    /// const remoteDoc = new YDoc()
    /// const remoteTxn = localDoc.beginTransaction()
    ///
    /// try {
    ///     const localSV = localTxn.stateVectorV1()
    ///     const remoteDelta = remoteTxn.diffV1(localSv)
    ///     localTxn.applyV1(remoteDelta)
    /// } finally {
    ///     localTxn.free()
    ///     remoteTxn.free()
    /// }
    /// ```
    #[wasm_bindgen(method, catch, js_name = applyV1)]
    pub fn apply_v1(&mut self, diff: Uint8Array) -> Result<(), JsValue> {
        let diff: Vec<u8> = diff.to_vec();
        let mut decoder = DecoderV1::from(diff.as_slice());
        match Update::decode(&mut decoder) {
            Ok(update) => self.try_apply(update),
            Err(e) => Err(JsValue::from(e.to_string())),
        }
    }

    fn try_apply(&mut self, update: Update) -> Result<(), JsValue> {
        if let Some(txn) = self.try_mut() {
            txn.apply_update(update);
            Ok(())
        } else {
            Err(JsValue::from_str(
                "cannot apply an update using a read-only transaction",
            ))
        }
    }

    /// Applies delta update generated by the remote document replica to a current transaction's
    /// document. This method assumes that a payload maintains lib0 v2 encoding format.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// /// document on machine A
    /// const localDoc = new YDoc()
    /// const localTxn = localDoc.beginTransaction()
    ///
    /// // document on machine B
    /// const remoteDoc = new YDoc()
    /// const remoteTxn = localDoc.beginTransaction()
    ///
    /// try {
    ///     const localSV = localTxn.stateVectorV1()
    ///     const remoteDelta = remoteTxn.diffV2(localSv)
    ///     localTxn.applyV2(remoteDelta)
    /// } finally {
    ///     localTxn.free()
    ///     remoteTxn.free()
    /// }
    /// ```
    #[wasm_bindgen(method, catch, js_name = applyV2)]
    pub fn apply_v2(&mut self, diff: Uint8Array) -> Result<(), JsValue> {
        let mut diff: Vec<u8> = diff.to_vec();
        match Update::decode_v2(&mut diff) {
            Ok(update) => self.try_apply(update),
            Err(e) => Err(JsValue::from(e.to_string())),
        }
    }

    #[wasm_bindgen(method, js_name = encodeUpdate)]
    pub fn encode_update(&mut self) -> Uint8Array {
        let out = match &self.0 {
            InnerTxn::ReadOnly(_) => vec![0u8, 0u8],
            InnerTxn::ReadWrite(txn) => txn.encode_update_v1(),
        };
        Uint8Array::from(&out[..out.len()])
    }

    #[wasm_bindgen(method, js_name = encodeUpdateV2)]
    pub fn encode_update_v2(&mut self) -> Uint8Array {
        let out = match &self.0 {
            InnerTxn::ReadOnly(_) => vec![0u8, 0u8],
            InnerTxn::ReadWrite(txn) => txn.encode_update_v2(),
        };
        Uint8Array::from(&out[..out.len()])
    }
}

/// Event generated by `YArray.observe` method. Emitted during transaction commit phase.
#[wasm_bindgen]
pub struct YArrayEvent {
    inner: *const ArrayEvent,
    txn: *const TransactionMut<'static>,
    target: Option<JsValue>,
    delta: Option<JsValue>,
}

#[wasm_bindgen]
impl YArrayEvent {
    fn new<'doc>(event: &ArrayEvent, txn: &TransactionMut<'doc>) -> Self {
        let inner = event as *const ArrayEvent;
        let txn: &TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const TransactionMut<'static>;
        YArrayEvent {
            inner,
            txn,
            target: None,
            delta: None,
        }
    }

    fn inner(&self) -> &ArrayEvent {
        unsafe { self.inner.as_ref().unwrap() }
    }

    fn txn(&self) -> &TransactionMut {
        unsafe { self.txn.as_ref().unwrap() }
    }

    /// Returns a current shared type instance, that current event changes refer to.
    #[wasm_bindgen(method, getter)]
    pub fn target(&mut self) -> JsValue {
        if let Some(target) = self.target.as_ref() {
            target.clone()
        } else {
            let target: JsValue = YArray::from(self.inner().target().clone()).into();
            self.target = Some(target.clone());
            target
        }
    }

    /// Returns an array of keys and indexes creating a path from root type down to current instance
    /// of shared type (accessible via `target` getter).
    #[wasm_bindgen(method)]
    pub fn path(&self) -> JsValue {
        path_into_js(self.inner().path())
    }

    /// Returns a list of text changes made over corresponding `YArray` collection within
    /// bounds of current transaction. These changes follow a format:
    ///
    /// - { insert: any[] }
    /// - { delete: number }
    /// - { retain: number }
    #[wasm_bindgen(method, getter)]
    pub fn delta(&mut self) -> JsValue {
        if let Some(delta) = &self.delta {
            delta.clone()
        } else {
            let delta = self
                .inner()
                .delta(self.txn())
                .into_iter()
                .map(change_into_js);
            let mut result = js_sys::Array::new();
            result.extend(delta);
            let delta: JsValue = result.into();
            self.delta = Some(delta.clone());
            delta
        }
    }
}

/// Event generated by `YMap.observe` method. Emitted during transaction commit phase.
#[wasm_bindgen]
pub struct YMapEvent {
    inner: *const MapEvent,
    txn: *const TransactionMut<'static>,
    target: Option<JsValue>,
    keys: Option<JsValue>,
}

#[wasm_bindgen]
impl YMapEvent {
    fn new<'doc>(event: &MapEvent, txn: &TransactionMut<'doc>) -> Self {
        let inner = event as *const MapEvent;
        let txn: &TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const TransactionMut<'static>;
        YMapEvent {
            inner,
            txn,
            target: None,
            keys: None,
        }
    }

    fn inner(&self) -> &MapEvent {
        unsafe { self.inner.as_ref().unwrap() }
    }

    fn txn(&self) -> &TransactionMut {
        unsafe { self.txn.as_ref().unwrap() }
    }

    /// Returns a current shared type instance, that current event changes refer to.
    #[wasm_bindgen(method, getter)]
    pub fn target(&mut self) -> JsValue {
        if let Some(target) = self.target.as_ref() {
            target.clone()
        } else {
            let target: JsValue = YMap::from(self.inner().target().clone()).into();
            self.target = Some(target.clone());
            target
        }
    }

    /// Returns an array of keys and indexes creating a path from root type down to current instance
    /// of shared type (accessible via `target` getter).
    #[wasm_bindgen(method)]
    pub fn path(&self) -> JsValue {
        path_into_js(self.inner().path())
    }

    /// Returns a list of key-value changes made over corresponding `YMap` collection within
    /// bounds of current transaction. These changes follow a format:
    ///
    /// - { action: 'add'|'update'|'delete', oldValue: any|undefined, newValue: any|undefined }
    #[wasm_bindgen(method, getter)]
    pub fn keys(&mut self) -> JsValue {
        if let Some(keys) = &self.keys {
            keys.clone()
        } else {
            let keys = self.inner().keys(self.txn());
            let result = js_sys::Object::new();
            for (key, value) in keys.iter() {
                let key = JsValue::from(key.as_ref());
                let value = entry_change_into_js(value);
                js_sys::Reflect::set(&result, &key, &value).unwrap();
            }
            let keys: JsValue = result.into();
            self.keys = Some(keys.clone());
            keys
        }
    }
}

/// Event generated by `YYText.observe` method. Emitted during transaction commit phase.
#[wasm_bindgen]
pub struct YTextEvent {
    inner: *const TextEvent,
    txn: *const TransactionMut<'static>,
    target: Option<JsValue>,
    delta: Option<JsValue>,
}

#[wasm_bindgen]
impl YTextEvent {
    fn new<'doc>(event: &TextEvent, txn: &TransactionMut<'doc>) -> Self {
        let inner = event as *const TextEvent;
        let txn: &TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const TransactionMut<'static>;
        YTextEvent {
            inner,
            txn,
            target: None,
            delta: None,
        }
    }

    fn inner(&self) -> &TextEvent {
        unsafe { self.inner.as_ref().unwrap() }
    }

    fn txn(&self) -> &TransactionMut {
        unsafe { self.txn.as_ref().unwrap() }
    }

    /// Returns a current shared type instance, that current event changes refer to.
    #[wasm_bindgen(method, getter)]
    pub fn target(&mut self) -> JsValue {
        if let Some(target) = self.target.as_ref() {
            target.clone()
        } else {
            let target: JsValue = YText::from(self.inner().target().clone()).into();
            self.target = Some(target.clone());
            target
        }
    }

    /// Returns an array of keys and indexes creating a path from root type down to current instance
    /// of shared type (accessible via `target` getter).
    #[wasm_bindgen(method)]
    pub fn path(&self) -> JsValue {
        path_into_js(self.inner().path())
    }

    /// Returns a list of text changes made over corresponding `YText` collection within
    /// bounds of current transaction. These changes follow a format:
    ///
    /// - { insert: string, attributes: any|undefined }
    /// - { delete: number }
    /// - { retain: number, attributes: any|undefined }
    #[wasm_bindgen(method, getter)]
    pub fn delta(&mut self) -> JsValue {
        if let Some(delta) = &self.delta {
            delta.clone()
        } else {
            let delta = self
                .inner()
                .delta(self.txn())
                .into_iter()
                .map(ytext_delta_into_js);
            let mut result = js_sys::Array::new();
            result.extend(delta);
            let delta: JsValue = result.into();
            self.delta = Some(delta.clone());
            delta
        }
    }
}

/// Event generated by `YXmlElement.observe` method. Emitted during transaction commit phase.
#[wasm_bindgen]
pub struct YXmlEvent {
    inner: *const XmlEvent,
    txn: *const TransactionMut<'static>,
    target: Option<JsValue>,
    keys: Option<JsValue>,
    delta: Option<JsValue>,
}

#[wasm_bindgen]
impl YXmlEvent {
    fn new<'doc>(event: &XmlEvent, txn: &TransactionMut<'doc>) -> Self {
        let inner = event as *const XmlEvent;
        let txn: &TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const TransactionMut<'static>;
        YXmlEvent {
            inner,
            txn,
            target: None,
            delta: None,
            keys: None,
        }
    }

    fn inner(&self) -> &XmlEvent {
        unsafe { self.inner.as_ref().unwrap() }
    }

    fn txn(&self) -> &TransactionMut {
        unsafe { self.txn.as_ref().unwrap() }
    }

    /// Returns a current shared type instance, that current event changes refer to.
    #[wasm_bindgen(method, getter)]
    pub fn target(&mut self) -> JsValue {
        if let Some(target) = self.target.as_ref() {
            target.clone()
        } else {
            let node = self.inner().target().clone();
            let target: JsValue = xml_into_js(node);
            self.target = Some(target.clone());
            target
        }
    }

    /// Returns an array of keys and indexes creating a path from root type down to current instance
    /// of shared type (accessible via `target` getter).
    #[wasm_bindgen(method)]
    pub fn path(&self) -> JsValue {
        path_into_js(self.inner().path())
    }

    /// Returns a list of attribute changes made over corresponding `YXmlText` collection within
    /// bounds of current transaction. These changes follow a format:
    ///
    /// - { action: 'add'|'update'|'delete', oldValue: string|undefined, newValue: string|undefined }
    #[wasm_bindgen(method, getter)]
    pub fn keys(&mut self) -> JsValue {
        if let Some(keys) = &self.keys {
            keys.clone()
        } else {
            let keys = self.inner().keys(self.txn());
            let result = js_sys::Object::new();
            for (key, value) in keys.iter() {
                let key = JsValue::from(key.as_ref());
                let value = entry_change_into_js(value);
                js_sys::Reflect::set(&result, &key, &value).unwrap();
            }
            let keys: JsValue = result.into();
            self.keys = Some(keys.clone());
            keys
        }
    }

    /// Returns a list of XML child node changes made over corresponding `YXmlElement` collection
    /// within bounds of current transaction. These changes follow a format:
    ///
    /// - { insert: (YXmlText|YXmlElement)[] }
    /// - { delete: number }
    /// - { retain: number }
    #[wasm_bindgen(method, getter)]
    pub fn delta(&mut self) -> JsValue {
        if let Some(delta) = &self.delta {
            delta.clone()
        } else {
            let delta = self
                .inner()
                .delta(self.txn())
                .into_iter()
                .map(change_into_js);
            let mut result = js_sys::Array::new();
            result.extend(delta);
            let delta: JsValue = result.into();
            self.delta = Some(delta.clone());
            delta
        }
    }
}

/// Event generated by `YXmlText.observe` method. Emitted during transaction commit phase.
#[wasm_bindgen]
pub struct YXmlTextEvent {
    inner: *const XmlTextEvent,
    txn: *const TransactionMut<'static>,
    target: Option<JsValue>,
    delta: Option<JsValue>,
    keys: Option<JsValue>,
}

#[wasm_bindgen]
impl YXmlTextEvent {
    fn new<'doc>(event: &XmlTextEvent, txn: &TransactionMut<'doc>) -> Self {
        let inner = event as *const XmlTextEvent;
        let txn: &TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const TransactionMut<'static>;
        YXmlTextEvent {
            inner,
            txn,
            target: None,
            delta: None,
            keys: None,
        }
    }

    fn inner(&self) -> &XmlTextEvent {
        unsafe { self.inner.as_ref().unwrap() }
    }

    fn txn(&self) -> &TransactionMut {
        unsafe { self.txn.as_ref().unwrap() }
    }

    /// Returns a current shared type instance, that current event changes refer to.
    #[wasm_bindgen(method, getter)]
    pub fn target(&mut self) -> JsValue {
        if let Some(target) = self.target.as_ref() {
            target.clone()
        } else {
            let target: JsValue = YXmlText(self.inner().target().clone()).into();
            self.target = Some(target.clone());
            target
        }
    }

    /// Returns an array of keys and indexes creating a path from root type down to current instance
    /// of shared type (accessible via `target` getter).
    #[wasm_bindgen(method)]
    pub fn path(&self) -> JsValue {
        path_into_js(self.inner().path())
    }

    /// Returns a list of text changes made over corresponding `YXmlText` collection within
    /// bounds of current transaction. These changes follow a format:
    ///
    /// - { insert: string, attributes: any|undefined }
    /// - { delete: number }
    /// - { retain: number, attributes: any|undefined }
    #[wasm_bindgen(method, getter)]
    pub fn delta(&mut self) -> JsValue {
        if let Some(delta) = &self.delta {
            delta.clone()
        } else {
            let delta = self
                .inner()
                .delta(self.txn())
                .into_iter()
                .map(ytext_delta_into_js);
            let mut result = js_sys::Array::new();
            result.extend(delta);
            let delta: JsValue = result.into();
            self.delta = Some(delta.clone());
            delta
        }
    }

    /// Returns a list of attribute changes made over corresponding `YXmlText` collection within
    /// bounds of current transaction. These changes follow a format:
    ///
    /// - { action: 'add'|'update'|'delete', oldValue: string|undefined, newValue: string|undefined }
    #[wasm_bindgen(method, getter)]
    pub fn keys(&mut self) -> JsValue {
        if let Some(keys) = &self.keys {
            keys.clone()
        } else {
            let keys = self.inner().keys(self.txn());
            let result = js_sys::Object::new();
            for (key, value) in keys.iter() {
                let key = JsValue::from(key.as_ref());
                let value = entry_change_into_js(value);
                js_sys::Reflect::set(&result, &key, &value).unwrap();
            }
            let keys: JsValue = result.into();
            self.keys = Some(keys.clone());
            keys
        }
    }
}

fn path_into_js(path: Path) -> JsValue {
    let result = js_sys::Array::new();
    for segment in path {
        match segment {
            PathSegment::Key(key) => {
                result.push(&JsValue::from(key.as_ref()));
            }
            PathSegment::Index(idx) => {
                result.push(&JsValue::from(idx));
            }
        }
    }
    result.into()
}

fn entry_change_into_js(change: &EntryChange) -> JsValue {
    let result = js_sys::Object::new();
    let action = JsValue::from("action");
    match change {
        EntryChange::Inserted(new) => {
            let new_value = value_into_js(new.clone());
            js_sys::Reflect::set(&result, &action, &JsValue::from("add")).unwrap();
            js_sys::Reflect::set(&result, &JsValue::from("newValue"), &new_value).unwrap();
        }
        EntryChange::Updated(old, new) => {
            let old_value = value_into_js(old.clone());
            let new_value = value_into_js(new.clone());
            js_sys::Reflect::set(&result, &action, &JsValue::from("update")).unwrap();
            js_sys::Reflect::set(&result, &JsValue::from("oldValue"), &old_value).unwrap();
            js_sys::Reflect::set(&result, &JsValue::from("newValue"), &new_value).unwrap();
        }
        EntryChange::Removed(old) => {
            let old_value = value_into_js(old.clone());
            js_sys::Reflect::set(&result, &action, &JsValue::from("delete")).unwrap();
            js_sys::Reflect::set(&result, &JsValue::from("oldValue"), &old_value).unwrap();
        }
    }
    result.into()
}

fn ytext_change_into_js(change: Diff<JsValue>) -> JsValue {
    let delta = Delta::Inserted(change.insert, change.attributes);
    let js = ytext_delta_into_js(&delta);
    if let Some(ychange) = change.ychange {
        let attrs = match js_sys::Reflect::get(&js, &JsValue::from("attributes")) {
            Ok(attrs) if attrs.is_object() => attrs,
            _ => {
                let attrs: JsValue = js_sys::Object::new().into();
                js_sys::Reflect::set(&js, &JsValue::from("attributes"), &attrs).unwrap();
                attrs
            }
        };
        js_sys::Reflect::set(&attrs, &JsValue::from("ychange"), &ychange).unwrap();
    }
    js
}

fn ytext_delta_into_js(delta: &Delta) -> JsValue {
    let result = js_sys::Object::new();
    match delta {
        Delta::Inserted(value, attrs) => {
            js_sys::Reflect::set(
                &result,
                &JsValue::from("insert"),
                &value_into_js(value.clone()),
            )
            .unwrap();

            if let Some(attrs) = attrs {
                let attrs = attrs_into_js(attrs);
                js_sys::Reflect::set(&result, &JsValue::from("attributes"), &attrs).unwrap();
            }
        }
        Delta::Retain(len, attrs) => {
            let value = JsValue::from(*len);
            js_sys::Reflect::set(&result, &JsValue::from("retain"), &value).unwrap();

            if let Some(attrs) = attrs {
                let attrs = attrs_into_js(attrs);
                js_sys::Reflect::set(&result, &JsValue::from("attributes"), &attrs).unwrap();
            }
        }
        Delta::Deleted(len) => {
            let value = JsValue::from(*len);
            js_sys::Reflect::set(&result, &JsValue::from("delete"), &value).unwrap();
        }
    }
    result.into()
}

fn attrs_into_js(attrs: &Attrs) -> JsValue {
    let o = js_sys::Object::new();
    for (key, value) in attrs.iter() {
        let key = JsValue::from_str(key.as_ref());
        let value = value_into_js(Value::Any(value.clone()));
        js_sys::Reflect::set(&o, &key, &value).unwrap();
    }

    o.into()
}

fn change_into_js(change: &Change) -> JsValue {
    let result = js_sys::Object::new();
    match change {
        Change::Added(values) => {
            let mut array = js_sys::Array::new();
            array.extend(values.iter().map(|v| value_into_js(v.clone())));
            js_sys::Reflect::set(&result, &JsValue::from("insert"), &array).unwrap();
        }
        Change::Removed(len) => {
            let value = JsValue::from(*len);
            js_sys::Reflect::set(&result, &JsValue::from("delete"), &value).unwrap();
        }
        Change::Retain(len) => {
            let value = JsValue::from(*len);
            js_sys::Reflect::set(&result, &JsValue::from("retain"), &value).unwrap();
        }
    }
    result.into()
}

fn state_vector_into_map(sv: &StateVector) -> js_sys::Map {
    let m = js_sys::Map::new();
    for (&k, &v) in sv.iter() {
        let key: JsValue = k.into();
        let value: JsValue = v.into();
        m.set(&key, &value);
    }
    m
}

fn delete_set_into_map(ds: &DeleteSet) -> js_sys::Map {
    let m = js_sys::Map::new();
    for (&k, v) in ds.iter() {
        let key: JsValue = k.into();
        let iter = v.iter().map(|r| {
            let start = r.start;
            let len = r.end - r.start;
            let res: JsValue = js_sys::Array::of2(&start.into(), &len.into()).into();
            res
        });
        let value = js_sys::Array::new();
        for v in iter {
            value.push(&v);
        }
        m.set(&key, &value);
    }
    m
}

#[wasm_bindgen]
pub struct YSubdocsEvent {
    added: JsValue,
    removed: JsValue,
    loaded: JsValue,
}

#[wasm_bindgen]
impl YSubdocsEvent {
    fn new(e: &SubdocsEvent) -> Self {
        fn to_array(iter: SubdocsEventIter) -> JsValue {
            let mut buf = js_sys::Array::new();
            let values = iter.map(|d| {
                let doc = YDoc::from(d.clone());
                let js: JsValue = doc.into();
                js
            });
            buf.extend(values);
            buf.into()
        }

        let added = to_array(e.added());
        let removed = to_array(e.removed());
        let loaded = to_array(e.loaded());
        YSubdocsEvent {
            added,
            removed,
            loaded,
        }
    }

    #[wasm_bindgen(method, getter)]
    pub fn added(&mut self) -> JsValue {
        self.added.clone()
    }

    #[wasm_bindgen(method, getter)]
    pub fn removed(&mut self) -> JsValue {
        self.removed.clone()
    }

    #[wasm_bindgen(method, getter)]
    pub fn loaded(&mut self) -> JsValue {
        self.loaded.clone()
    }
}

#[wasm_bindgen]
pub struct YSubdocsObserver(SubdocsSubscription);

impl From<SubdocsSubscription> for YSubdocsObserver {
    fn from(o: SubdocsSubscription) -> Self {
        YSubdocsObserver(o)
    }
}

#[wasm_bindgen]
pub struct YDestroyObserver(DestroySubscription);

impl From<DestroySubscription> for YDestroyObserver {
    fn from(o: DestroySubscription) -> Self {
        YDestroyObserver(o)
    }
}

#[wasm_bindgen]
pub struct YAfterTransactionEvent {
    before_state: js_sys::Map,
    after_state: js_sys::Map,
    delete_set: js_sys::Map,
}

#[wasm_bindgen]
impl YAfterTransactionEvent {
    /// Returns a state vector - a map of entries (clientId, clock) - that represents logical
    /// time descriptor at the moment when transaction was originally created, prior to any changes
    /// made in scope of this transaction.
    #[wasm_bindgen(method, getter, js_name = beforeState)]
    pub fn before_state(&self) -> js_sys::Map {
        self.before_state.clone()
    }

    /// Returns a state vector - a map of entries (clientId, clock) - that represents logical
    /// time descriptor at the moment when transaction was comitted.
    #[wasm_bindgen(method, getter, js_name = afterState)]
    pub fn after_state(&self) -> js_sys::Map {
        self.after_state.clone()
    }

    /// Returns a delete set - a map of entries (clientId, (clock, len)[]) - that represents a range
    /// of all blocks deleted as part of current transaction.
    #[wasm_bindgen(method, getter, js_name = deleteSet)]
    pub fn delete_set(&self) -> js_sys::Map {
        self.delete_set.clone()
    }

    fn new(e: &TransactionCleanupEvent) -> Self {
        YAfterTransactionEvent {
            before_state: state_vector_into_map(&e.before_state),
            after_state: state_vector_into_map(&e.after_state),
            delete_set: delete_set_into_map(&e.delete_set),
        }
    }
}

#[wasm_bindgen]
pub struct YAfterTransactionObserver(TransactionCleanupSubscription);

impl From<TransactionCleanupSubscription> for YAfterTransactionObserver {
    fn from(o: TransactionCleanupSubscription) -> Self {
        YAfterTransactionObserver(o)
    }
}

#[wasm_bindgen]
pub struct YUpdateObserver(UpdateSubscription);

impl From<UpdateSubscription> for YUpdateObserver {
    fn from(o: UpdateSubscription) -> Self {
        YUpdateObserver(o)
    }
}

#[wasm_bindgen]
pub struct YArrayObserver(Subscription<Arc<dyn Fn(&TransactionMut, &ArrayEvent) -> ()>>);

#[wasm_bindgen]
pub struct YTextObserver(Subscription<Arc<dyn Fn(&TransactionMut, &TextEvent) -> ()>>);

#[wasm_bindgen]
pub struct YMapObserver(Subscription<Arc<dyn Fn(&TransactionMut, &MapEvent) -> ()>>);

#[wasm_bindgen]
pub struct YXmlObserver(Subscription<Arc<dyn Fn(&TransactionMut, &XmlEvent) -> ()>>);

#[wasm_bindgen]
pub struct YXmlTextObserver(Subscription<Arc<dyn Fn(&TransactionMut, &XmlTextEvent) -> ()>>);

#[wasm_bindgen]
pub struct YEventObserver(DeepEventsSubscription);

impl From<DeepEventsSubscription> for YEventObserver {
    fn from(o: DeepEventsSubscription) -> Self {
        YEventObserver(o)
    }
}

enum SharedType<T, P> {
    Integrated(T),
    Prelim(P),
}

impl<T, P> SharedType<T, P> {
    #[inline(always)]
    fn new(value: T) -> RefCell<Self> {
        RefCell::new(SharedType::Integrated(value))
    }

    #[inline(always)]
    fn prelim(prelim: P) -> RefCell<Self> {
        RefCell::new(SharedType::Prelim(prelim))
    }

    fn as_integrated(&self) -> Option<&T> {
        if let SharedType::Integrated(value) = self {
            Some(value)
        } else {
            None
        }
    }
}

/// A shared data type used for collaborative text editing. It enables multiple users to add and
/// remove chunks of text in efficient manner. This type is internally represented as a mutable
/// double-linked list of text chunks - an optimization occurs during `YTransaction.commit`, which
/// allows to squash multiple consecutively inserted characters together as a single chunk of text
/// even between transaction boundaries in order to preserve more efficient memory model.
///
/// `YText` structure internally uses UTF-8 encoding and its length is described in a number of
/// bytes rather than individual characters (a single UTF-8 code point can consist of many bytes).
///
/// Like all Yrs shared data types, `YText` is resistant to the problem of interleaving (situation
/// when characters inserted one after another may interleave with other peers concurrent inserts
/// after merging all updates together). In case of Yrs conflict resolution is solved by using
/// unique document id to determine correct and consistent ordering.
#[wasm_bindgen]
pub struct YText(RefCell<SharedType<TextRef, String>>);

impl From<TextRef> for YText {
    fn from(v: TextRef) -> Self {
        YText(SharedType::new(v))
    }
}

#[wasm_bindgen]
impl YText {
    /// Creates a new preliminary instance of a `YText` shared data type, with its state initialized
    /// to provided parameter.
    ///
    /// Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
    /// Once a preliminary instance has been inserted this way, it becomes integrated into ywasm
    /// document store and cannot be nested again: attempt to do so will result in an exception.
    #[wasm_bindgen(constructor)]
    pub fn new(init: Option<String>) -> Self {
        YText(SharedType::prelim(init.unwrap_or_default()))
    }

    /// Returns true if this is a preliminary instance of `YText`.
    ///
    /// Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
    /// Once a preliminary instance has been inserted this way, it becomes integrated into ywasm
    /// document store and cannot be nested again: attempt to do so will result in an exception.
    #[wasm_bindgen(method, getter)]
    pub fn prelim(&self) -> bool {
        if let SharedType::Prelim(_) = &*self.0.borrow() {
            true
        } else {
            false
        }
    }

    /// Returns length of an underlying string stored in this `YText` instance,
    /// understood as a number of UTF-8 encoded bytes.
    #[wasm_bindgen(method, js_name = length)]
    pub fn length(&self, txn: &ImplicitTransaction) -> u32 {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    v.len(txn)
                } else {
                    v.len(&v.transact())
                }
            }
            SharedType::Prelim(v) => v.len() as u32,
        }
    }

    /// Returns an underlying shared string stored in this data type.
    #[wasm_bindgen(method, js_name = toString)]
    pub fn to_string(&self, txn: &ImplicitTransaction) -> String {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    v.get_string(txn)
                } else {
                    v.get_string(&v.transact())
                }
            }
            SharedType::Prelim(v) => v.clone(),
        }
    }

    /// Returns an underlying shared string stored in this data type.
    #[wasm_bindgen(method, js_name = toJson)]
    pub fn to_json(&self, txn: &ImplicitTransaction) -> JsValue {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    JsValue::from(&v.get_string(txn))
                } else {
                    JsValue::from(&v.get_string(&v.transact()))
                }
            }
            SharedType::Prelim(v) => JsValue::from(v),
        }
    }

    /// Inserts a given `chunk` of text into this `YText` instance, starting at a given `index`.
    ///
    /// Optional object with defined `attributes` will be used to wrap provided text `chunk`
    /// with a formatting blocks.`attributes` are only supported for a `YText` instance which
    /// already has been integrated into document store.
    #[wasm_bindgen(method, js_name = insert)]
    pub fn insert(&self, index: u32, chunk: &str, attributes: JsValue, txn: &ImplicitTransaction) {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn_mut(txn) {
                    if let Some(attrs) = Self::parse_attrs(attributes) {
                        v.insert_with_attributes(txn, index, chunk, attrs)
                    } else {
                        v.insert(txn, index, chunk)
                    }
                } else {
                    let mut txn = v.transact_mut();
                    if let Some(attrs) = Self::parse_attrs(attributes) {
                        v.insert_with_attributes(&mut txn, index, chunk, attrs)
                    } else {
                        v.insert(&mut txn, index, chunk)
                    }
                }
            }
            SharedType::Prelim(v) => {
                if attributes.is_object() {
                    panic!("insert with attributes requires YText instance to be integrated first.")
                } else {
                    v.insert_str(index as usize, chunk)
                }
            }
        }
    }

    /// Inserts a given `embed` object into this `YText` instance, starting at a given `index`.
    ///
    /// Optional object with defined `attributes` will be used to wrap provided `embed`
    /// with a formatting blocks.`attributes` are only supported for a `YText` instance which
    /// already has been integrated into document store.
    #[wasm_bindgen(method, js_name = insertEmbed)]
    pub fn insert_embed(
        &self,
        index: u32,
        embed: JsValue,
        attributes: JsValue,
        txn: &ImplicitTransaction,
    ) {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                let content = js_into_any(&embed).unwrap();
                if let Some(txn) = get_txn_mut(txn) {
                    if let Some(attrs) = Self::parse_attrs(attributes) {
                        v.insert_embed_with_attributes(txn, index, content, attrs);
                    } else {
                        v.insert_embed(txn, index, content);
                    }
                } else {
                    let mut txn = v.transact_mut();

                    if let Some(attrs) = Self::parse_attrs(attributes) {
                        v.insert_embed_with_attributes(&mut txn, index, content, attrs);
                    } else {
                        v.insert_embed(&mut txn, index, content);
                    }
                }
            }
            SharedType::Prelim(_) => {
                panic!("insert embeds requires YText instance to be integrated first.")
            }
        }
    }

    /// Wraps an existing piece of text within a range described by `index`-`length` parameters with
    /// formatting blocks containing provided `attributes` metadata. This method only works for
    /// `YText` instances that already have been integrated into document store.
    #[wasm_bindgen(method, js_name = format)]
    pub fn format(&self, index: u32, length: u32, attributes: JsValue, txn: &ImplicitTransaction) {
        if let Some(attrs) = Self::parse_attrs(attributes) {
            match &mut *self.0.borrow_mut() {
                SharedType::Integrated(v) => {
                    if let Some(txn) = get_txn_mut(txn) {
                        v.format(txn, index, length, attrs);
                    } else {
                        let mut txn = v.transact_mut();
                        v.format(&mut txn, index, length, attrs);
                    }
                }
                SharedType::Prelim(_) => {
                    panic!("format with attributes requires YText instance to be integrated first.")
                }
            }
        }
    }

    fn parse_attrs(attrs: JsValue) -> Option<Attrs> {
        if attrs.is_object() {
            let mut map = Attrs::new();
            let object = js_sys::Object::from(attrs);
            let entries = js_sys::Object::entries(&object);
            for tuple in entries.iter() {
                let tuple = js_sys::Array::from(&tuple);
                let key: String = tuple.get(0).as_string()?;
                let value = js_into_any(&tuple.get(1))?;
                map.insert(key.into(), value);
            }
            Some(map)
        } else {
            None
        }
    }

    /// Appends a given `chunk` of text at the end of current `YText` instance.
    ///
    /// Optional object with defined `attributes` will be used to wrap provided text `chunk`
    /// with a formatting blocks.`attributes` are only supported for a `YText` instance which
    /// already has been integrated into document store.
    #[wasm_bindgen(method, js_name = push)]
    pub fn push(&self, chunk: &str, attributes: JsValue, txn: &ImplicitTransaction) {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn_mut(txn) {
                    if let Some(attrs) = Self::parse_attrs(attributes) {
                        v.insert_with_attributes(txn, v.len(txn), chunk, attrs)
                    } else {
                        v.push(txn, chunk)
                    }
                } else {
                    let mut txn = v.transact_mut();
                    if let Some(attrs) = Self::parse_attrs(attributes) {
                        let index = v.len(&txn);
                        v.insert_with_attributes(&mut txn, index, chunk, attrs)
                    } else {
                        v.push(&mut txn, chunk)
                    }
                }
            }
            SharedType::Prelim(v) => {
                if attributes.is_object() {
                    panic!("push with attributes requires YText instance to be integrated first.")
                }
                v.push_str(chunk)
            }
        }
    }

    /// Deletes a specified range of of characters, starting at a given `index`.
    /// Both `index` and `length` are counted in terms of a number of UTF-8 character bytes.
    #[wasm_bindgen(method, js_name = delete)]
    pub fn delete(&mut self, index: u32, length: u32, txn: &ImplicitTransaction) {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn_mut(txn) {
                    v.remove_range(txn, index, length);
                } else {
                    let mut txn = v.transact_mut();
                    v.remove_range(&mut txn, index, length);
                }
            }
            SharedType::Prelim(v) => {
                v.drain((index as usize)..(index + length) as usize);
            }
        }
    }

    /// Returns the Delta representation of this YText type.
    #[wasm_bindgen(method, js_name = toDelta)]
    pub fn to_delta(
        &self,
        snapshot: Option<YSnapshot>,
        prev_snapshot: Option<YSnapshot>,
        compute_ychange: Option<js_sys::Function>,
        txn: &ImplicitTransaction,
    ) -> JsValue {
        match &*self.0.borrow() {
            SharedType::Prelim(_) => JsValue::UNDEFINED,
            SharedType::Integrated(v) => {
                let hi = snapshot.map(|s| s.0);
                let lo = prev_snapshot.map(|s| s.0);

                fn changes(change: YChange, compute_ychange: &Option<js_sys::Function>) -> JsValue {
                    let kind = match change.kind {
                        ChangeKind::Added => JsValue::from("added"),
                        ChangeKind::Removed => JsValue::from("removed"),
                    };
                    let result = if let Some(func) = compute_ychange {
                        let id = change.id.into_js();
                        func.call2(&JsValue::UNDEFINED, &kind, &id).unwrap()
                    } else {
                        let js: JsValue = js_sys::Object::new().into();
                        js_sys::Reflect::set(&js, &JsValue::from("type"), &kind).unwrap();
                        js
                    };
                    result
                }

                let delta = if let Some(txn) = get_txn_mut(txn) {
                    v.diff_range(txn, hi.as_ref(), lo.as_ref(), |change| {
                        changes(change, &compute_ychange)
                    })
                    .into_iter()
                    .map(ytext_change_into_js)
                } else {
                    let mut txn = v.transact_mut();
                    v.diff_range(&mut txn, hi.as_ref(), lo.as_ref(), |change| {
                        changes(change, &compute_ychange)
                    })
                    .into_iter()
                    .map(ytext_change_into_js)
                };
                let mut result = js_sys::Array::new();
                result.extend(delta);
                let delta: JsValue = result.into();
                delta
            }
        }
    }

    /// Subscribes to all operations happening over this instance of `YText`. All changes are
    /// batched and eventually triggered during transaction commit phase.
    /// Returns an `YTextObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observe)]
    pub fn observe(&mut self, f: js_sys::Function) -> YTextObserver {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                let sub = v.observe(move |txn, e| {
                    let e = YTextEvent::new(e, txn);
                    let arg: JsValue = e.into();
                    f.call1(&JsValue::UNDEFINED, &arg).unwrap();
                });
                YTextObserver(sub)
            }
            SharedType::Prelim(_) => {
                panic!("YText.observe is not supported on preliminary type.")
            }
        }
    }

    /// Subscribes to all operations happening over this Y shared type, as well as events in
    /// shared types stored within this one. All changes are batched and eventually triggered
    /// during transaction commit phase.
    /// Returns an `YEventObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observeDeep)]
    pub fn observe_deep(&mut self, f: js_sys::Function) -> YEventObserver {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                let sub = v.observe_deep(move |txn, e| {
                    let arg = events_into_js(txn, e);
                    f.call1(&JsValue::UNDEFINED, &arg).unwrap();
                });
                YEventObserver(sub)
            }
            SharedType::Prelim(_) => {
                panic!("YText.observeDeep is not supported on preliminary type.")
            }
        }
    }
}

#[wasm_bindgen]
pub struct YSnapshot(Snapshot);

#[wasm_bindgen]
impl YSnapshot {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self {
        YSnapshot(Snapshot::default())
    }
}

#[wasm_bindgen(js_name = snapshot)]
pub fn snapshot(doc: &YDoc) -> YSnapshot {
    YSnapshot(doc.as_ref().transact().snapshot())
}

#[wasm_bindgen(js_name = equalSnapshots)]
pub fn equal_snapshots(snap1: &YSnapshot, snap2: &YSnapshot) -> bool {
    snap1.0 == snap2.0
}

#[wasm_bindgen(js_name = encodeSnapshotV1)]
pub fn encode_snapshot_v1(snapshot: &YSnapshot) -> Vec<u8> {
    snapshot.0.encode_v1()
}

#[wasm_bindgen(js_name = encodeSnapshotV2)]
pub fn encode_snapshot_v2(snapshot: &YSnapshot) -> Vec<u8> {
    snapshot.0.encode_v2()
}

#[wasm_bindgen(catch, js_name = decodeSnapshotV2)]
pub fn decode_snapshot_v2(snapshot: &[u8]) -> Result<YSnapshot, JsValue> {
    let s = Snapshot::decode_v2(snapshot)
        .map_err(|_| JsValue::from("failed to deserialize snapshot using lib0 v2 decoding"))?;
    Ok(YSnapshot(s))
}

#[wasm_bindgen(catch, js_name = decodeSnapshotV1)]
pub fn decode_snapshot_v1(snapshot: &[u8]) -> Result<YSnapshot, JsValue> {
    let s = Snapshot::decode_v1(snapshot)
        .map_err(|_| JsValue::from("failed to deserialize snapshot using lib0 v1 decoding"))?;
    Ok(YSnapshot(s))
}

#[wasm_bindgen(catch, js_name = encodeStateFromSnapshotV1)]
pub fn encode_state_from_snapshot_v1(doc: &YDoc, snapshot: &YSnapshot) -> Result<Vec<u8>, JsValue> {
    let mut encoder = EncoderV1::new();
    match doc
        .as_ref()
        .transact()
        .encode_state_from_snapshot(&snapshot.0, &mut encoder)
    {
        Ok(_) => Ok(encoder.to_vec()),
        Err(e) => Err(JsValue::from(e.to_string())),
    }
}

#[wasm_bindgen(catch, js_name = encodeStateFromSnapshotV2)]
pub fn encode_state_from_snapshot_v2(doc: &YDoc, snapshot: &YSnapshot) -> Result<Vec<u8>, JsValue> {
    let mut encoder = EncoderV2::new();
    match doc
        .as_ref()
        .transact()
        .encode_state_from_snapshot(&snapshot.0, &mut encoder)
    {
        Ok(_) => Ok(encoder.to_vec()),
        Err(e) => Err(JsValue::from(e.to_string())),
    }
}

/// A collection used to store data in an indexed sequence structure. This type is internally
/// implemented as a double linked list, which may squash values inserted directly one after another
/// into single list node upon transaction commit.
///
/// Reading a root-level type as an YArray means treating its sequence components as a list, where
/// every countable element becomes an individual entity:
///
/// - JSON-like primitives (booleans, numbers, strings, JSON maps, arrays etc.) are counted
///   individually.
/// - Text chunks inserted by [Text] data structure: each character becomes an element of an
///   array.
/// - Embedded and binary values: they count as a single element even though they correspond of
///   multiple bytes.
///
/// Like all Yrs shared data types, YArray is resistant to the problem of interleaving (situation
/// when elements inserted one after another may interleave with other peers concurrent inserts
/// after merging all updates together). In case of Yrs conflict resolution is solved by using
/// unique document id to determine correct and consistent ordering.
#[wasm_bindgen]
pub struct YArray(RefCell<SharedType<ArrayRef, Vec<JsValue>>>);

impl From<ArrayRef> for YArray {
    fn from(v: ArrayRef) -> Self {
        YArray(SharedType::new(v))
    }
}

impl PartialEq for YArray {
    fn eq(&self, other: &Self) -> bool {
        match (&*self.0.borrow(), &*other.0.borrow()) {
            (SharedType::Integrated(v1), SharedType::Integrated(v2)) => v1 == v2,
            (SharedType::Prelim(v1), SharedType::Prelim(v2)) => v1 == v2,
            _ => false,
        }
    }
}

#[wasm_bindgen]
impl YArray {
    /// Creates a new preliminary instance of a `YArray` shared data type, with its state
    /// initialized to provided parameter.
    ///
    /// Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
    /// Once a preliminary instance has been inserted this way, it becomes integrated into ywasm
    /// document store and cannot be nested again: attempt to do so will result in an exception.
    #[wasm_bindgen(constructor)]
    pub fn new(init: Option<Vec<JsValue>>) -> Self {
        YArray(SharedType::prelim(init.unwrap_or_default()))
    }

    /// Returns true if this is a preliminary instance of `YArray`.
    ///
    /// Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
    /// Once a preliminary instance has been inserted this way, it becomes integrated into ywasm
    /// document store and cannot be nested again: attempt to do so will result in an exception.
    #[wasm_bindgen(method, getter)]
    pub fn prelim(&self) -> bool {
        if let SharedType::Prelim(_) = &*self.0.borrow() {
            true
        } else {
            false
        }
    }

    /// Returns a number of elements stored within this instance of `YArray`.
    #[wasm_bindgen(method, js_name = length)]
    pub fn length(&self, txn: &ImplicitTransaction) -> u32 {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    v.len(txn)
                } else {
                    v.len(&v.transact())
                }
            }
            SharedType::Prelim(v) => v.len() as u32,
        }
    }

    /// Converts an underlying contents of this `YArray` instance into their JSON representation.
    #[wasm_bindgen(method, js_name = toJson)]
    pub fn to_json(&self, txn: &ImplicitTransaction) -> JsValue {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    any_into_js(&v.to_json(txn))
                } else {
                    let txn = v.transact();
                    any_into_js(&v.to_json(&txn))
                }
            }
            SharedType::Prelim(v) => {
                let array = js_sys::Array::new();
                for js in v.iter() {
                    array.push(js);
                }
                array.into()
            }
        }
    }

    /// Inserts a given range of `items` into this `YArray` instance, starting at given `index`.
    #[wasm_bindgen(method, js_name = insert)]
    pub fn insert(&self, index: u32, items: Vec<JsValue>, txn: &ImplicitTransaction) {
        let mut j = index;
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn_mut(txn) {
                    insert_at(v, txn, index, items);
                } else {
                    let mut txn = v.transact_mut();
                    insert_at(v, &mut txn, index, items);
                }
            }
            SharedType::Prelim(vec) => {
                for js in items {
                    vec.insert(j as usize, js);
                    j += 1;
                }
            }
        }
    }

    /// Appends a range of `items` at the end of this `YArray` instance.
    #[wasm_bindgen(method, js_name = push)]
    pub fn push(&self, items: Vec<JsValue>, txn: &ImplicitTransaction) {
        let index = self.length(txn);
        self.insert(index, items, txn);
    }

    /// Deletes a range of items of given `length` from current `YArray` instance,
    /// starting from given `index`.
    #[wasm_bindgen(method, js_name = delete)]
    pub fn delete(&self, index: u32, length: u32, txn: &ImplicitTransaction) {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn_mut(txn) {
                    v.remove_range(txn, index, length)
                } else {
                    let mut txn = v.transact_mut();
                    v.remove_range(&mut txn, index, length)
                }
            }
            SharedType::Prelim(v) => {
                v.drain((index as usize)..(index + length) as usize);
            }
        }
    }

    /// Moves element found at `source` index into `target` index position.
    #[wasm_bindgen(method, js_name = move)]
    pub fn move_content(&self, source: u32, target: u32, txn: &ImplicitTransaction) {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn_mut(txn) {
                    v.move_to(txn, source, target)
                } else {
                    let mut txn = v.transact_mut();
                    v.move_to(&mut txn, source, target)
                }
            }
            SharedType::Prelim(v) => {
                let index = if target > source { target - 1 } else { target };
                let moved = v.remove(source as usize);
                v.insert(index as usize, moved);
            }
        }
    }

    /// Returns an element stored under given `index`.
    #[wasm_bindgen(method, catch, js_name = get)]
    pub fn get(&self, index: u32, txn: &ImplicitTransaction) -> Result<JsValue, JsValue> {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    if let Some(value) = v.get(txn, index) {
                        Ok(value_into_js(value))
                    } else {
                        Err(JsValue::from("Index outside the bounds of an YArray"))
                    }
                } else {
                    let txn = v.transact();
                    if let Some(value) = v.get(&txn, index) {
                        Ok(value_into_js(value))
                    } else {
                        Err(JsValue::from("Index outside the bounds of an YArray"))
                    }
                }
            }
            SharedType::Prelim(v) => {
                if let Some(value) = v.get(index as usize) {
                    Ok(value.clone())
                } else {
                    Err(JsValue::from("Index outside the bounds of an YArray"))
                }
            }
        }
    }

    /// Returns an iterator that can be used to traverse over the values stored withing this
    /// instance of `YArray`.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// /// document on machine A
    /// const doc = new YDoc()
    /// const array = doc.getArray('name')
    /// const txn = doc.beginTransaction()
    /// try {
    ///     array.push(txn, ['hello', 'world'])
    ///     for (let item of array.values(txn)) {
    ///         console.log(item)
    ///     }
    /// } finally {
    ///     txn.free()
    /// }
    /// ```
    #[wasm_bindgen(method, js_name = values)]
    pub fn values(&self, txn: &ImplicitTransaction) -> JsValue {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    let values = v.iter(txn);
                    iter_to_array(values).into()
                } else {
                    let txn = v.transact();
                    let values = v.iter(&txn);
                    iter_to_array(values).into()
                }
            }
            SharedType::Prelim(v) => {
                let values = v.iter();
                iter_to_array(values).into()
            }
        }
    }

    /// Subscribes to all operations happening over this instance of `YArray`. All changes are
    /// batched and eventually triggered during transaction commit phase.
    /// Returns an `YObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observe)]
    pub fn observe(&mut self, f: js_sys::Function) -> YArrayObserver {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                let sub = v.observe(move |txn, e| {
                    let e = YArrayEvent::new(e, txn);
                    let arg: JsValue = e.into();
                    f.call1(&JsValue::UNDEFINED, &arg).unwrap();
                });
                YArrayObserver(sub)
            }
            SharedType::Prelim(_) => {
                panic!("YArray.observe is not supported on preliminary type.")
            }
        }
    }

    /// Subscribes to all operations happening over this Y shared type, as well as events in
    /// shared types stored within this one. All changes are batched and eventually triggered
    /// during transaction commit phase.
    /// Returns an `YEventObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observeDeep)]
    pub fn observe_deep(&mut self, f: js_sys::Function) -> YEventObserver {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => v
                .observe_deep(move |txn, e| {
                    let arg = events_into_js(txn, e);
                    f.call1(&JsValue::UNDEFINED, &arg).unwrap();
                })
                .into(),
            SharedType::Prelim(_) => {
                panic!("YText.observeDeep is not supported on preliminary type.")
            }
        }
    }
}

fn iter_to_array<I, T>(iter: I) -> js_sys::Array
where
    I: Iterator<Item = T>,
    T: IntoJs,
{
    let array = js_sys::Array::new();
    for value in iter {
        let js_value = value.into_js();
        array.push(&js_value);
    }
    array
}

fn iter_to_map<'a, I, T>(iter: I) -> js_sys::Object
where
    I: Iterator<Item = (&'a str, T)>,
    T: IntoJs,
{
    let obj = js_sys::Object::new();
    for (key, value) in iter {
        let key = JsValue::from_str(key);
        let value = value.into_js();
        js_sys::Reflect::set(&obj, &key, &value).unwrap();
    }
    obj
}

trait IntoJs {
    fn into_js(self) -> JsValue;
}

impl<'a> IntoJs for &'a JsValue {
    fn into_js(self) -> JsValue {
        self.clone()
    }
}

impl IntoJs for JsValue {
    fn into_js(self) -> JsValue {
        self
    }
}

impl IntoJs for Value {
    fn into_js(self) -> JsValue {
        value_into_js(self)
    }
}

impl IntoJs for String {
    fn into_js(self) -> JsValue {
        JsValue::from_str(&self)
    }
}

impl IntoJs for XmlNode {
    fn into_js(self) -> JsValue {
        xml_into_js(self)
    }
}
impl<'a> IntoJs for (&'a str, Value) {
    fn into_js(self) -> JsValue {
        let tuple = js_sys::Array::new_with_length(2);
        tuple.set(0, JsValue::from(self.0));
        tuple.set(1, value_into_js(self.1));
        tuple.into()
    }
}

impl<'a> IntoJs for (&'a str, String) {
    fn into_js(self) -> JsValue {
        let tuple = js_sys::Array::new_with_length(2);
        tuple.set(0, JsValue::from_str(self.0));
        tuple.set(1, JsValue::from(&self.1));
        tuple.into()
    }
}

/// Collection used to store key-value entries in an unordered manner. Keys are always represented
/// as UTF-8 strings. Values can be any value type supported by Yrs: JSON-like primitives as well as
/// shared data types.
///
/// In terms of conflict resolution, [Map] uses logical last-write-wins principle, meaning the past
/// updates are automatically overridden and discarded by newer ones, while concurrent updates made
/// by different peers are resolved into a single value using document id seniority to establish
/// order.
#[wasm_bindgen]
pub struct YMap(RefCell<SharedType<MapRef, HashMap<String, JsValue>>>);

impl From<MapRef> for YMap {
    fn from(v: MapRef) -> Self {
        YMap(SharedType::new(v))
    }
}

#[wasm_bindgen]
impl YMap {
    /// Creates a new preliminary instance of a `YMap` shared data type, with its state
    /// initialized to provided parameter.
    ///
    /// Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
    /// Once a preliminary instance has been inserted this way, it becomes integrated into ywasm
    /// document store and cannot be nested again: attempt to do so will result in an exception.
    #[wasm_bindgen(constructor)]
    pub fn new(init: Option<js_sys::Object>) -> Self {
        let map = if let Some(object) = init {
            let mut map = HashMap::new();
            let entries = js_sys::Object::entries(&object);
            for tuple in entries.iter() {
                let tuple = js_sys::Array::from(&tuple);
                let key = tuple.get(0).as_string().unwrap();
                let value = tuple.get(1);
                map.insert(key, value);
            }
            map
        } else {
            HashMap::new()
        };
        YMap(SharedType::prelim(map))
    }

    /// Returns true if this is a preliminary instance of `YMap`.
    ///
    /// Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
    /// Once a preliminary instance has been inserted this way, it becomes integrated into ywasm
    /// document store and cannot be nested again: attempt to do so will result in an exception.
    #[wasm_bindgen(method, getter)]
    pub fn prelim(&self) -> bool {
        if let SharedType::Prelim(_) = &*self.0.borrow() {
            true
        } else {
            false
        }
    }

    /// Returns a number of entries stored within this instance of `YMap`.
    #[wasm_bindgen(method, js_name = length)]
    pub fn length(&self, txn: &ImplicitTransaction) -> u32 {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    v.len(txn)
                } else {
                    v.len(&v.transact())
                }
            }
            SharedType::Prelim(v) => v.len() as u32,
        }
    }

    /// Converts contents of this `YMap` instance into a JSON representation.
    #[wasm_bindgen(method, js_name = toJson)]
    pub fn to_json(&self, txn: &ImplicitTransaction) -> JsValue {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    any_into_js(&v.to_json(txn))
                } else {
                    let txn = v.transact();
                    any_into_js(&v.to_json(&txn))
                }
            }
            SharedType::Prelim(v) => {
                let map = js_sys::Object::new();
                for (k, v) in v.iter() {
                    js_sys::Reflect::set(&map, &k.into(), v).unwrap();
                }
                map.into()
            }
        }
    }

    /// Sets a given `key`-`value` entry within this instance of `YMap`. If another entry was
    /// already stored under given `key`, it will be overridden with new `value`.
    #[wasm_bindgen(method, js_name = set)]
    pub fn set(&self, key: &str, value: JsValue, txn: &ImplicitTransaction) {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn_mut(txn) {
                    v.insert(txn, key.to_string(), JsValueWrapper(value));
                } else {
                    let mut txn = v.transact_mut();
                    v.insert(&mut txn, key.to_string(), JsValueWrapper(value));
                }
            }
            SharedType::Prelim(v) => {
                v.insert(key.to_string(), value);
            }
        }
    }

    /// Removes an entry identified by a given `key` from this instance of `YMap`, if such exists.
    #[wasm_bindgen(method, js_name = delete)]
    pub fn delete(&mut self, key: &str, txn: &ImplicitTransaction) {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn_mut(txn) {
                    v.remove(txn, key);
                } else {
                    let mut txn = v.transact_mut();
                    v.remove(&mut txn, key);
                }
            }
            SharedType::Prelim(v) => {
                v.remove(key);
            }
        }
    }

    /// Returns value of an entry stored under given `key` within this instance of `YMap`,
    /// or `undefined` if no such entry existed.
    #[wasm_bindgen(method, js_name = get)]
    pub fn get(&self, key: &str, txn: &ImplicitTransaction) -> JsValue {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                let value = if let Some(txn) = get_txn(txn) {
                    v.get(txn, key)
                } else {
                    v.get(&v.transact(), key)
                };

                if let Some(value) = value {
                    value_into_js(value)
                } else {
                    JsValue::undefined()
                }
            }
            SharedType::Prelim(v) => {
                if let Some(value) = v.get(key) {
                    value.clone()
                } else {
                    JsValue::undefined()
                }
            }
        }
    }

    /// Returns an iterator that can be used to traverse over all entries stored within this
    /// instance of `YMap`. Order of entry is not specified.
    ///
    /// Example:
    ///
    /// ```javascript
    /// import YDoc from 'ywasm'
    ///
    /// /// document on machine A
    /// const doc = new YDoc()
    /// const map = doc.getMap('name')
    /// const txn = doc.beginTransaction()
    /// try {
    ///     map.set(txn, 'key1', 'value1')
    ///     map.set(txn, 'key2', true)
    ///
    ///     for (let [key, value] of map.entries(txn)) {
    ///         console.log(key, value)
    ///     }
    /// } finally {
    ///     txn.free()
    /// }
    /// ```
    #[wasm_bindgen(method, js_name = entries)]
    pub fn entries(&self, txn: &ImplicitTransaction) -> JsValue {
        match &*self.0.borrow() {
            SharedType::Integrated(v) => {
                if let Some(txn) = get_txn(txn) {
                    let entries = v.iter(txn);
                    iter_to_map(entries).into()
                } else {
                    let txn = v.transact();
                    let entries = v.iter(&txn);
                    iter_to_map(entries).into()
                }
            }
            SharedType::Prelim(v) => {
                let obj = js_sys::Object::new();
                for (key, value) in v.iter() {
                    let key = JsValue::from_str(key.as_str());
                    let value = value.into_js();
                    js_sys::Reflect::set(&obj, &key, &value).unwrap();
                }
                obj.into()
            }
        }
    }

    /// Subscribes to all operations happening over this instance of `YMap`. All changes are
    /// batched and eventually triggered during transaction commit phase.
    /// Returns an `YObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observe)]
    pub fn observe(&mut self, f: js_sys::Function) -> YMapObserver {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => {
                let sub = v.observe(move |txn, e| {
                    let e = YMapEvent::new(e, txn);
                    let arg: JsValue = e.into();
                    f.call1(&JsValue::UNDEFINED, &arg).unwrap();
                });
                YMapObserver(sub)
            }
            SharedType::Prelim(_) => {
                panic!("YMap.observe is not supported on preliminary type.")
            }
        }
    }

    /// Subscribes to all operations happening over this Y shared type, as well as events in
    /// shared types stored within this one. All changes are batched and eventually triggered
    /// during transaction commit phase.
    /// Returns an `YEventObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observeDeep)]
    pub fn observe_deep(&mut self, f: js_sys::Function) -> YEventObserver {
        match &mut *self.0.borrow_mut() {
            SharedType::Integrated(v) => v
                .observe_deep(move |txn, e| {
                    let arg = events_into_js(txn, e);
                    f.call1(&JsValue::UNDEFINED, &arg).unwrap();
                })
                .into(),
            SharedType::Prelim(_) => {
                panic!("YText.observeDeep is not supported on preliminary type.")
            }
        }
    }
}

/// XML element data type. It represents an XML node, which can contain key-value attributes
/// (interpreted as strings) as well as other nested XML elements or rich text (represented by
/// `YXmlText` type).
///
/// In terms of conflict resolution, `YXmlElement` uses following rules:
///
/// - Attribute updates use logical last-write-wins principle, meaning the past updates are
///   automatically overridden and discarded by newer ones, while concurrent updates made by
///   different peers are resolved into a single value using document id seniority to establish
///   an order.
/// - Child node insertion uses sequencing rules from other Yrs collections - elements are inserted
///   using interleave-resistant algorithm, where order of concurrent inserts at the same index
///   is established using peer's document id seniority.
#[wasm_bindgen]
pub struct YXmlElement(XmlElementRef);

#[wasm_bindgen]
impl YXmlElement {
    /// Returns a tag name of this XML node.
    #[wasm_bindgen(method, getter)]
    pub fn name(&self) -> String {
        self.0.tag().to_string()
    }

    /// Returns a number of child XML nodes stored within this `YXMlElement` instance.
    #[wasm_bindgen(method, js_name = length)]
    pub fn length(&self, txn: &ImplicitTransaction) -> u32 {
        if let Some(txn) = get_txn(txn) {
            self.0.len(txn)
        } else {
            let txn = self.0.transact();
            self.0.len(&txn)
        }
    }

    /// Inserts a new instance of `YXmlElement` as a child of this XML node and returns it.
    #[wasm_bindgen(method, js_name = insertXmlElement)]
    pub fn insert_xml_element(
        &self,
        index: u32,
        name: &str,
        txn: &ImplicitTransaction,
    ) -> YXmlElement {
        if let Some(txn) = get_txn_mut(txn) {
            YXmlElement(self.0.insert(txn, index, XmlElementPrelim::empty(name)))
        } else {
            let mut txn = self.0.transact_mut();
            YXmlElement(
                self.0
                    .insert(&mut txn, index, XmlElementPrelim::empty(name)),
            )
        }
    }

    /// Inserts a new instance of `YXmlText` as a child of this XML node and returns it.
    #[wasm_bindgen(method, js_name = insertXmlText)]
    pub fn insert_xml_text(&self, index: u32, txn: &ImplicitTransaction) -> YXmlText {
        if let Some(txn) = get_txn_mut(txn) {
            YXmlText(self.0.insert(txn, index, XmlTextPrelim::new("")))
        } else {
            let mut txn = self.0.transact_mut();
            YXmlText(self.0.insert(&mut txn, index, XmlTextPrelim::new("")))
        }
    }

    /// Removes a range of children XML nodes from this `YXmlElement` instance,
    /// starting at given `index`.
    #[wasm_bindgen(method, js_name = delete)]
    pub fn delete(&self, index: u32, length: u32, txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(txn) {
            self.0.remove_range(txn, index, length)
        } else {
            let mut txn = self.0.transact_mut();
            self.0.remove_range(&mut txn, index, length)
        }
    }

    /// Appends a new instance of `YXmlElement` as the last child of this XML node and returns it.
    #[wasm_bindgen(method, js_name = pushXmlElement)]
    pub fn push_xml_element(&self, name: &str, txn: &ImplicitTransaction) -> YXmlElement {
        if let Some(txn) = get_txn_mut(txn) {
            YXmlElement(self.0.push_back(txn, XmlElementPrelim::empty(name)))
        } else {
            let mut txn = self.0.transact_mut();
            YXmlElement(self.0.push_back(&mut txn, XmlElementPrelim::empty(name)))
        }
    }

    /// Appends a new instance of `YXmlText` as the last child of this XML node and returns it.
    #[wasm_bindgen(method, js_name = pushXmlText)]
    pub fn push_xml_text(&self, txn: &ImplicitTransaction) -> YXmlText {
        if let Some(txn) = get_txn_mut(txn) {
            YXmlText(self.0.push_back(txn, XmlTextPrelim::new("")))
        } else {
            let mut txn = self.0.transact_mut();
            YXmlText(self.0.push_back(&mut txn, XmlTextPrelim::new("")))
        }
    }

    /// Returns a first child of this XML node.
    /// It can be either `YXmlElement`, `YXmlText` or `undefined` if current node has not children.
    #[wasm_bindgen(method, js_name = firstChild)]
    pub fn first_child(&self) -> JsValue {
        if let Some(xml) = self.0.first_child() {
            xml_into_js(xml)
        } else {
            JsValue::undefined()
        }
    }

    /// Returns a next XML sibling node of this XMl node.
    /// It can be either `YXmlElement`, `YXmlText` or `undefined` if current node is a last child of
    /// parent XML node.
    #[wasm_bindgen(method, js_name = nextSibling)]
    pub fn next_sibling(&self, txn: &ImplicitTransaction) -> JsValue {
        if let Some(txn) = get_txn_mut(txn) {
            let mut siblings = self.0.siblings(txn);
            siblings
                .next()
                .map(xml_into_js)
                .unwrap_or(JsValue::UNDEFINED)
        } else {
            let txn = self.0.transact_mut();
            let mut siblings = self.0.siblings(&txn);
            siblings
                .next()
                .map(xml_into_js)
                .unwrap_or(JsValue::UNDEFINED)
        }
    }

    /// Returns a previous XML sibling node of this XMl node.
    /// It can be either `YXmlElement`, `YXmlText` or `undefined` if current node is a first child
    /// of parent XML node.
    #[wasm_bindgen(method, js_name = prevSibling)]
    pub fn prev_sibling(&self, txn: &ImplicitTransaction) -> JsValue {
        if let Some(txn) = get_txn_mut(txn) {
            let mut siblings = self.0.siblings(txn);
            siblings
                .next_back()
                .map(xml_into_js)
                .unwrap_or(JsValue::UNDEFINED)
        } else {
            let txn = self.0.transact_mut();
            let mut siblings = self.0.siblings(&txn);
            siblings
                .next_back()
                .map(xml_into_js)
                .unwrap_or(JsValue::UNDEFINED)
        }
    }

    /// Returns a parent `YXmlElement` node or `undefined` if current node has no parent assigned.
    #[wasm_bindgen(method, getter, js_name = parent)]
    pub fn parent(&self) -> JsValue {
        if let Some(xml) = self.0.parent() {
            xml_into_js(xml)
        } else {
            JsValue::undefined()
        }
    }

    /// Returns a string representation of this XML node.
    #[wasm_bindgen(method, js_name = toString)]
    pub fn to_string(&self, txn: &ImplicitTransaction) -> String {
        if let Some(txn) = get_txn(txn) {
            self.0.get_string(txn)
        } else {
            self.0.get_string(&self.0.transact())
        }
    }

    /// Sets a `name` and `value` as new attribute for this XML node. If an attribute with the same
    /// `name` already existed on that node, its value with be overridden with a provided one.
    #[wasm_bindgen(method, js_name = setAttribute)]
    pub fn set_attribute(&self, name: &str, value: &str, txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(txn) {
            self.0.insert_attribute(txn, name, value)
        } else {
            let mut txn = self.0.transact_mut();
            self.0.insert_attribute(&mut txn, name, value)
        }
    }

    /// Returns a value of an attribute given its `name`. If no attribute with such name existed,
    /// `null` will be returned.
    #[wasm_bindgen(method, js_name = getAttribute)]
    pub fn get_attribute(&self, name: &str, txn: &ImplicitTransaction) -> Option<String> {
        if let Some(txn) = get_txn(txn) {
            self.0.get_attribute(txn, name)
        } else {
            let txn = self.0.transact();
            self.0.get_attribute(&txn, name)
        }
    }

    /// Removes an attribute from this XML node, given its `name`.
    #[wasm_bindgen(method, js_name = removeAttribute)]
    pub fn remove_attribute(&self, name: &str, txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(txn) {
            self.0.remove_attribute(txn, &name);
        } else {
            let mut txn = self.0.transact_mut();
            self.0.remove_attribute(&mut txn, &name);
        }
    }

    /// Returns an iterator that enables to traverse over all attributes of this XML node in
    /// unspecified order.
    #[wasm_bindgen(method, js_name = attributes)]
    pub fn attributes(&self, txn: &ImplicitTransaction) -> JsValue {
        if let Some(txn) = get_txn(txn) {
            let attrs = self.0.attributes(txn);
            iter_to_map(attrs).into()
        } else {
            let txn = self.0.transact();
            let attrs = self.0.attributes(&txn);
            iter_to_map(attrs).into()
        }
    }

    /// Returns an iterator that enables a deep traversal of this XML node - starting from first
    /// child over this XML node successors using depth-first strategy.
    #[wasm_bindgen(method, js_name = treeWalker)]
    pub fn tree_walker(&self, txn: &ImplicitTransaction) -> JsValue {
        if let Some(txn) = get_txn(txn) {
            let tree_walker = self.0.successors(txn);
            iter_to_array(tree_walker).into()
        } else {
            let txn = self.0.transact();
            let tree_walker = self.0.successors(&txn);
            iter_to_array(tree_walker).into()
        }
    }

    /// Subscribes to all operations happening over this instance of `YXmlElement`. All changes are
    /// batched and eventually triggered during transaction commit phase.
    /// Returns an `YObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observe)]
    pub fn observe(&mut self, f: js_sys::Function) -> YXmlObserver {
        let sub = self.0.observe(move |txn, e| {
            let e = YXmlEvent::new(e, txn);
            let arg: JsValue = e.into();
            f.call1(&JsValue::UNDEFINED, &arg).unwrap();
        });
        YXmlObserver(sub)
    }

    /// Subscribes to all operations happening over this Y shared type, as well as events in
    /// shared types stored within this one. All changes are batched and eventually triggered
    /// during transaction commit phase.
    /// Returns an `YEventObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observeDeep)]
    pub fn observe_deep(&mut self, f: js_sys::Function) -> YEventObserver {
        let sub = self.0.observe_deep(move |txn, e| {
            let arg = events_into_js(txn, e);
            f.call1(&JsValue::UNDEFINED, &arg).unwrap();
        });
        YEventObserver(sub)
    }
}

/// Represents a list of `YXmlElement` and `YXmlText` types.
/// A `YXmlFragment` is similar to a `YXmlElement`, but it does not have a
/// nodeName and it does not have attributes. Though it can be bound to a DOM
/// element - in this case the attributes and the nodeName are not shared
#[wasm_bindgen]
pub struct YXmlFragment(XmlFragmentRef);

#[wasm_bindgen]
impl YXmlFragment {
    /// Returns a number of child XML nodes stored within this `YXMlElement` instance.
    #[wasm_bindgen(js_name = length)]
    pub fn length(&self, txn: &ImplicitTransaction) -> u32 {
        if let Some(txn) = get_txn(txn) {
            self.0.len(txn)
        } else {
            let txn = self.0.transact();
            self.0.len(&txn)
        }
    }

    /// Inserts a new instance of `YXmlElement` as a child of this XML node and returns it.
    #[wasm_bindgen(method, js_name = insertXmlElement)]
    pub fn insert_xml_element(
        &self,
        index: u32,
        name: &str,
        txn: &ImplicitTransaction,
    ) -> YXmlElement {
        if let Some(txn) = get_txn_mut(txn) {
            YXmlElement(self.0.insert(txn, index, XmlElementPrelim::empty(name)))
        } else {
            let mut txn = self.0.transact_mut();
            YXmlElement(
                self.0
                    .insert(&mut txn, index, XmlElementPrelim::empty(name)),
            )
        }
    }

    /// Inserts a new instance of `YXmlText` as a child of this XML node and returns it.
    #[wasm_bindgen(method, js_name = insertXmlText)]
    pub fn insert_xml_text(&self, index: u32, txn: &ImplicitTransaction) -> YXmlText {
        if let Some(txn) = get_txn_mut(txn) {
            YXmlText(self.0.insert(txn, index, XmlTextPrelim::new("")))
        } else {
            let mut txn = self.0.transact_mut();
            YXmlText(self.0.insert(&mut txn, index, XmlTextPrelim::new("")))
        }
    }

    /// Removes a range of children XML nodes from this `YXmlElement` instance,
    /// starting at given `index`.
    #[wasm_bindgen(method, js_name = delete)]
    pub fn delete(&self, index: u32, length: u32, txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(txn) {
            self.0.remove_range(txn, index, length)
        } else {
            let mut txn = self.0.transact_mut();
            self.0.remove_range(&mut txn, index, length)
        }
    }

    /// Appends a new instance of `YXmlElement` as the last child of this XML node and returns it.
    #[wasm_bindgen(method, js_name = pushXmlElement)]
    pub fn push_xml_element(&self, name: &str, txn: &ImplicitTransaction) -> YXmlElement {
        if let Some(txn) = get_txn_mut(txn) {
            YXmlElement(self.0.push_back(txn, XmlElementPrelim::empty(name)))
        } else {
            let mut txn = self.0.transact_mut();
            YXmlElement(self.0.push_back(&mut txn, XmlElementPrelim::empty(name)))
        }
    }

    /// Appends a new instance of `YXmlText` as the last child of this XML node and returns it.
    #[wasm_bindgen(method, js_name = pushXmlText)]
    pub fn push_xml_text(&self, txn: &ImplicitTransaction) -> YXmlText {
        if let Some(txn) = get_txn_mut(txn) {
            YXmlText(self.0.push_back(txn, XmlTextPrelim::new("")))
        } else {
            let mut txn = self.0.transact_mut();
            YXmlText(self.0.push_back(&mut txn, XmlTextPrelim::new("")))
        }
    }

    /// Returns a first child of this XML node.
    /// It can be either `YXmlElement`, `YXmlText` or `undefined` if current node has not children.
    #[wasm_bindgen(method, js_name = firstChild)]
    pub fn first_child(&self) -> JsValue {
        if let Some(xml) = self.0.first_child() {
            xml_into_js(xml)
        } else {
            JsValue::undefined()
        }
    }

    /// Returns a string representation of this XML node.
    #[wasm_bindgen(method, js_name = toString)]
    pub fn to_string(&self, txn: &ImplicitTransaction) -> String {
        if let Some(txn) = get_txn(txn) {
            self.0.get_string(txn)
        } else {
            self.0.get_string(&self.0.transact())
        }
    }

    /// Returns an iterator that enables a deep traversal of this XML node - starting from first
    /// child over this XML node successors using depth-first strategy.
    #[wasm_bindgen(method, js_name = treeWalker)]
    pub fn tree_walker(&self, txn: &ImplicitTransaction) -> JsValue {
        if let Some(txn) = get_txn(txn) {
            let tree_walker = self.0.successors(txn);
            iter_to_array(tree_walker).into()
        } else {
            let txn = self.0.transact();
            let tree_walker = self.0.successors(&txn);
            iter_to_array(tree_walker).into()
        }
    }

    /// Subscribes to all operations happening over this instance of `YXmlElement`. All changes are
    /// batched and eventually triggered during transaction commit phase.
    /// Returns an `YObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observe)]
    pub fn observe(&mut self, f: js_sys::Function) -> YXmlObserver {
        let sub = self.0.observe(move |txn, e| {
            let e = YXmlEvent::new(e, txn);
            let arg: JsValue = e.into();
            f.call1(&JsValue::UNDEFINED, &arg).unwrap();
        });
        YXmlObserver(sub)
    }

    /// Subscribes to all operations happening over this Y shared type, as well as events in
    /// shared types stored within this one. All changes are batched and eventually triggered
    /// during transaction commit phase.
    /// Returns an `YEventObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observeDeep)]
    pub fn observe_deep(&mut self, f: js_sys::Function) -> YEventObserver {
        let sub = self.0.observe_deep(move |txn, e| {
            let arg = events_into_js(txn, e);
            f.call1(&JsValue::UNDEFINED, &arg).unwrap();
        });
        YEventObserver(sub)
    }
}

/// A shared data type used for collaborative text editing, that can be used in a context of
/// `YXmlElement` nodee. It enables multiple users to add and remove chunks of text in efficient
/// manner. This type is internally represented as a mutable double-linked list of text chunks
/// - an optimization occurs during `YTransaction.commit`, which allows to squash multiple
/// consecutively inserted characters together as a single chunk of text even between transaction
/// boundaries in order to preserve more efficient memory model.
///
/// Just like `YXmlElement`, `YXmlText` can be marked with extra metadata in form of attributes.
///
/// `YXmlText` structure internally uses UTF-8 encoding and its length is described in a number of
/// bytes rather than individual characters (a single UTF-8 code point can consist of many bytes).
///
/// Like all Yrs shared data types, `YXmlText` is resistant to the problem of interleaving (situation
/// when characters inserted one after another may interleave with other peers concurrent inserts
/// after merging all updates together). In case of Yrs conflict resolution is solved by using
/// unique document id to determine correct and consistent ordering.
#[wasm_bindgen]
pub struct YXmlText(XmlTextRef);

#[wasm_bindgen]
impl YXmlText {
    /// Returns length of an underlying string stored in this `YXmlText` instance,
    /// understood as a number of UTF-8 encoded bytes.
    #[wasm_bindgen(method)]
    pub fn length(&self, txn: &ImplicitTransaction) -> u32 {
        if let Some(txn) = get_txn(txn) {
            self.0.len(txn)
        } else {
            let txn = self.0.transact();
            self.0.len(&txn)
        }
    }

    /// Inserts a given `chunk` of text into this `YXmlText` instance, starting at a given `index`.
    ///
    /// Optional object with defined `attributes` will be used to wrap provided text `chunk`
    /// with a formatting blocks.
    #[wasm_bindgen(method, js_name = insert)]
    pub fn insert(&self, index: i32, chunk: &str, attrs: JsValue, txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(txn) {
            if let Some(attrs) = YText::parse_attrs(attrs) {
                self.0
                    .insert_with_attributes(txn, index as u32, chunk, attrs)
            } else {
                self.0.insert(txn, index as u32, chunk)
            }
        } else {
            let mut txn = self.0.transact_mut();
            if let Some(attrs) = YText::parse_attrs(attrs) {
                self.0
                    .insert_with_attributes(&mut txn, index as u32, chunk, attrs)
            } else {
                self.0.insert(&mut txn, index as u32, chunk)
            }
        }
    }

    /// Formats text within bounds specified by `index` and `len` with a given formatting
    /// attributes.
    #[wasm_bindgen(method, js_name = format)]
    pub fn format(&self, index: i32, len: i32, attrs: JsValue, txn: &ImplicitTransaction) {
        if let Some(attrs) = YText::parse_attrs(attrs) {
            if let Some(txn) = get_txn_mut(txn) {
                self.0.format(txn, index as u32, len as u32, attrs)
            } else {
                let mut txn = self.0.transact_mut();
                self.0.format(&mut txn, index as u32, len as u32, attrs)
            }
        } else {
            panic!("couldn't parse format attributes")
        }
    }

    /// Inserts a given `embed` object into this `YXmlText` instance, starting at a given `index`.
    ///
    /// Optional object with defined `attributes` will be used to wrap provided `embed`
    /// with a formatting blocks.`attributes` are only supported for a `YXmlText` instance which
    /// already has been integrated into document store.
    #[wasm_bindgen(method, js_name = insertEmbed)]
    pub fn insert_embed(
        &self,
        index: u32,
        embed: JsValue,
        attributes: JsValue,
        txn: &ImplicitTransaction,
    ) {
        let content = js_into_any(&embed).unwrap();
        if let Some(txn) = get_txn_mut(txn) {
            if let Some(attrs) = YText::parse_attrs(attributes) {
                self.0
                    .insert_embed_with_attributes(txn, index, content, attrs);
            } else {
                self.0.insert_embed(txn, index, content);
            }
        } else {
            let mut txn = self.0.transact_mut();
            if let Some(attrs) = YText::parse_attrs(attributes) {
                self.0
                    .insert_embed_with_attributes(&mut txn, index, content, attrs);
            } else {
                self.0.insert_embed(&mut txn, index, content);
            }
        }
    }

    /// Appends a given `chunk` of text at the end of `YXmlText` instance.
    ///
    /// Optional object with defined `attributes` will be used to wrap provided text `chunk`
    /// with a formatting blocks.
    #[wasm_bindgen(method, js_name = push)]
    pub fn push(&self, chunk: &str, attrs: JsValue, txn: &ImplicitTransaction) {
        let index = if let Some(txn) = get_txn(txn) {
            self.0.len(txn)
        } else {
            let txn = self.0.transact();
            self.0.len(&txn)
        };
        self.insert(index as i32, chunk, attrs, txn)
    }

    /// Deletes a specified range of of characters, starting at a given `index`.
    /// Both `index` and `length` are counted in terms of a number of UTF-8 character bytes.
    #[wasm_bindgen(method, js_name = delete)]
    pub fn delete(&self, index: u32, length: u32, txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(txn) {
            self.0.remove_range(txn, index, length)
        } else {
            let mut txn = self.0.transact_mut();
            self.0.remove_range(&mut txn, index, length)
        }
    }

    /// Returns a next XML sibling node of this XMl node.
    /// It can be either `YXmlElement`, `YXmlText` or `undefined` if current node is a last child of
    /// parent XML node.
    #[wasm_bindgen(method, js_name = nextSibling)]
    pub fn next_sibling(&self, txn: &ImplicitTransaction) -> JsValue {
        if let Some(txn) = get_txn_mut(txn) {
            let mut siblings = self.0.siblings(txn);
            siblings
                .next()
                .map(xml_into_js)
                .unwrap_or(JsValue::UNDEFINED)
        } else {
            let txn = self.0.transact_mut();
            let mut siblings = self.0.siblings(&txn);
            siblings
                .next()
                .map(xml_into_js)
                .unwrap_or(JsValue::UNDEFINED)
        }
    }

    /// Returns a previous XML sibling node of this XMl node.
    /// It can be either `YXmlElement`, `YXmlText` or `undefined` if current node is a first child
    /// of parent XML node.
    #[wasm_bindgen(method, js_name = prevSibling)]
    pub fn prev_sibling(&self, txn: &ImplicitTransaction) -> JsValue {
        if let Some(txn) = get_txn_mut(txn) {
            let mut siblings = self.0.siblings(txn);
            siblings
                .next_back()
                .map(xml_into_js)
                .unwrap_or(JsValue::UNDEFINED)
        } else {
            let txn = self.0.transact_mut();
            let mut siblings = self.0.siblings(&txn);
            siblings
                .next_back()
                .map(xml_into_js)
                .unwrap_or(JsValue::UNDEFINED)
        }
    }

    /// Returns a parent `YXmlElement` node or `undefined` if current node has no parent assigned.
    #[wasm_bindgen(method, getter, js_name = parent)]
    pub fn parent(&self) -> JsValue {
        if let Some(xml) = self.0.parent() {
            xml_into_js(xml)
        } else {
            JsValue::undefined()
        }
    }

    /// Returns an underlying string stored in this `YXmlText` instance.
    #[wasm_bindgen(method, js_name = toString)]
    pub fn to_string(&self, txn: &ImplicitTransaction) -> String {
        if let Some(txn) = get_txn(txn) {
            self.0.get_string(txn)
        } else {
            let txn = self.0.transact();
            self.0.get_string(&txn)
        }
    }

    /// Sets a `name` and `value` as new attribute for this XML node. If an attribute with the same
    /// `name` already existed on that node, its value with be overridden with a provided one.
    #[wasm_bindgen(method, js_name = setAttribute)]
    pub fn set_attribute(&self, name: &str, value: &str, txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(txn) {
            self.0.insert_attribute(txn, name, value);
        } else {
            let mut txn = self.0.transact_mut();
            self.0.insert_attribute(&mut txn, name, value);
        }
    }

    /// Returns a value of an attribute given its `name`. If no attribute with such name existed,
    /// `null` will be returned.
    #[wasm_bindgen(method, js_name = getAttribute)]
    pub fn get_attribute(&self, name: &str, txn: &ImplicitTransaction) -> Option<String> {
        if let Some(txn) = get_txn(txn) {
            self.0.get_attribute(txn, name)
        } else {
            let txn = self.0.transact();
            self.0.get_attribute(&txn, name)
        }
    }

    /// Removes an attribute from this XML node, given its `name`.
    #[wasm_bindgen(method, js_name = removeAttribute)]
    pub fn remove_attribute(&self, name: &str, txn: &ImplicitTransaction) {
        if let Some(txn) = get_txn_mut(txn) {
            self.0.remove_attribute(txn, &name);
        } else {
            let mut txn = self.0.transact_mut();
            self.0.remove_attribute(&mut txn, &name);
        }
    }

    /// Returns an iterator that enables to traverse over all attributes of this XML node in
    /// unspecified order.
    #[wasm_bindgen(method, js_name = attributes)]
    pub fn attributes(&self, txn: &ImplicitTransaction) -> JsValue {
        if let Some(txn) = get_txn(txn) {
            let attrs = self.0.attributes(txn);
            iter_to_map(attrs).into()
        } else {
            let txn = self.0.transact();
            let attrs = self.0.attributes(&txn);
            iter_to_map(attrs).into()
        }
    }

    /// Subscribes to all operations happening over this instance of `YXmlText`. All changes are
    /// batched and eventually triggered during transaction commit phase.
    /// Returns an `YObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observe)]
    pub fn observe(&mut self, f: js_sys::Function) -> YXmlTextObserver {
        let sub = self.0.observe(move |txn, e| {
            let e = YXmlTextEvent::new(e, txn);
            let arg: JsValue = e.into();
            f.call1(&JsValue::UNDEFINED, &arg).unwrap();
        });
        YXmlTextObserver(sub)
    }

    /// Subscribes to all operations happening over this Y shared type, as well as events in
    /// shared types stored within this one. All changes are batched and eventually triggered
    /// during transaction commit phase.
    /// Returns an `YEventObserver` which, when free'd, will unsubscribe current callback.
    #[wasm_bindgen(method, js_name = observeDeep)]
    pub fn observe_deep(&mut self, f: js_sys::Function) -> YEventObserver {
        let sub = self.0.observe_deep(move |txn, e| {
            let arg = events_into_js(txn, e);
            f.call1(&JsValue::UNDEFINED, &arg).unwrap();
        });
        YEventObserver(sub)
    }
}

#[wasm_bindgen]
#[repr(transparent)]
pub struct YUndoManager(UndoManager);

#[wasm_bindgen]
impl YUndoManager {
    #[wasm_bindgen(constructor)]
    pub fn new(doc: &YDoc, scope: JsValue, options: JsValue) -> Self {
        let doc = &doc.0;
        let scope = JsValueWrapper(scope);
        let mut o = yrs::undo::Options::default();
        o.timestamp = Rc::new(|| js_sys::Date::now() as u64);
        if options.is_object() {
            if let Ok(js) = Reflect::get(&options, &JsValue::from_str("captureTimeout")) {
                if let Some(millis) = js.as_f64() {
                    o.capture_timeout_millis = millis as u64;
                }
            }
            if let Ok(js) = Reflect::get(&options, &JsValue::from_str("trackedOrigins")) {
                if js_sys::Array::is_array(&js) {
                    let array = js_sys::Array::from(&js);
                    for js in array.iter() {
                        let v = JsValueWrapper(js);
                        o.tracked_origins.insert(v.into());
                    }
                }
            }
        }
        YUndoManager(UndoManager::with_options(doc, &scope, o))
    }

    #[wasm_bindgen(method, js_name = addToScope)]
    pub fn add_to_scope(&mut self, ytypes: js_sys::Array) {
        for js in ytypes.iter() {
            let scope = JsValueWrapper(js);
            self.0.expand_scope(&scope);
        }
    }

    #[wasm_bindgen(method, js_name = addTrackedOrigin)]
    pub fn add_tracked_origin(&mut self, origin: JsValue) {
        self.0.include_origin(JsValueWrapper(origin))
    }

    #[wasm_bindgen(method, js_name = removeTrackedOrigin)]
    pub fn remove_tracked_origin(&mut self, origin: JsValue) {
        self.0.exclude_origin(JsValueWrapper(origin))
    }

    #[wasm_bindgen(method, catch, js_name = clear)]
    pub fn clear(&mut self) -> Result<(), JsValue> {
        if let Err(err) = self.0.clear() {
            Err(JsValue::from_str(&err.to_string()))
        } else {
            Ok(())
        }
    }

    #[wasm_bindgen(method, js_name = stopCapturing)]
    pub fn stop_capturing(&mut self) {
        self.0.reset()
    }

    #[wasm_bindgen(method, catch, js_name = undo)]
    pub fn undo(&mut self) -> Result<(), JsValue> {
        if let Err(err) = self.0.undo() {
            Err(JsValue::from_str(&err.to_string()))
        } else {
            Ok(())
        }
    }

    #[wasm_bindgen(method, catch, js_name = redo)]
    pub fn redo(&mut self) -> Result<(), JsValue> {
        if let Err(err) = self.0.redo() {
            Err(JsValue::from_str(&err.to_string()))
        } else {
            Ok(())
        }
    }

    #[wasm_bindgen(method, getter, js_name = canUndo)]
    pub fn can_undo(&mut self) -> bool {
        self.0.can_undo()
    }

    #[wasm_bindgen(method, getter, js_name = canRedo)]
    pub fn can_redo(&mut self) -> bool {
        self.0.can_redo()
    }

    #[wasm_bindgen(method, js_name = onStackItemAdded)]
    pub fn on_item_added(&mut self, callback: js_sys::Function) -> YUndoObserver {
        YUndoObserver(self.0.observe_item_added(move |_, e| {
            let arg: JsValue = YUndoEvent::new(e).into();
            callback.call1(&JsValue::UNDEFINED, &arg).unwrap();
        }))
    }

    #[wasm_bindgen(method, js_name = onStackItemPopped)]
    pub fn on_item_popped(&mut self, callback: js_sys::Function) -> YUndoObserver {
        YUndoObserver(self.0.observe_item_popped(move |_, e| {
            let arg: JsValue = YUndoEvent::new(e).into();
            callback.call1(&JsValue::UNDEFINED, &arg).unwrap();
        }))
    }
}

#[wasm_bindgen]
pub struct YUndoEvent {
    origin: JsValue,
    kind: JsValue,
    stack_item: JsValue,
}

#[wasm_bindgen]
impl YUndoEvent {
    #[wasm_bindgen(method, getter, js_name = origin)]
    pub fn origin(&self) -> JsValue {
        self.origin.clone()
    }
    #[wasm_bindgen(method, getter, js_name = kind)]
    pub fn kind(&self) -> JsValue {
        self.kind.clone()
    }
    #[wasm_bindgen(method, getter, js_name = stackItem)]
    pub fn stack_item(&self) -> JsValue {
        self.stack_item.clone()
    }

    fn new(e: &yrs::undo::Event) -> Self {
        let stack_item: JsValue = Object::new().into();
        Reflect::set(
            &stack_item,
            &JsValue::from_str("deletions"),
            &delete_set_into_map(e.item.deletions()),
        )
        .unwrap();
        Reflect::set(
            &stack_item,
            &JsValue::from_str("insertions"),
            &delete_set_into_map(e.item.insertions()),
        )
        .unwrap();
        YUndoEvent {
            stack_item,
            origin: e
                .origin
                .as_ref()
                .map(|origin| Uint8Array::from(origin.as_ref()).into())
                .unwrap_or(JsValue::NULL),
            kind: match e.kind {
                EventKind::Undo => JsValue::from_str("undo"),
                EventKind::Redo => JsValue::from_str("redo"),
            },
        }
    }
}

#[wasm_bindgen]
pub struct YUndoObserver(UndoEventSubscription);

#[repr(transparent)]
struct JsValueWrapper(JsValue);

impl Prelim for JsValueWrapper {
    type Return = Unused;

    fn into_content(self, _txn: &mut TransactionMut) -> (ItemContent, Option<Self>) {
        let content = if let Some(any) = js_into_any(&self.0) {
            ItemContent::Any(vec![any])
        } else if let Ok(shared) = Shared::try_from(&self.0) {
            if shared.is_prelim() {
                let branch = Branch::new(shared.type_ref(), None);
                ItemContent::Type(branch)
            } else if let Shared::Doc(doc) = shared {
                if doc.0.parent_doc().is_some() {
                    panic!("Cannot integrate document, that has been already integrated elsewhere")
                } else {
                    ItemContent::Doc(None, doc.0.clone())
                }
            } else {
                panic!("Cannot integrate this type")
            }
        } else {
            panic!("Cannot integrate this type")
        };

        let this = if let ItemContent::Type(_) = &content {
            Some(self)
        } else {
            None
        };

        (content, this)
    }

    fn integrate(self, txn: &mut TransactionMut, inner_ref: BranchPtr) {
        if let Ok(shared) = Shared::try_from(&self.0) {
            if shared.is_prelim() {
                match shared {
                    Shared::Text(v) => {
                        let text = TextRef::from(inner_ref);
                        if let SharedType::Prelim(v) =
                            v.0.replace(SharedType::Integrated(text.clone()))
                        {
                            text.push(txn, v.as_str());
                        }
                    }
                    Shared::Array(v) => {
                        let array = ArrayRef::from(inner_ref);
                        if let SharedType::Prelim(items) =
                            v.0.replace(SharedType::Integrated(array.clone()))
                        {
                            let len = array.len(txn);
                            insert_at(&array, txn, len, items);
                        }
                    }
                    Shared::Map(v) => {
                        let map = MapRef::from(inner_ref);
                        if let SharedType::Prelim(entries) =
                            v.0.replace(SharedType::Integrated(map.clone()))
                        {
                            for (k, v) in entries {
                                map.insert(txn, k, JsValueWrapper(v));
                            }
                        }
                    }
                    _ => panic!("Cannot integrate this type"),
                }
            }
        }
    }
}

impl Into<Origin> for JsValueWrapper {
    fn into(self) -> Origin {
        if let Ok(branch) = self.as_branch_ptr() {
            BranchPtr::from(branch).into()
        } else {
            let ptr = self.0.into_abi();
            let bytes = ptr.to_be_bytes();
            Origin::from(bytes.as_ref())
        }
    }
}

impl AsRef<Branch> for JsValueWrapper {
    fn as_ref(&self) -> &Branch {
        let ptr = self.as_branch_ptr().unwrap();
        let branch = ptr.deref();
        unsafe { std::mem::transmute(branch) }
    }
}

impl JsValueWrapper {
    fn as_branch_ptr<'a>(&'a self) -> Result<BranchPtr, JsValue> {
        let s = Shared::<'a>::try_from(&self.0)?;
        match s {
            Shared::Text(v) => {
                if let SharedType::Integrated(x) = v.0.borrow().deref() {
                    Ok(BranchPtr::from(x.as_ref()))
                } else {
                    Err(JsValue::from_str(
                        "Shared type must be integrated first to be used in this context",
                    ))
                }
            }
            Shared::Array(v) => {
                if let SharedType::Integrated(x) = v.0.borrow().deref() {
                    Ok(BranchPtr::from(x.as_ref()))
                } else {
                    Err(JsValue::from_str(
                        "Shared type must be integrated first to be used in this context",
                    ))
                }
            }
            Shared::Map(v) => {
                if let SharedType::Integrated(x) = v.0.borrow().deref() {
                    Ok(BranchPtr::from(x.as_ref()))
                } else {
                    Err(JsValue::from_str(
                        "Shared type must be integrated first to be used in this context",
                    ))
                }
            }
            Shared::XmlElement(v) => Ok(BranchPtr::from(v.deref().0.as_ref())),
            Shared::XmlText(v) => Ok(BranchPtr::from(v.deref().0.as_ref())),
            Shared::XmlFragment(v) => Ok(BranchPtr::from(v.deref().0.as_ref())),
            Shared::Doc(_) => Err(JsValue::from_str("Doc is not a shared type")),
        }
    }
}

fn insert_at(dst: &ArrayRef, txn: &mut TransactionMut, index: u32, src: Vec<JsValue>) {
    let mut j = index;
    let mut i = 0;
    while i < src.len() {
        let mut anys = Vec::default();
        while i < src.len() {
            let js = &src[i];
            if let Some(any) = js_into_any(js) {
                anys.push(any);
                i += 1;
            } else {
                break;
            }
        }

        if !anys.is_empty() {
            let len = anys.len() as u32;
            dst.insert_range(txn, j, anys);
            j += len;
        } else {
            let js = &src[i];
            let wrapper = JsValueWrapper(js.clone());
            dst.insert(txn, j, wrapper);
            i += 1;
            j += 1;
        }
    }
}

fn js_into_any(v: &JsValue) -> Option<Any> {
    if v.is_string() {
        Some(Any::String(v.as_string()?.into_boxed_str()))
    } else if v.is_bigint() {
        let i = js_sys::BigInt::from(v.clone()).as_f64()?;
        Some(Any::BigInt(i as i64))
    } else if v.is_null() {
        Some(Any::Null)
    } else if v.is_undefined() {
        Some(Any::Undefined)
    } else if let Some(f) = v.as_f64() {
        Some(Any::Number(f))
    } else if let Some(b) = v.as_bool() {
        Some(Any::Bool(b))
    } else if js_sys::Array::is_array(v) {
        let array = js_sys::Array::from(v);
        let mut result = Vec::with_capacity(array.length() as usize);
        for value in array.iter() {
            result.push(js_into_any(&value)?);
        }
        Some(Any::Array(result.into_boxed_slice()))
    } else if v.is_object() {
        if let Ok(_) = Shared::try_from(v) {
            None
        } else {
            let mut map = HashMap::new();
            let object = js_sys::Object::from(v.clone());
            let entries = js_sys::Object::entries(&object);
            for tuple in entries.iter() {
                let tuple = js_sys::Array::from(&tuple);
                let key: String = tuple.get(0).as_string()?;
                let value = js_into_any(&tuple.get(1))?;
                map.insert(key, value);
            }
            Some(Any::Map(Box::new(map)))
        }
    } else {
        None
    }
}

fn any_into_js(v: &Any) -> JsValue {
    match v {
        Any::Null => JsValue::NULL,
        Any::Undefined => JsValue::UNDEFINED,
        Any::Bool(v) => JsValue::from_bool(*v),
        Any::Number(v) => JsValue::from(*v),
        Any::BigInt(v) => JsValue::from(*v),
        Any::String(v) => JsValue::from(v.as_ref()),
        Any::Buffer(v) => {
            let v = Uint8Array::from(v.as_ref());
            v.into()
        }
        Any::Array(v) => {
            let a = js_sys::Array::new();
            for value in v.as_ref() {
                a.push(&any_into_js(value));
            }
            a.into()
        }
        Any::Map(v) => {
            let m = js_sys::Object::new();
            for (k, v) in v.as_ref() {
                let key = JsValue::from(k);
                let value = any_into_js(v);
                js_sys::Reflect::set(&m, &key, &value).unwrap();
            }
            m.into()
        }
    }
}

fn value_into_js(v: Value) -> JsValue {
    match v {
        Value::Any(v) => any_into_js(&v),
        Value::YText(v) => YText::from(v).into(),
        Value::YArray(v) => YArray::from(v).into(),
        Value::YMap(v) => YMap::from(v).into(),
        Value::YXmlElement(v) => YXmlElement(v).into(),
        Value::YXmlText(v) => YXmlText(v).into(),
        Value::YXmlFragment(v) => YXmlFragment(v).into(),
        Value::YDoc(doc) => YDoc::from(doc).into(),
    }
}

fn xml_into_js(v: XmlNode) -> JsValue {
    match v {
        XmlNode::Element(v) => YXmlElement(v).into(),
        XmlNode::Text(v) => YXmlText(v).into(),
        XmlNode::Fragment(v) => YXmlFragment(v).into(),
    }
}

fn events_into_js(txn: &TransactionMut, e: &Events) -> JsValue {
    let mut array = js_sys::Array::new();
    let mapped = e.iter().map(|e| {
        let js: JsValue = match e {
            Event::Text(e) => YTextEvent::new(e, txn).into(),
            Event::Array(e) => YArrayEvent::new(e, txn).into(),
            Event::Map(e) => YMapEvent::new(e, txn).into(),
            Event::XmlText(e) => YXmlTextEvent::new(e, txn).into(),
            Event::XmlFragment(e) => YXmlEvent::new(e, txn).into(),
        };
        js
    });
    array.extend(mapped);
    array.into()
}

enum Shared<'a> {
    Text(Ref<'a, YText>),
    Array(Ref<'a, YArray>),
    Map(Ref<'a, YMap>),
    XmlElement(Ref<'a, YXmlElement>),
    XmlText(Ref<'a, YXmlText>),
    XmlFragment(Ref<'a, YXmlFragment>),
    Doc(Ref<'a, YDoc>),
}

fn as_ref<'a, T>(js: u32) -> Ref<'a, T> {
    unsafe {
        let js = js as *mut wasm_bindgen::__rt::WasmRefCell<T>;
        (*js).borrow()
    }
}

impl<'a> TryFrom<&'a JsValue> for Shared<'a> {
    type Error = JsValue;

    fn try_from(js: &'a JsValue) -> Result<Self, Self::Error> {
        let ctor_name = Object::get_prototype_of(js).constructor().name();
        let ptr = Reflect::get(js, &JsValue::from_str("ptr"))?;
        let ptr_u32: u32 = ptr.as_f64().ok_or(JsValue::NULL)? as u32;

        if ctor_name == "YText" {
            Ok(Shared::Text(as_ref(ptr_u32)))
        } else if ctor_name == "YArray" {
            Ok(Shared::Array(as_ref(ptr_u32)))
        } else if ctor_name == "YMap" {
            Ok(Shared::Map(as_ref(ptr_u32)))
        } else if ctor_name == "YXmlElement" {
            Ok(Shared::XmlElement(as_ref(ptr_u32)))
        } else if ctor_name == "YXmlText" {
            Ok(Shared::XmlText(as_ref(ptr_u32)))
        } else if ctor_name == "YXmlFragment" {
            Ok(Shared::XmlFragment(as_ref(ptr_u32)))
        } else if ctor_name == "YDoc" {
            Ok(Shared::Doc(as_ref(ptr_u32)))
        } else {
            Err(ctor_name.into())
        }
    }
}

impl<'a> Shared<'a> {
    fn is_prelim(&self) -> bool {
        match self {
            Shared::Text(v) => v.prelim(),
            Shared::Array(v) => v.prelim(),
            Shared::Map(v) => v.prelim(),
            Shared::Doc(_)
            | Shared::XmlElement(_)
            | Shared::XmlText(_)
            | Shared::XmlFragment(_) => false,
        }
    }

    fn type_ref(&self) -> TypeRefs {
        match self {
            Shared::Text(_) => TYPE_REFS_TEXT,
            Shared::Array(_) => TYPE_REFS_ARRAY,
            Shared::Map(_) => TYPE_REFS_MAP,
            Shared::XmlElement(_) => TYPE_REFS_XML_ELEMENT,
            Shared::XmlText(_) => TYPE_REFS_XML_TEXT,
            Shared::XmlFragment(_) => TYPE_REFS_XML_FRAGMENT,
            Shared::Doc(_) => TYPE_REFS_DOC,
        }
    }

    fn branch(&self) -> Option<BranchPtr> {
        match self {
            Shared::Text(v) => {
                let inner = v.0.borrow();
                let integrated = inner.as_integrated()?;
                Some(BranchPtr::from(integrated.as_ref()))
            }
            Shared::Array(v) => {
                let inner = v.0.borrow();
                let integrated = inner.as_integrated()?;
                Some(BranchPtr::from(integrated.as_ref()))
            }
            Shared::Map(v) => {
                let inner = v.0.borrow();
                let integrated = inner.as_integrated()?;
                Some(BranchPtr::from(integrated.as_ref()))
            }
            Shared::XmlElement(v) => Some(BranchPtr::from(v.0.as_ref())),
            Shared::XmlText(v) => Some(BranchPtr::from(v.0.as_ref())),
            Shared::XmlFragment(v) => Some(BranchPtr::from(v.0.as_ref())),
            Shared::Doc(_) => None,
        }
    }
}

/// Retrieves a sticky index corresponding to a given human-readable `index` pointing into
/// the shared `ytype`. Unlike standard indexes sticky indexes enables to track
/// the location inside of a shared y-types, even in the face of concurrent updates.
///
/// If association is >= 0, the resulting position will point to location **after** the referenced index.
/// If association is < 0, the resulting position will point to location **before** the referenced index.
#[wasm_bindgen(catch, js_name=createStickyIndexFromType)]
pub fn create_sticky_index_from_type(
    ytype: &JsValue,
    index: u32,
    assoc: i32,
    txn: &ImplicitTransaction,
) -> Result<JsValue, JsValue> {
    if let Ok(shared) = Shared::try_from(ytype) {
        if shared.is_prelim() {
            return Err(JsValue::from_str(
                "cannot build sticky index if shared type was not integrated",
            ));
        }
        let assoc = if assoc >= 0 {
            Assoc::After
        } else {
            Assoc::Before
        };
        if let Some(branch) = shared.branch() {
            let pos = if let Some(txn) = get_txn_mut(txn) {
                StickyIndex::at(txn, branch, index, assoc)
            } else {
                let mut txn = branch.transact_mut();
                StickyIndex::at(&mut txn, branch, index, assoc)
            };
            let result = if let Some(pos) = pos {
                Ok(pos.into_js())
            } else {
                Ok(JsValue::NULL)
            };
            return result;
        }
    }
    Err(JsValue::from_str("shared type parameter is not indexable"))
}

/// Converts a sticky index (see: `createStickyIndexFromType`) into an object
/// containing human-readable index.
#[wasm_bindgen(catch, js_name=createOffsetFromStickyIndex)]
pub fn create_offset_from_sticky_index(rpos: &JsValue, doc: &YDoc) -> Result<JsValue, JsValue> {
    let pos = sticky_index_from_js(rpos)?;
    let txn = doc.0.transact();
    if let Some(abs) = pos.get_offset(&txn) {
        Ok(abs.into_js())
    } else {
        Ok(JsValue::NULL)
    }
}

/// Serializes sticky index created by `createStickyIndexFromType` into a binary
/// payload.
#[wasm_bindgen(catch, js_name=encodeStickyIndex)]
pub fn encode_sticky_index(rpos: &JsValue) -> Result<Uint8Array, JsValue> {
    if let Ok(pos) = sticky_index_from_js(rpos) {
        let bytes = Uint8Array::from(pos.encode_v1().as_slice());
        Ok(bytes)
    } else {
        Err(JsValue::from_str("passed parameter is not StickyIndex"))
    }
}

/// Deserializes sticky index serialized previously by `encodeStickyIndex`.
#[wasm_bindgen(catch, js_name=decodeStickyIndex)]
pub fn decode_sticky_index(bin: Uint8Array) -> Result<JsValue, JsValue> {
    let data: Vec<u8> = bin.to_vec();
    match StickyIndex::decode_v1(&data) {
        Ok(value) => Ok(value.into_js()),
        Err(err) => Err(JsValue::from_str(&err.to_string())),
    }
}

fn sticky_index_from_js(js: &JsValue) -> Result<StickyIndex, JsValue> {
    let value = Reflect::get(js, &JsValue::from_str("item"))?;
    let context = if value.is_undefined() || value.is_null() {
        let value = Reflect::get(js, &JsValue::from_str("tname"))?;
        if value.is_undefined() || value.is_null() {
            let value = Reflect::get(js, &JsValue::from_str("type"))?;
            let id = id_from_js(&value)?;
            IndexScope::Nested(id)
        } else {
            if let Some(tname) = value.as_string() {
                IndexScope::Root(tname.into())
            } else {
                return Err(value);
            }
        }
    } else {
        let id = id_from_js(&value)?;
        IndexScope::Relative(id)
    };
    let assoc = Reflect::get(js, &JsValue::from_str("assoc"))?;
    let assoc = if let Some(a) = assoc.as_f64() {
        if a >= 0.0 {
            Assoc::After
        } else {
            Assoc::Before
        }
    } else {
        return Err(assoc);
    };

    Ok(StickyIndex::new(context, assoc))
}

fn id_from_js(js: &JsValue) -> Result<ID, JsValue> {
    let value = Reflect::get(js, &JsValue::from_str("client"))?;
    let client = if let Ok(client) = u64::try_from(value) {
        client as ClientID
    } else {
        return Err(JsValue::from_str("ID.client was not a number"));
    };
    let value = Reflect::get(js, &JsValue::from_str("clock"))?;
    let clock = if let Some(clock) = value.as_f64() {
        clock as u32
    } else {
        return Err(JsValue::from_str("ID.clock was not a number"));
    };
    Ok(ID::new(client, clock))
}

impl IntoJs for ID {
    fn into_js(self) -> JsValue {
        let js: JsValue = js_sys::Object::new().into();
        Reflect::set(
            &js,
            &JsValue::from_str("client"),
            &JsValue::from(self.client),
        )
        .unwrap();
        Reflect::set(&js, &JsValue::from_str("clock"), &JsValue::from(self.clock)).unwrap();
        js
    }
}

impl IntoJs for StickyIndex {
    fn into_js(self) -> JsValue {
        let js: JsValue = js_sys::Object::new().into();

        match self.scope() {
            IndexScope::Relative(id) => {
                Reflect::set(&js, &JsValue::from_str("item"), &id.into_js()).unwrap();
            }
            IndexScope::Nested(id) => {
                Reflect::set(&js, &JsValue::from_str("type"), &id.into_js()).unwrap();
            }
            IndexScope::Root(tname) => {
                Reflect::set(&js, &JsValue::from_str("tname"), &JsValue::from_str(&tname)).unwrap();
            }
        }

        let assoc = match self.assoc {
            Assoc::After => 0,
            Assoc::Before => -1,
        };
        Reflect::set(&js, &JsValue::from_str("assoc"), &JsValue::from(assoc)).unwrap();
        js
    }
}

impl IntoJs for Offset {
    fn into_js(self) -> JsValue {
        let js: JsValue = js_sys::Object::new().into();
        Reflect::set(&js, &JsValue::from_str("index"), &JsValue::from(self.index)).unwrap();
        let assoc = match self.assoc {
            Assoc::After => 0,
            Assoc::Before => -1,
        };
        Reflect::set(&js, &JsValue::from_str("assoc"), &JsValue::from(assoc)).unwrap();
        js
    }
}