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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { last, isNil, repeat, reverse, dropLast as dropLast$2, adjust, compose } from '@react-pdf/fns';
import bidiFactory from 'bidi-js';
import unicode from 'unicode-properties';
import hyphen from 'hyphen';
import pattern from 'hyphen/patterns/en-us.js';

/**
 * Scripts requiring NFD decomposition for correct glyph-to-string mapping.
 * In these complex scripts, fontkit's glyph output after OpenType shaping
 * can produce codepoints that don't match the NFC input, making index
 * mapping unreliable. NFD produces codepoints that align with fontkit's output.
 *
 * Latin, Greek, Cyrillic and other simple scripts are excluded because
 * fontkit handles their NFC forms correctly.
 */
const SCRIPTS_NEEDING_DECOMPOSITION = [
    'Bengali',
    'Devanagari',
    'Gujarati',
    'Gurmukhi',
    'Kannada',
    'Khmer',
    'Malayalam',
    'Myanmar',
    'Oriya',
    'Sinhala',
    'Tamil',
    'Telugu',
    'Tibetan',
];
const scriptPattern = SCRIPTS_NEEDING_DECOMPOSITION.map((s) => `\\p{Script=${s}}`).join('|');
const HAS_COMPLEX_SCRIPT = new RegExp(scriptPattern, 'u');
const COMPLEX_SCRIPT_CHARS = new RegExp(`(?:${scriptPattern})+`, 'gu');
/**
 * Selectively applies NFD decomposition only to characters from complex
 * scripts that need it for correct glyph mapping. Other scripts remain
 * in their original (NFC) form since fontkit handles them correctly.
 */
const selectiveNFD = (str) => {
    if (!HAS_COMPLEX_SCRIPT.test(str))
        return str;
    return str.replace(COMPLEX_SCRIPT_CHARS, (match) => match.normalize('NFD'));
};
const isCustomFont = (run) => {
    const font = run.attributes?.font?.[0];
    return !!font && font.type !== 'STANDARD';
};
/**
 * Selectively decomposes Unicode characters in an attributed string.
 * Only characters from complex scripts (Indic, Southeast Asian) are
 * NFD-decomposed for custom fonts. Latin and other simple scripts
 * remain in NFC form.
 *
 * @returns Layout step that transforms an attributed string
 */
const decomposeUnicode = () => {
    return (attributedString) => {
        let string = '';
        let offset = 0;
        const runs = [];
        for (let i = 0; i < attributedString.runs.length; i += 1) {
            const run = attributedString.runs[i];
            const rawString = attributedString.string.slice(run.start, run.end);
            const runString = isCustomFont(run) ? selectiveNFD(rawString) : rawString;
            const fragmentLength = runString.length;
            runs.push({
                ...run,
                start: offset,
                end: offset + fragmentLength,
            });
            offset += fragmentLength;
            string += runString;
        }
        return { ...attributedString, string, runs };
    };
};

/**
 * Create attributed string from text fragments
 *
 * @param fragments - Fragments
 * @returns Attributed string
 */
const fromFragments = (fragments) => {
    let offset = 0;
    const strings = [];
    const runs = [];
    for (let i = 0; i < fragments.length; i += 1) {
        const fragment = fragments[i];
        const fragmentLength = fragment.string.length;
        strings.push(fragment.string);
        runs.push({
            ...fragment,
            start: offset,
            end: offset + fragmentLength,
            attributes: fragment.attributes || {},
        });
        offset += fragmentLength;
    }
    return { string: strings.join(''), runs };
};

const SOFT_HYPHEN$1 = '\u00ad';
/**
 * Default word hyphenation engine used when no one provided.
 * Does not perform word hyphenation at all
 *
 * @param word
 * @returns Same word
 */
const defaultHyphenate = (word) => [word];
/**
 * Remove soft hyphens from word
 *
 * @param word
 * @returns Word without soft hyphens
 */
const removeSoftHyphens = (word) => {
    return word.replaceAll(SOFT_HYPHEN$1, '');
};
/**
 * Wrap words of attribute string
 *
 * @param engines layout engines
 * @param options layout options
 */
const wrapWords = (engines = {}, options = {}) => {
    /**
     * @param attributedString - Attributed string
     * @returns Attributed string including syllables
     */
    return (attributedString) => {
        const syllables = [];
        const fragments = [];
        const builtinHyphenate = engines.wordHyphenation?.() || defaultHyphenate;
        const hyphenate = options.hyphenationCallback || builtinHyphenate;
        let offset = 0;
        for (let i = 0; i < attributedString.runs.length; i += 1) {
            let string = '';
            const run = attributedString.runs[i];
            const words = attributedString.string
                .slice(run.start, run.end)
                .split(/([ ]+)/g)
                .filter(Boolean);
            for (let j = 0; j < words.length; j += 1) {
                const word = words[j];
                const parts = hyphenate(word, builtinHyphenate).map(removeSoftHyphens);
                syllables.push(...parts);
                string += parts.join('');
            }
            // Modify run start and end based on removed soft hyphens.
            const runOffset = run.end - run.start - string.length;
            const start = run.start - offset;
            const end = run.end - offset - runOffset;
            fragments.push({ ...run, start, end, string });
            offset += runOffset;
        }
        const result = { ...fromFragments(fragments), syllables };
        return result;
    };
};

/**
 * Clone rect
 *
 * @param rect - Rect
 * @returns Cloned rect
 */
const copy = (rect) => {
    return Object.assign({}, rect);
};

/**
 * Partition rect in two in the vertical direction
 *
 * @param rect - Rect
 * @param height - Height
 * @returns Partitioned rects
 */
const partition = (rect, height) => {
    const a = Object.assign({}, rect, { height });
    const b = Object.assign({}, rect, {
        y: rect.y + height,
        height: rect.height - height,
    });
    return [a, b];
};

/**
 * Crop upper section of rect
 *
 * @param height - Height
 * @param rect - Rect
 * @returns Cropped rect
 */
const crop = (height, rect) => {
    const [, result] = partition(rect, height);
    return result;
};

/**
 * Get paragraph block height
 *
 * @param paragraph - Paragraph
 * @returns Paragraph block height
 */
const height$2 = (paragraph) => {
    return paragraph.reduce((acc, block) => acc + block.box.height, 0);
};

/**
 * Calculate run scale
 *
 * @param run - Run
 * @returns Scale
 */
const calculateScale = (run) => {
    const attributes = run.attributes || {};
    const fontSize = attributes.fontSize || 12;
    const font = attributes.font;
    const unitsPerEm = typeof font === 'string' ? null : font?.[0]?.unitsPerEm;
    return unitsPerEm ? fontSize / unitsPerEm : 0;
};
/**
 * Get run scale
 *
 * @param  run
 * @returns Scale
 */
const scale = (run) => {
    return run.attributes?.scale || calculateScale(run);
};

/**
 * Get ligature offset by index
 *
 * Ex. ffi ligature
 *
 *   glyphs:         l  o  f  f  i  m
 *   stringIndices:   0  1  2  2  2  3
 *   offset:         0  0  0  1  2  0
 *
 * @param index
 * @param run - Run
 * @returns Ligature offset
 */
const offset = (index, run) => {
    if (!run)
        return 0;
    const stringIndices = run.stringIndices || [];
    const value = stringIndices[index];
    return stringIndices.slice(0, index).filter((i) => i === value).length;
};

/**
 * Get run font
 *
 * @param run - Run
 * @returns Font
 */
const getFont = (run) => {
    return run.attributes?.font?.[0] || null;
};

/**
 * Slice glyph between codePoints range.
 * Useful for breaking ligatures into individual glyphs.
 *
 * @param start - Start code point index
 * @param end - End code point index
 * @param font - Font to generate new glyphs from
 * @param glyph - Glyph to be sliced
 * @returns Array of sliced glyph parts
 */
const slice$2 = (start, end, font, glyph) => {
    if (!glyph)
        return [];
    if (start === end)
        return [];
    const { codePoints } = glyph;
    if (start === 0 && end === codePoints.length)
        return [glyph];
    if (!font)
        return [glyph];
    const slicedCodePoints = codePoints.slice(start, end);
    const string = String.fromCodePoint(...slicedCodePoints);
    // Force LTR direction to prevent fontkit from reversing the string
    return font.layout(string, undefined, undefined, undefined, 'ltr').glyphs;
};

/**
 * Return last glyph index that maps to the given string index.
 * Falls back to the string index itself if glyphIndices is not present.
 *
 * When multiple consecutive glyphs point to the same string index
 * (e.g. decomposed characters), returns the last glyph in that group.
 *
 * @param index - String index
 * @param run - Run
 * @returns Glyph index
 */
const glyphIndexAt = (index, run) => {
    const glyphIndices = run?.glyphIndices;
    if (!glyphIndices)
        return index;
    // If index is past all glyph mappings, return length (one past end)
    if (glyphIndices.length > 0 &&
        index > glyphIndices[glyphIndices.length - 1]) {
        return glyphIndices.length;
    }
    let result = index;
    for (let i = glyphIndices.length - 1; i >= 0; i -= 1) {
        if (glyphIndices[i] <= index) {
            result = i;
            break;
        }
    }
    return result;
};

/**
 * Returns new array starting with zero, keeping the same relation between consecutive values.
 *
 * @param array - List of numbers
 * @returns Normalized array starting at zero
 */
const normalize = (array) => {
    if (array.length === 0)
        return [];
    const offset = array[0];
    return array.map((value) => value - offset);
};

/**
 * Slice run between string indices range
 *
 * @param start - String index
 * @param end - String index
 * @param run - Run
 * @returns Sliced run
 */
const slice$1 = (start, end, run) => {
    const runScale = scale(run);
    const font = getFont(run);
    // Get glyph start and end indices
    const startIndex = glyphIndexAt(start, run);
    const endIndex = glyphIndexAt(end - 1, run);
    // Get start and end glyph
    const startGlyph = run.glyphs?.[startIndex];
    const endGlyph = run.glyphs?.[endIndex];
    // Get start ligature chunks (if any)
    const startOffset = offset(start, run);
    const startGlyphs = startOffset > 0 ? slice$2(startOffset, Infinity, font, startGlyph) : [];
    // Get end ligature chunks (if any)
    const endOffset = offset(end, run);
    const endGlyphs = slice$2(0, endOffset, font, endGlyph);
    // Compute new glyphs
    const startGlyphCovers = (run.glyphIndices?.[startIndex] ?? startIndex) >= start;
    const sliceStart = startIndex + (startOffset > 0 || !startGlyphCovers ? 1 : 0);
    const sliceEnd = endIndex + 1 - Math.min(1, endOffset);
    const glyphs = (run.glyphs || []).slice(sliceStart, sliceEnd);
    // Compute new positions
    const glyphPosition = (g) => ({
        xAdvance: g.advanceWidth * runScale,
        yAdvance: 0,
        xOffset: 0,
        yOffset: 0,
    });
    const startPositions = startGlyphs.map(glyphPosition);
    const positions = (run.positions || []).slice(sliceStart, sliceEnd);
    const endPositions = endGlyphs.map(glyphPosition);
    // Compute new string indices
    const stringIndices = normalize((run.stringIndices || []).slice(start, end));
    // Compute new glyph indices
    const startGlyphIndices = startGlyphs.map((_, i) => (run.glyphIndices?.[startIndex] ?? 0) - start + startOffset + i);
    const slicedGlyphIndices = (run.glyphIndices || [])
        .slice(sliceStart, sliceEnd)
        .map((v) => v - start);
    const endGlyphIndices = endGlyphs.map((_, i) => (run.glyphIndices?.[endIndex] ?? 0) - start + i);
    const glyphIndices = [
        startGlyphIndices,
        slicedGlyphIndices,
        endGlyphIndices,
    ].flat();
    return Object.assign({}, run, {
        start: Math.max(run.start + start, 0),
        end: Math.max(Math.min(run.end, run.start + end), 0),
        stringIndices,
        glyphIndices,
        glyphs: [startGlyphs, glyphs, endGlyphs].flat(),
        positions: [startPositions, positions, endPositions].flat(),
    });
};

/**
 * Get run index that contains passed index
 *
 * @param index - Index
 * @param runs - Runs
 * @returns Run index
 */
const runIndexAt$1 = (index, runs) => {
    if (!runs)
        return -1;
    return runs.findIndex((run) => run.start <= index && index < run.end);
};

/**
 * Filter runs contained between start and end
 *
 * @param start
 * @param end
 * @param runs
 * @returns Filtered runs
 */
const filter = (start, end, runs) => {
    const startIndex = runIndexAt$1(start, runs);
    const endIndex = Math.max(runIndexAt$1(end - 1, runs), startIndex);
    return runs.slice(startIndex, endIndex + 1);
};

/**
 * Subtract scalar to run
 *
 * @param index - Scalar
 * @param run - Run
 * @returns Subtracted run
 */
const subtract = (index, run) => {
    const start = run.start - index;
    const end = run.end - index;
    return Object.assign({}, run, { start, end });
};

/**
 * Slice array of runs
 *
 * @param start - Offset
 * @param end - Offset
 * @param runs
 * @returns Sliced runs
 */
const sliceRuns = (start, end, runs) => {
    const sliceFirstRun = (a) => slice$1(start - a.start, end - a.start, a);
    const sliceLastRun = (a) => slice$1(0, end - a.start, a);
    return runs.map((run, i) => {
        let result = run;
        const isFirst = i === 0;
        const isLast = !isFirst && i === runs.length - 1;
        if (isFirst)
            result = sliceFirstRun(run);
        if (isLast)
            result = sliceLastRun(run);
        return subtract(start, result);
    });
};
/**
 * Slice attributed string between two indices
 *
 * @param start - Offset
 * @param end - Offset
 * @param attributedString - Attributed string
 * @returns Attributed string
 */
const slice = (start, end, attributedString) => {
    if (attributedString.string.length === 0)
        return attributedString;
    const string = attributedString.string.slice(start, end);
    const filteredRuns = filter(start, end, attributedString.runs);
    const slicedRuns = sliceRuns(start, end, filteredRuns);
    return Object.assign({}, attributedString, { string, runs: slicedRuns });
};

const WHITESPACE_REGEX = /\S/;
/**
 * Find index of first non-whitespace character
 *
 * @param string - String to search
 * @returns Index of first non-whitespace character, or -1 if not found
 */
const findCharIndex = (string) => {
    return string.search(WHITESPACE_REGEX);
};
/**
 * Find index of last non-whitespace character
 *
 * @param string - String to search
 * @returns Index of last non-whitespace character, or -1 if not found
 */
const findLastCharIndex = (string) => {
    for (let i = string.length - 1; i >= 0; i -= 1) {
        if (WHITESPACE_REGEX.test(string[i]))
            return i;
    }
    return -1;
};
/**
 * Removes (strips) whitespace from both ends of the attributted string.
 *
 * @param attributedString - Attributed string
 * @returns Attributed string
 */
const trim = (attributedString) => {
    const start = findCharIndex(attributedString.string);
    const end = findLastCharIndex(attributedString.string);
    return slice(start, end + 1, attributedString);
};

/**
 * Returns empty run
 *
 * @returns Empty run
 */
const empty$1 = () => {
    return {
        start: 0,
        end: 0,
        stringIndices: [],
        glyphIndices: [],
        glyphs: [],
        positions: [],
        attributes: {},
    };
};

/**
 * Check if value is a number
 *
 * @param value - Value to check
 * @returns Whether value is a number
 */
const isNumber = (value) => {
    return typeof value === 'number';
};

/**
 * Append glyph indices with given length
 *
 * Ex. appendIndices(3, [0, 1, 2, 2]) => [0, 1, 2, 2, 3, 3, 3]
 *
 * @param length - Length to append
 * @param indices - Glyph indices
 * @returns Extended glyph indices
 */
const appendIndices$1 = (length, indices) => {
    const lastIndex = last(indices);
    const value = isNil(lastIndex) ? 0 : lastIndex + 1;
    const newIndices = Array(length).fill(value);
    return indices.concat(newIndices);
};

/**
 * Append a new glyph index entry to the end of the indices array.
 * The appended value represents the character position of the new glyph,
 * which corresponds to the current string length.
 *
 * @param value - The current string length (character position of the new glyph)
 * @param indices - The existing glyph indices array
 * @returns New array with the appended index
 */
const appendIndices = (value, indices) => {
    return indices.concat([value]);
};

/**
 * Get glyph for a given code point
 *
 * @param codePoint - Unicode code point (0 is treated as invalid)
 * @param font - Font to get glyph from
 * @returns Glyph or null if font/codePoint is invalid
 */
const fromCodePoint = (codePoint, font) => {
    // String fonts (e.g., 'Helvetica') don't support glyph lookup
    if (typeof font === 'string')
        return null;
    // Require valid font and non-zero code point
    if (!font || !codePoint)
        return null;
    return font.glyphForCodePoint(codePoint);
};

/**
 * Append glyph to run
 *
 * @param glyph - Glyph
 * @param run - Run
 * @returns Run with glyph
 */
const appendGlyph = (glyph, run) => {
    const glyphLength = glyph.codePoints?.length || 0;
    const stringLength = run.stringIndices?.length || 0;
    const glyphs = run.glyphs.concat(glyph);
    const stringIndices = appendIndices$1(glyphLength, run.stringIndices);
    const glyphIndices = appendIndices(stringLength, run.glyphIndices);
    const end = run.end + glyphLength;
    if (!run.positions)
        return Object.assign({}, run, { end, glyphs, stringIndices, glyphIndices });
    const positions = run.positions.concat({
        xAdvance: glyph.advanceWidth * scale(run),
        yAdvance: 0,
        xOffset: 0,
        yOffset: 0,
    });
    return Object.assign({}, run, {
        end,
        glyphs,
        stringIndices,
        glyphIndices,
        positions,
    });
};
/**
 * Append glyph or code point to run
 *
 * @param value - Glyph or codePoint
 * @param run - Run
 * @returns Run with glyph
 */
const append$1 = (value, run) => {
    if (!value)
        return run;
    const font = getFont(run);
    const glyph = isNumber(value) ? fromCodePoint(value, font) : value;
    return appendGlyph(glyph, run);
};

/**
 * Get string from array of code points
 *
 * @param codePoints - Points
 * @returns String
 */
const stringFromCodePoints = (codePoints) => {
    return String.fromCodePoint(...(codePoints || []));
};

/**
 * Append glyph into last run of attributed string
 *
 * @param glyph - Glyph or code point
 * @param attributedString - Attributed string
 * @returns Attributed string with new glyph
 */
const append = (glyph, attributedString) => {
    const codePoints = typeof glyph === 'number' ? [glyph] : glyph?.codePoints;
    const codePointsString = stringFromCodePoints(codePoints || []);
    const string = attributedString.string + codePointsString;
    const firstRuns = attributedString.runs.slice(0, -1);
    const lastRun = last(attributedString.runs) || empty$1();
    const runs = firstRuns.concat(append$1(glyph, lastRun));
    return Object.assign({}, attributedString, { string, runs });
};

const ELLIPSIS_UNICODE = 8230;
const ELLIPSIS_STRING = String.fromCharCode(ELLIPSIS_UNICODE);
/**
 * Get ellipsis codepoint. This may be different in standard and embedded fonts
 *
 * @param font
 * @returns Ellipsis codepoint
 */
const getEllipsisCodePoint = (font) => {
    if (!font.encode)
        return ELLIPSIS_UNICODE;
    const [codePoints] = font.encode(ELLIPSIS_STRING);
    return parseInt(codePoints[0], 16);
};
/**
 * Trucante block with ellipsis
 *
 * @param paragraph - Paragraph
 * @returns Sliced paragraph
 */
const truncate = (paragraph) => {
    const runs = last(paragraph)?.runs || [];
    const font = last(runs)?.attributes?.font[0];
    if (font) {
        const index = paragraph.length - 1;
        const codePoint = getEllipsisCodePoint(font);
        const glyph = font.glyphForCodePoint(codePoint);
        const lastBlock = append(glyph, trim(paragraph[index]));
        return Object.assign([], paragraph, { [index]: lastBlock });
    }
    return paragraph;
};

/**
 * Omit attribute from run
 *
 * @param value - Attribute key
 * @param run - Run
 * @returns Run without ommited attribute
 */
const omit = (value, run) => {
    const attributes = Object.assign({}, run.attributes);
    delete attributes[value];
    return Object.assign({}, run, { attributes });
};

/**
 * Get run ascent
 *
 * @param run - Run
 * @returns Ascent
 */
const ascent$1 = (run) => {
    const { font, attachment } = run.attributes;
    const attachmentHeight = attachment?.height || 0;
    const fontAscent = typeof font === 'string' ? 0 : font?.[0]?.ascent || 0;
    return Math.max(attachmentHeight, fontAscent * scale(run));
};

/**
 * Get run descent
 *
 * @param run - Run
 * @returns Descent
 */
const descent = (run) => {
    const font = run.attributes?.font;
    const fontDescent = typeof font === 'string' ? 0 : font?.[0]?.descent || 0;
    return scale(run) * fontDescent;
};

/**
 * Get run lineGap
 *
 * @param run - Run
 * @returns LineGap
 */
const lineGap = (run) => {
    const font = run.attributes?.font;
    const lineGap = typeof font === 'string' ? 0 : font?.[0]?.lineGap || 0;
    return lineGap * scale(run);
};

/**
 * Get run height
 *
 * @param run - Run
 * @returns Height
 */
const height$1 = (run) => {
    const lineHeight = run.attributes?.lineHeight;
    return lineHeight || lineGap(run) + ascent$1(run) - descent(run);
};

/**
 * Returns attributed string height
 *
 * @param attributedString - Attributed string
 * @returns Height
 */
const height = (attributedString) => {
    const reducer = (acc, run) => Math.max(acc, height$1(run));
    return attributedString.runs.reduce(reducer, 0);
};

/**
 * Checks if two rects intersect each other
 *
 * @param a - Rect A
 * @param b - Rect B
 * @returns Whether rects intersect
 */
const intersects = (a, b) => {
    const x = Math.max(a.x, b.x);
    const num1 = Math.min(a.x + a.width, b.x + b.width);
    const y = Math.max(a.y, b.y);
    const num2 = Math.min(a.y + a.height, b.y + b.height);
    return num1 >= x && num2 >= y;
};

const getLineFragment = (lineRect, excludeRect) => {
    if (!intersects(excludeRect, lineRect))
        return [lineRect];
    const eStart = excludeRect.x;
    const eEnd = excludeRect.x + excludeRect.width;
    const lStart = lineRect.x;
    const lEnd = lineRect.x + lineRect.width;
    const a = Object.assign({}, lineRect, { width: eStart - lStart });
    const b = Object.assign({}, lineRect, { x: eEnd, width: lEnd - eEnd });
    return [a, b].filter((r) => r.width > 0);
};
const getLineFragments = (rect, excludeRects) => {
    let fragments = [rect];
    for (let i = 0; i < excludeRects.length; i += 1) {
        const excludeRect = excludeRects[i];
        fragments = fragments.reduce((acc, fragment) => {
            const pieces = getLineFragment(fragment, excludeRect);
            return acc.concat(pieces);
        }, []);
    }
    return fragments;
};
const generateLineRects = (container, height) => {
    const { excludeRects, ...rect } = container;
    if (!excludeRects)
        return [rect];
    const lineRects = [];
    const maxY = Math.max(...excludeRects.map((r) => r.y + r.height));
    let currentRect = rect;
    while (currentRect.y < maxY) {
        const [lineRect, rest] = partition(currentRect, height);
        const lineRectFragments = getLineFragments(lineRect, excludeRects);
        currentRect = rest;
        lineRects.push(...lineRectFragments);
    }
    return [...lineRects, currentRect];
};

const ATTACHMENT_CODE$1 = '\ufffc'; // 65532
/**
 * Remove attachment attribute if no char present
 *
 * @param line - Line
 * @returns Line
 */
const purgeAttachments = (line) => {
    const shouldPurge = !line.string.includes(ATTACHMENT_CODE$1);
    if (!shouldPurge)
        return line;
    const runs = line.runs.map((run) => omit('attachment', run));
    return Object.assign({}, line, { runs });
};
/**
 * Layout paragraphs inside rectangle
 *
 * @param rects - Rects
 * @param lines - Attributed strings
 * @param indent
 * @returns layout blocks
 */
const layoutLines = (rects, lines, indent) => {
    let rect = rects.shift();
    let currentY = rect.y;
    return lines.map((line, i) => {
        const lineIndent = i === 0 ? indent : 0;
        const style = line.runs?.[0]?.attributes || {};
        const height$1 = Math.max(height(line), style.lineHeight);
        if (currentY + height$1 > rect.y + rect.height && rects.length > 0) {
            rect = rects.shift();
            currentY = rect.y;
        }
        const newLine = {
            string: line.string,
            runs: line.runs,
            box: {
                x: rect.x + lineIndent,
                y: currentY,
                width: rect.width - lineIndent,
                height: height$1,
            },
        };
        currentY += height$1;
        return purgeAttachments(newLine);
    });
};
/**
 * Performs line breaking and layout
 *
 * @param engines - Engines
 * @param options - Layout options
 */
const layoutParagraph = (engines, options = {}) => {
    /**
     * @param container - Container
     * @param paragraph - Attributed string
     * @returns Layout block
     */
    return (container, paragraph) => {
        const height$1 = height(paragraph);
        const indent = paragraph.runs?.[0]?.attributes?.indent || 0;
        const rects = generateLineRects(container, height$1);
        const availableWidths = rects.map((r) => r.width);
        availableWidths.unshift(availableWidths[0] - indent);
        const lines = engines.linebreaker(options)(paragraph, availableWidths);
        return layoutLines(rects, lines, indent);
    };
};

/**
 * Slice block at given height
 *
 * @param height - Height
 * @param paragraph - Paragraph
 * @returns Sliced paragraph
 */
const sliceAtHeight = (height, paragraph) => {
    const newBlock = [];
    let counter = 0;
    for (let i = 0; i < paragraph.length; i += 1) {
        const line = paragraph[i];
        counter += line.box.height;
        if (counter < height) {
            newBlock.push(line);
        }
        else {
            break;
        }
    }
    return newBlock;
};

/**
 * Layout paragraphs inside container until it does not
 * fit anymore, performing line wrapping in the process.
 *
 * @param  engines - Engines
 * @param  options - Layout options
 * @param container - Container
 */
const typesetter = (engines, options, container) => {
    /**
     * @param attributedStrings - Attributed strings (paragraphs)
     * @returns Paragraph blocks
     */
    return (attributedStrings) => {
        const result = [];
        const paragraphs = [...attributedStrings];
        const layout = layoutParagraph(engines, options);
        const maxLines = isNil(container.maxLines) ? Infinity : container.maxLines;
        const truncateEllipsis = container.truncateMode === 'ellipsis';
        let linesCount = maxLines;
        let paragraphRect = copy(container);
        let nextParagraph = paragraphs.shift();
        while (linesCount > 0 && nextParagraph) {
            const paragraph = layout(paragraphRect, nextParagraph);
            const slicedBlock = paragraph.slice(0, linesCount);
            const linesHeight = height$2(slicedBlock);
            const shouldTruncate = truncateEllipsis && paragraph.length !== slicedBlock.length;
            linesCount -= slicedBlock.length;
            if (paragraphRect.height >= linesHeight) {
                result.push(shouldTruncate ? truncate(slicedBlock) : slicedBlock);
                paragraphRect = crop(linesHeight, paragraphRect);
                nextParagraph = paragraphs.shift();
            }
            else {
                result.push(truncate(sliceAtHeight(paragraphRect.height, slicedBlock)));
                break;
            }
        }
        return result;
    };
};

/**
 * Get attributed string start value
 *
 * @param attributedString - Attributed string
 * @returns Start
 */
const start = (attributedString) => {
    const { runs } = attributedString;
    return runs.length === 0 ? 0 : runs[0].start;
};

/**
 * Get attributed string end value
 *
 * @param attributedString - Attributed string
 * @returns End
 */
const end = (attributedString) => {
    const { runs } = attributedString;
    return runs.length === 0 ? 0 : last(runs).end;
};

/**
 * Get attributed string length
 *
 * @param attributedString - Attributed string
 * @returns End
 */
const length$1 = (attributedString) => {
    return end(attributedString) - start(attributedString);
};

const bidi$2 = bidiFactory();
const getBidiLevels$1 = (runs) => {
    return runs.reduce((acc, run) => {
        const length = run.end - run.start;
        const levels = repeat(run.attributes.bidiLevel, length);
        return acc.concat(levels);
    }, []);
};
const getReorderedIndices = (string, segments) => {
    // Fill an array with indices
    const indices = [];
    for (let i = 0; i < string.length; i += 1) {
        indices[i] = i;
    }
    // Reverse each segment in order
    segments.forEach(([start, end]) => {
        const slice = indices.slice(start, end + 1);
        for (let i = slice.length - 1; i >= 0; i -= 1) {
            indices[end - i] = slice[i];
        }
    });
    return indices;
};
const getItemAtIndex = (runs, objectName, index) => {
    for (let i = 0; i < runs.length; i += 1) {
        const run = runs[i];
        const updatedIndex = run.stringIndices[index - run.start];
        if (index >= run.start && index < run.end) {
            return run[objectName][updatedIndex];
        }
    }
    throw new Error(`index ${index} out of range`);
};
const reorderLine = (line) => {
    const levels = getBidiLevels$1(line.runs);
    const direction = line.runs[0]?.attributes.direction;
    const level = direction === 'rtl' ? 1 : 0;
    const end = length$1(line) - 1;
    const paragraphs = [{ start: 0, end, level }];
    const embeddingLevels = { paragraphs, levels };
    const segments = bidi$2.getReorderSegments(line.string, embeddingLevels);
    // No need for bidi reordering
    if (segments.length === 0)
        return line;
    const indices = getReorderedIndices(line.string, segments);
    const updatedString = bidi$2.getReorderedString(line.string, embeddingLevels);
    const updatedRuns = line.runs.map((run) => {
        const selectedIndices = indices.slice(run.start, run.end);
        const updatedGlyphs = [];
        const updatedPositions = [];
        const addedGlyphs = new Set();
        for (let i = 0; i < selectedIndices.length; i += 1) {
            const index = selectedIndices[i];
            const glyph = getItemAtIndex(line.runs, 'glyphs', index);
            if (addedGlyphs.has(glyph.id))
                continue;
            updatedGlyphs.push(glyph);
            updatedPositions.push(getItemAtIndex(line.runs, 'positions', index));
            if (glyph.isLigature) {
                addedGlyphs.add(glyph.id);
            }
        }
        return {
            ...run,
            glyphs: updatedGlyphs,
            positions: updatedPositions,
        };
    });
    return {
        box: line.box,
        runs: updatedRuns,
        string: updatedString,
    };
};
const reorderParagraph = (paragraph) => paragraph.map(reorderLine);
/**
 * Perform bidi reordering
 *
 * @returns Reordered paragraphs
 */
const bidiReordering = () => {
    /**
     * @param paragraphs - Paragraphs
     * @returns Reordered paragraphs
     */
    return (paragraphs) => paragraphs.map(reorderParagraph);
};

/**
 * Resolve string indices based on glyphs code points.
 * Maps each glyph to its corresponding string index, handling ligatures
 * by assigning the same index to all code points within a ligature.
 *
 * @param glyphs - Array of glyphs (may contain undefined for missing glyphs)
 * @returns Glyph indices array
 */
const resolve$1 = (glyphs = []) => {
    const result = [];
    let currentIndex = 0;
    for (let i = 0; i < glyphs.length; i += 1) {
        const glyph = glyphs[i];
        const codePointCount = glyph?.codePoints?.length || 0;
        for (let j = 0; j < codePointCount; j += 1) {
            result.push(currentIndex);
        }
        currentIndex += 1;
    }
    return result;
};

/**
 * Resolve glyph indices based on glyphs code points.
 * Maps each glyph to its starting character index in the original string,
 * accounting for ligatures where a single glyph represents multiple code points.
 *
 * @param glyphs - Array of glyphs (may contain undefined for missing glyphs)
 * @returns Array of character indices, one per glyph
 */
const resolve = (glyphs = []) => {
    const result = [];
    let currentIndex = 0;
    for (let i = 0; i < glyphs.length; i += 1) {
        const glyph = glyphs[i];
        const length = glyph?.codePoints?.length || 0;
        const value = length === 0 ? result[i - 1] : currentIndex;
        result.push(value);
        currentIndex += length;
    }
    return result;
};

const getCharacterSpacing = (run) => {
    return run.attributes?.characterSpacing || 0;
};
/**
 * Scale run positions
 *
 * @param  run
 * @param  positions
 * @returns Scaled positions
 */
const scalePositions = (run, positions) => {
    const runScale = scale(run);
    const characterSpacing = getCharacterSpacing(run);
    return positions.map((position, i) => {
        const isLast = i === positions.length;
        const xSpacing = isLast ? 0 : characterSpacing;
        return Object.assign({}, position, {
            xAdvance: position.xAdvance * runScale + xSpacing,
            yAdvance: position.yAdvance * runScale,
            xOffset: position.xOffset * runScale,
            yOffset: position.yOffset * runScale,
        });
    });
};
/**
 * Create glyph run
 *
 * @param string string
 */
const layoutRun = (string) => {
    /**
     * @param run - Run
     * @returns Glyph run
     */
    return (run) => {
        const { start, end, attributes = {} } = run;
        const { font } = attributes;
        if (!font)
            return {
                ...run,
                glyphs: [],
                stringIndices: [],
                glyphIndices: [],
                positions: [],
            };
        const runString = string.slice(start, end);
        if (typeof font === 'string')
            throw new Error('Invalid font');
        // passing LTR To force fontkit to not reverse the string
        const glyphRun = font[0].layout(runString, undefined, undefined, undefined, 'ltr');
        const positions = scalePositions(run, glyphRun.positions);
        const stringIndices = resolve$1(glyphRun.glyphs);
        const glyphIndices = resolve(glyphRun.glyphs);
        const result = {
            ...run,
            positions,
            stringIndices,
            glyphIndices,
            glyphs: glyphRun.glyphs,
        };
        return result;
    };
};
/**
 * Generate glyphs for single attributed string
 */
const generateGlyphs = () => {
    /**
     * @param attributedString - Attributed string
     * @returns Attributed string with glyphs
     */
    return (attributedString) => {
        const runs = attributedString.runs.map(layoutRun(attributedString.string));
        const res = Object.assign({}, attributedString, { runs });
        return res;
    };
};

/**
 * Resolves yOffset for run
 *
 * @param run - Run
 * @returns Run
 */
const resolveRunYOffset = (run) => {
    if (!run.positions)
        return run;
    const unitsPerEm = run.attributes?.font?.[0]?.unitsPerEm || 0;
    const yOffset = (run.attributes?.yOffset || 0) * unitsPerEm;
    const positions = run.positions.map((p) => Object.assign({}, p, { yOffset }));
    return Object.assign({}, run, { positions });
};
/**
 * Resolves yOffset for multiple paragraphs
 */
const resolveYOffset = () => {
    /**
     * @param attributedString - Attributed string
     * @returns Attributed string
     */
    return (attributedString) => {
        const runs = attributedString.runs.map(resolveRunYOffset);
        const res = Object.assign({}, attributedString, { runs });
        return res;
    };
};

/**
 * Sort runs in ascending order
 *
 * @param runs
 * @returns Sorted runs
 */
const sort = (runs) => {
    return runs.sort((a, b) => a.start - b.start || a.end - b.end);
};

/**
 * Is run empty (start === end)
 *
 * @param run - Run
 * @returns Is run empty
 */
const isEmpty = (run) => {
    return run.start === run.end;
};

/**
 * Sort points in ascending order
 * @param a - First point
 * @param b - Second point
 * @returns Sort order
 */
const sortPoints = (a, b) => {
    return a[1] - b[1] || a[3] - b[3];
};
/**
 * @param runs
 * @returns Points
 */
const generatePoints = (runs) => {
    const result = runs.reduce((acc, run, i) => {
        return acc.concat([
            ['start', run.start, run.attributes, i],
            ['end', run.end, run.attributes, i],
        ]);
    }, []);
    return result.sort(sortPoints);
};
/**
 * @param runs
 * @returns Merged runs
 */
const mergeRuns = (runs) => {
    return runs.reduce((acc, run) => {
        const attributes = Object.assign({}, acc.attributes, run.attributes);
        return Object.assign({}, run, { attributes });
    }, {});
};
/**
 * @param runs
 * @returns Grouped runs
 */
const groupEmptyRuns = (runs) => {
    const groups = runs.reduce((acc, run) => {
        if (!acc[run.start])
            acc[run.start] = [];
        acc[run.start].push(run);
        return acc;
    }, []);
    return Object.values(groups);
};
/**
 * @param runs
 * @returns Flattened runs
 */
const flattenEmptyRuns = (runs) => {
    return groupEmptyRuns(runs).map(mergeRuns);
};
/**
 * @param runs
 * @returns Flattened runs
 */
const flattenRegularRuns = (runs) => {
    const res = [];
    const points = generatePoints(runs);
    let start = -1;
    let attrs = {};
    const stack = [];
    for (let i = 0; i < points.length; i += 1) {
        const [type, offset, attributes] = points[i];
        if (start !== -1 && start < offset) {
            res.push({
                start,
                end: offset,
                attributes: attrs,
                stringIndices: [],
                glyphIndices: [],
                glyphs: [],
                positions: [],
            });
        }
        if (type === 'start') {
            stack.push(attributes);
            attrs = Object.assign({}, attrs, attributes);
        }
        else {
            attrs = {};
            for (let j = 0; j < stack.length; j += 1) {
                if (stack[j] === attributes) {
                    stack.splice(j--, 1);
                }
                else {
                    attrs = Object.assign({}, attrs, stack[j]);
                }
            }
        }
        start = offset;
    }
    return res;
};
/**
 * Flatten many runs
 *
 * @param runs
 * @returns Flattened runs
 */
const flatten = (runs = []) => {
    const emptyRuns = flattenEmptyRuns(runs.filter((run) => isEmpty(run)));
    const regularRuns = flattenRegularRuns(runs.filter((run) => !isEmpty(run)));
    return sort(emptyRuns.concat(regularRuns));
};

/**
 * Returns empty attributed string
 *
 * @returns Empty attributed string
 */
const empty = () => ({ string: '', runs: [] });

/**
 *
 * @param attributedString
 * @returns Attributed string without font
 */
const omitFont = (attributedString) => {
    const runs = attributedString.runs.map((run) => omit('font', run));
    return Object.assign({}, attributedString, { runs });
};
/**
 * Performs font substitution and script itemization on attributed string
 *
 * @param engines - engines
 */
const preprocessRuns = (engines) => {
    /**
     * @param attributedString - Attributed string
     * @returns Processed attributed string
     */
    return (attributedString) => {
        if (isNil(attributedString))
            return empty();
        const { string } = attributedString;
        const { fontSubstitution, scriptItemizer, bidi } = engines;
        const { runs: omittedFontRuns } = omitFont(attributedString);
        const { runs: itemizationRuns } = scriptItemizer()(attributedString);
        const { runs: substitutedRuns } = fontSubstitution()(attributedString);
        const { runs: bidiRuns } = bidi()(attributedString);
        const runs = bidiRuns
            .concat(substitutedRuns)
            .concat(itemizationRuns)
            .concat(omittedFontRuns);
        return { string, runs: flatten(runs) };
    };
};

/**
 * Breaks attributed string into paragraphs
 */
const splitParagraphs = () => {
    /**
     * @param attributedString - Attributed string
     * @returns Paragraphs attributed strings
     */
    return (attributedString) => {
        const paragraphs = [];
        let start = 0;
        let breakPoint = attributedString.string.indexOf('\n') + 1;
        while (breakPoint > 0) {
            paragraphs.push(slice(start, breakPoint, attributedString));
            start = breakPoint;
            breakPoint = attributedString.string.indexOf('\n', breakPoint) + 1;
        }
        if (start === 0) {
            paragraphs.push(attributedString);
        }
        else if (start < attributedString.string.length) {
            paragraphs.push(slice(start, length$1(attributedString), attributedString));
        }
        return paragraphs;
    };
};

/**
 * Return positions advance width
 *
 * @param positions - Positions
 * @returns {number} advance width
 */
const advanceWidth$2 = (positions) => {
    return positions.reduce((acc, pos) => acc + (pos.xAdvance || 0), 0);
};

/**
 * Return run advance width
 *
 * @param run - Run
 * @returns Advance width
 */
const advanceWidth$1 = (run) => {
    return advanceWidth$2(run.positions || []);
};

/**
 * Returns attributed string advancewidth
 *
 * @param attributedString - Attributed string
 * @returns Advance width
 */
const advanceWidth = (attributedString) => {
    const reducer = (acc, run) => acc + advanceWidth$1(run);
    return attributedString.runs.reduce(reducer, 0);
};

/**
 * ASCII code for space character.
 * Note: Only space (32) is considered whitespace for typographic layout purposes,
 * not tabs, newlines, or other control characters.
 */
const SPACE_CODE = 32;
/**
 * Check if glyph contains a space character
 *
 * @param glyph - Glyph
 * @returns Whether glyph contains a space
 */
const isWhiteSpace$1 = (glyph) => {
    const codePoints = glyph?.codePoints || [];
    return codePoints.includes(SPACE_CODE);
};

/**
 * Check if run is entirely whitespace
 *
 * @param run - Run
 * @returns Whether run is entirely whitespace
 */
const isWhiteSpace = (run) => {
    const glyphs = run?.glyphs || [];
    return glyphs.length > 0 && glyphs.every(isWhiteSpace$1);
};

/**
 * Get white space leading positions
 *
 * @param run - Run
 * @returns White space leading positions
 */
const leadingPositions = (run) => {
    const glyphs = run.glyphs || [];
    const positions = run.positions || [];
    const leadingWhitespaces = glyphs.findIndex((g) => !isWhiteSpace$1(g));
    return leadingWhitespaces === -1
        ? positions
        : positions.slice(0, leadingWhitespaces);
};
/**
 * Get run leading white space offset
 *
 * @param run - Run
 * @returns Leading white space offset
 */
const leadingOffset$1 = (run) => {
    if (!run)
        return 0;
    const positions = leadingPositions(run);
    return positions.reduce((acc, pos) => acc + (pos.xAdvance || 0), 0);
};

/**
 * Get attributed string leading white space offset
 *
 * @param attributedString - Attributed string
 * @returns Leading white space offset
 */
const leadingOffset = (attributedString) => {
    const runs = attributedString.runs || [];
    let offset = 0;
    for (const run of runs) {
        offset += leadingOffset$1(run);
        if (!isWhiteSpace(run))
            break;
    }
    return offset;
};

/**
 * Get white space trailing positions
 *
 * @param run run
 * @returns White space trailing positions
 */
const trailingPositions = (run) => {
    const glyphs = reverse(run.glyphs || []);
    const positions = reverse(run.positions || []);
    const leadingWhitespaces = glyphs.findIndex((g) => !isWhiteSpace$1(g));
    return leadingWhitespaces === -1
        ? positions
        : positions.slice(0, leadingWhitespaces);
};
/**
 * Get run trailing white space offset
 *
 * @param run - Run
 * @returns Trailing white space offset
 */
const trailingOffset$1 = (run) => {
    if (!run)
        return 0;
    const positions = trailingPositions(run);
    return positions.reduce((acc, pos) => acc + (pos.xAdvance || 0), 0);
};

/**
 * Get attributed string trailing white space offset
 *
 * @param attributedString - Attributed string
 * @returns Trailing white space offset
 */
const trailingOffset = (attributedString) => {
    const runs = attributedString.runs || [];
    let offset = 0;
    for (let i = runs.length - 1; i >= 0; i -= 1) {
        const run = runs[i];
        offset += trailingOffset$1(run);
        if (!isWhiteSpace(run))
            break;
    }
    return offset;
};

/**
 * Drop last char of run
 *
 * @param run - Run
 * @returns Run without last char
 */
const dropLast$1 = (run) => {
    return slice$1(0, run.end - run.start - 1, run);
};

/**
 * Drop last glyph
 *
 * @param attributedString - Attributed string
 * @returns Attributed string with new glyph
 */
const dropLast = (attributedString) => {
    const string = dropLast$2(attributedString.string);
    const runs = adjust(-1, dropLast$1, attributedString.runs);
    return Object.assign({}, attributedString, { string, runs });
};

const ALIGNMENT_FACTORS = { center: 0.5, right: 1 };
/**
 * Remove new line char at the end of line if present
 *
 * @param line
 * @returns Line
 */
const removeNewLine = (line) => {
    return last(line.string) === '\n' ? dropLast(line) : line;
};
const getOverflowLeft = (line) => {
    return leadingOffset(line) + (line.overflowLeft || 0);
};
const getOverflowRight = (line) => {
    return trailingOffset(line) + (line.overflowRight || 0);
};
/**
 * Ignore whitespace at the start and end of a line for alignment
 *
 * @param line
 * @returns Line
 */
const adjustOverflow = (line) => {
    const overflowLeft = getOverflowLeft(line);
    const overflowRight = getOverflowRight(line);
    const x = line.box.x - overflowLeft;
    const width = line.box.width + overflowLeft + overflowRight;
    const box = Object.assign({}, line.box, { x, width });
    return Object.assign({}, line, { box, overflowLeft, overflowRight });
};
/**
 * Performs line justification by calling appropiate engine
 *
 * @param engines - Engines
 * @param options - Layout options
 * @param align - Text align
 */
const justifyLine$1 = (engines, options, align) => {
    /**
     * @param line - Line
     * @returns Line
     */
    return (line) => {
        const lineWidth = advanceWidth(line);
        const alignFactor = ALIGNMENT_FACTORS[align] || 0;
        const remainingWidth = Math.max(0, line.box.width - lineWidth);
        const shouldJustify = align === 'justify' || lineWidth > line.box.width;
        const x = line.box.x + remainingWidth * alignFactor;
        const box = Object.assign({}, line.box, { x });
        const newLine = Object.assign({}, line, { box });
        return shouldJustify ? engines.justification(options)(newLine) : newLine;
    };
};
const finalizeLine = (line) => {
    let lineAscent = 0;
    let lineDescent = 0;
    let lineHeight = 0;
    let lineXAdvance = 0;
    const runs = line.runs.map((run) => {
        const height = height$1(run);
        const ascent = ascent$1(run);
        const descent$1 = descent(run);
        const xAdvance = advanceWidth$1(run);
        lineHeight = Math.max(lineHeight, height);
        lineAscent = Math.max(lineAscent, ascent);
        lineDescent = Math.max(lineDescent, descent$1);
        lineXAdvance += xAdvance;
        return Object.assign({}, run, { height, ascent, descent: descent$1, xAdvance });
    });
    return Object.assign({}, line, {
        runs,
        height: lineHeight,
        ascent: lineAscent,
        descent: lineDescent,
        xAdvance: lineXAdvance,
    });
};
/**
 * Finalize line by performing line justification
 * and text decoration (using appropiate engines)
 *
 * @param engines - Engines
 * @param options - Layout options
 */
const finalizeBlock = (engines, options) => {
    /**
     * @param line - Line
     * @param i - Line index
     * @param lines - Total lines
     * @returns Line
     */
    return (line, index, lines) => {
        const isLastFragment = index === lines.length - 1;
        const style = line.runs?.[0]?.attributes || {};
        const align = isLastFragment ? style.alignLastLine : style.align;
        return compose(finalizeLine, engines.textDecoration(), justifyLine$1(engines, options, align), adjustOverflow, removeNewLine)(line);
    };
};
/**
 * Finalize line block by performing line justification
 * and text decoration (using appropiate engines)
 *
 * @param engines - Engines
 * @param options - Layout options
 */
const finalizeFragments = (engines, options) => {
    /**
     * @param paragraphs - Paragraphs
     * @returns Paragraphs
     */
    return (paragraphs) => {
        const blockFinalizer = finalizeBlock(engines, options);
        return paragraphs.map((paragraph) => paragraph.map(blockFinalizer));
    };
};

const ATTACHMENT_CODE = 0xfffc; // 65532
const isReplaceGlyph = (glyph) => glyph.codePoints.includes(ATTACHMENT_CODE);
/**
 * Resolve attachments of run
 *
 * @param run
 * @returns Run
 */
const resolveRunAttachments = (run) => {
    if (!run.positions)
        return run;
    const glyphs = run.glyphs || [];
    const attachment = run.attributes?.attachment;
    if (!attachment)
        return run;
    const positions = run.positions.map((position, i) => {
        const glyph = glyphs[i];
        if (attachment.width && isReplaceGlyph(glyph)) {
            return Object.assign({}, position, { xAdvance: attachment.width });
        }
        return Object.assign({}, position);
    });
    return Object.assign({}, run, { positions });
};
/**
 * Resolve attachments for multiple paragraphs
 */
const resolveAttachments = () => {
    /**
     * @param attributedString - Attributed string
     * @returns Attributed string
     */
    return (attributedString) => {
        const runs = attributedString.runs.map(resolveRunAttachments);
        const res = Object.assign({}, attributedString, { runs });
        return res;
    };
};

/**
 * @param attributes - Attributes
 * @returns Attributes with defaults
 */
const applyAttributes = (a) => {
    return {
        align: a.align || (a.direction === 'rtl' ? 'right' : 'left'),
        alignLastLine: a.alignLastLine || (a.align === 'justify' ? 'left' : a.align || 'left'),
        attachment: a.attachment || null,
        backgroundColor: a.backgroundColor || null,
        bullet: a.bullet || null,
        characterSpacing: a.characterSpacing || 0,
        color: a.color || 'black',
        direction: a.direction || 'ltr',
        features: a.features || [],
        fill: a.fill !== false,
        font: a.font || [],
        fontSize: a.fontSize || 12,
        hangingPunctuation: a.hangingPunctuation || false,
        hyphenationFactor: a.hyphenationFactor || 0,
        indent: a.indent || 0,
        justificationFactor: a.justificationFactor || 1,
        lineHeight: a.lineHeight || null,
        lineSpacing: a.lineSpacing || 0,
        link: a.link || null,
        marginLeft: a.marginLeft || a.margin || 0,
        marginRight: a.marginRight || a.margin || 0,
        opacity: a.opacity,
        paddingTop: a.paddingTop || a.padding || 0,
        paragraphSpacing: a.paragraphSpacing || 0,
        script: a.script || null,
        shrinkFactor: a.shrinkFactor || 0,
        strike: a.strike || false,
        strikeColor: a.strikeColor || a.color || 'black',
        strikeStyle: a.strikeStyle || 'solid',
        stroke: a.stroke || false,
        underline: a.underline || false,
        underlineColor: a.underlineColor || a.color || 'black',
        underlineStyle: a.underlineStyle || 'solid',
        verticalAlign: a.verticalAlign || null,
        wordSpacing: a.wordSpacing || 0,
        yOffset: a.yOffset || 0,
    };
};
/**
 * Apply default style to run
 *
 * @param run - Run
 * @returns Run with default styles
 */
const applyRunStyles = (run) => {
    const attributes = applyAttributes(run.attributes);
    return Object.assign({}, run, { attributes });
};
/**
 * Apply default attributes for an attributed string
 */
const applyDefaultStyles = () => {
    return (attributedString) => {
        const string = attributedString.string || '';
        const runs = (attributedString.runs || []).map(applyRunStyles);
        return { string, runs };
    };
};

/**
 * Apply scaling and yOffset for verticalAlign 'sub' and 'super'.
 */
const verticalAlignment = () => {
    /**
     * @param attributedString - Attributed string
     * @returns Attributed string
     */
    return (attributedString) => {
        attributedString.runs.forEach((run) => {
            const { attributes } = run;
            const { verticalAlign } = attributes;
            if (verticalAlign === 'sub') {
                attributes.yOffset = -0.2;
            }
            else if (verticalAlign === 'super') {
                attributes.yOffset = 0.4;
            }
        });
        return attributedString;
    };
};

const bidi$1 = bidiFactory();
/**
 * @param runs
 * @returns Bidi levels
 */
const getBidiLevels = (runs) => {
    return runs.reduce((acc, run) => {
        const length = run.end - run.start;
        const levels = repeat(run.attributes.bidiLevel, length);
        return acc.concat(levels);
    }, []);
};
/**
 * Perform bidi mirroring
 */
const mirrorString = () => {
    /**
     * @param attributedString - Attributed string
     * @returns Attributed string
     */
    return (attributedString) => {
        const levels = getBidiLevels(attributedString.runs);
        let updatedString = '';
        attributedString.string.split('').forEach((char, index) => {
            const isRTL = levels[index] % 2 === 1;
            const mirroredChar = isRTL
                ? bidi$1.getMirroredCharacter(attributedString.string.charAt(index))
                : null;
            updatedString += mirroredChar || char;
        });
        const result = {
            ...attributedString,
            string: updatedString,
        };
        return result;
    };
};

/**
 * A LayoutEngine is the main object that performs text layout.
 * It accepts an AttributedString and a Container object
 * to layout text into, and uses several helper objects to perform
 * various layout tasks. These objects can be overridden to customize
 * layout behavior.
 */
const layoutEngine = (engines) => {
    return (attributedString, container, options = {}) => {
        const processParagraph = compose(resolveYOffset(), resolveAttachments(), verticalAlignment(), generateGlyphs(), wrapWords(engines, options), mirrorString(), preprocessRuns(engines));
        const processParagraphs = (paragraphs) => paragraphs.map(processParagraph);
        return compose(finalizeFragments(engines, options), bidiReordering(), typesetter(engines, options, container), processParagraphs, splitParagraphs(), applyDefaultStyles(), decomposeUnicode())(attributedString);
    };
};

const bidi = bidiFactory();
const bidiEngine = () => {
    /**
     * @param attributedString - Attributed string
     * @returns Attributed string
     */
    return (attributedString) => {
        const { string } = attributedString;
        const direction = attributedString.runs[0]?.attributes.direction;
        const { levels } = bidi.getEmbeddingLevels(string, direction);
        let lastLevel = null;
        let lastIndex = 0;
        let index = 0;
        const runs = [];
        for (let i = 0; i < levels.length; i += 1) {
            const level = levels[i];
            if (level !== lastLevel) {
                if (lastLevel !== null) {
                    runs.push({
                        start: lastIndex,
                        end: index,
                        attributes: { bidiLevel: lastLevel },
                    });
                }
                lastIndex = index;
                lastLevel = level;
            }
            index += 1;
        }
        if (lastIndex < string.length) {
            runs.push({
                start: lastIndex,
                end: string.length,
                attributes: { bidiLevel: lastLevel },
            });
        }
        const result = { string, runs };
        return result;
    };
};

const INFINITY = 10000;
const skipPastGlueAndPenalty = (nodes, start) => {
    let j = start + 1;
    for (; j < nodes.length; j++) {
        if (nodes[j].type !== 'glue' && nodes[j].type !== 'penalty') {
            break;
        }
    }
    return nodes[j - 1];
};
const getNextBreakpoint = (subnodes, widths, lineNumber) => {
    let position = null;
    let minimumBadness = Infinity;
    const sum = { width: 0, stretch: 0, shrink: 0 };
    const lineLength = widths[Math.min(lineNumber, widths.length - 1)];
    const calculateRatio = (node) => {
        const stretch = 'stretch' in node ? node.stretch : null;
        if (sum.width < lineLength) {
            if (!stretch)
                return INFINITY;
            return sum.stretch - stretch > 0
                ? (lineLength - sum.width) / sum.stretch
                : INFINITY;
        }
        const shrink = 'shrink' in node ? node.shrink : null;
        if (sum.width > lineLength) {
            if (!shrink)
                return INFINITY;
            return sum.shrink - shrink > 0
                ? (lineLength - sum.width) / sum.shrink
                : INFINITY;
        }
        return 0;
    };
    let hyphenWidth = 0;
    for (let i = 0; i < subnodes.length; i += 1) {
        const node = subnodes[i];
        if (node.type === 'box') {
            sum.width += node.width;
        }
        if (node.type === 'glue') {
            sum.width += node.width;
            sum.stretch += node.stretch;
            sum.shrink += node.shrink;
        }
        const potentialEndOfLine = skipPastGlueAndPenalty(subnodes, i);
        hyphenWidth =
            potentialEndOfLine.type === 'penalty' ? potentialEndOfLine.width : 0;
        if (sum.width - sum.shrink + hyphenWidth > lineLength) {
            if (position === null) {
                let j = i === 0 ? i + 1 : i;
                while (j < subnodes.length &&
                    (subnodes[j].type === 'glue' || subnodes[j].type === 'penalty')) {
                    j++;
                }
                position = j - 1;
            }
            break;
        }
        if (node.type === 'penalty' || node.type === 'glue') {
            const ratio = calculateRatio(node);
            const penalty = node.type === 'penalty' ? node.penalty : 0;
            const badness = 100 * Math.abs(ratio) ** 3 + penalty;
            if (minimumBadness >= badness) {
                position = i;
                minimumBadness = badness;
            }
        }
    }
    return sum.width - sum.shrink + hyphenWidth > lineLength ? position : null;
};
const applyBestFit = (nodes, widths) => {
    let count = 0;
    let lineNumber = 0;
    let subnodes = nodes;
    const breakpoints = [0];
    while (subnodes.length > 0) {
        const breakpoint = getNextBreakpoint(subnodes, widths, lineNumber);
        if (breakpoint !== null) {
            count += breakpoint;
            breakpoints.push(count);
            subnodes = subnodes.slice(breakpoint + 1, subnodes.length);
            count++;
            lineNumber++;
        }
        else {
            subnodes = [];
        }
    }
    return breakpoints;
};

/* eslint-disable max-classes-per-file */
class LinkedListNode {
    data;
    prev;
    next;
    constructor(data) {
        this.data = data;
        this.prev = null;
        this.next = null;
    }
}
class LinkedList {
    static Node = LinkedListNode;
    head;
    tail;
    listSize;
    listLength;
    constructor() {
        this.head = null;
        this.tail = null;
        this.listSize = 0;
        this.listLength = 0;
    }
    isLinked(node) {
        return !((node &&
            node.prev === null &&
            node.next === null &&
            this.tail !== node &&
            this.head !== node) ||
            this.isEmpty());
    }
    size() {
        return this.listSize;
    }
    isEmpty() {
        return this.listSize === 0;
    }
    first() {
        return this.head;
    }
    last() {
        return this.last;
    }
    forEach(callback) {
        let node = this.head;
        while (node !== null) {
            callback(node);
            node = node.next;
        }
    }
    at(i) {
        let node = this.head;
        let index = 0;
        if (i >= this.listLength || i < 0) {
            return null;
        }
        while (node !== null) {
            if (i === index) {
                return node;
            }
            node = node.next;
            index += 1;
        }
        return null;
    }
    insertAfter(node, newNode) {
        if (!this.isLinked(node))
            return this;
        newNode.prev = node;
        newNode.next = node.next;
        if (node.next === null) {
            this.tail = newNode;
        }
        else {
            node.next.prev = newNode;
        }
        node.next = newNode;
        this.listSize += 1;
        return this;
    }
    insertBefore(node, newNode) {
        if (!this.isLinked(node))
            return this;
        newNode.prev = node.prev;
        newNode.next = node;
        if (node.prev === null) {
            this.head = newNode;
        }
        else {
            node.prev.next = newNode;
        }
        node.prev = newNode;
        this.listSize += 1;
        return this;
    }
    push(node) {
        if (this.head === null) {
            this.unshift(node);
        }
        else {
            this.insertAfter(this.tail, node);
        }
        return this;
    }
    unshift(node) {
        if (this.head === null) {
            this.head = node;
            this.tail = node;
            node.prev = null;
            node.next = null;
            this.listSize += 1;
        }
        else {
            this.insertBefore(this.head, node);
        }
        return this;
    }
    remove(node) {
        if (!this.isLinked(node))
            return this;
        if (node.prev === null) {
            this.head = node.next;
        }
        else {
            node.prev.next = node.next;
        }
        if (node.next === null) {
            this.tail = node.prev;
        }
        else {
            node.next.prev = node.prev;
        }
        this.listSize -= 1;
        return this;
    }
}

/**
 * Licensed under the new BSD License.
 * Copyright 2009-2010, Bram Stein
 * All rights reserved.
 */
function breakpoint(position, demerits, line, fitnessClass, totals, previous) {
    return {
        position,
        demerits,
        line,
        fitnessClass,
        totals: totals || {
            width: 0,
            stretch: 0,
            shrink: 0,
        },
        previous,
    };
}
function computeCost(nodes, lineLengths, sum, end, active, currentLine) {
    let width = sum.width - active.totals.width;
    let stretch = 0;
    let shrink = 0;
    // If the current line index is within the list of linelengths, use it, otherwise use
    // the last line length of the list.
    const lineLength = currentLine < lineLengths.length
        ? lineLengths[currentLine - 1]
        : lineLengths[lineLengths.length - 1];
    if (nodes[end].type === 'penalty') {
        width += nodes[end].width;
    }
    // Calculate the stretch ratio
    if (width < lineLength) {
        stretch = sum.stretch - active.totals.stretch;
        if (stretch > 0) {
            return (lineLength - width) / stretch;
        }
        return linebreak.infinity;
    }
    // Calculate the shrink ratio
    if (width > lineLength) {
        shrink = sum.shrink - active.totals.shrink;
        if (shrink > 0) {
            return (lineLength - width) / shrink;
        }
        return linebreak.infinity;
    }
    // perfect match
    return 0;
}
// Add width, stretch and shrink values from the current
// break point up to the next box or forced penalty.
function computeSum(nodes, sum, breakPointIndex) {
    const result = {
        width: sum.width,
        stretch: sum.stretch,
        shrink: sum.shrink,
    };
    for (let i = breakPointIndex; i < nodes.length; i += 1) {
        const node = nodes[i];
        if (node.type === 'glue') {
            result.width += node.width;
            result.stretch += node.stretch;
            result.shrink += node.shrink;
        }
        else if (node.type === 'box' ||
            (node.type === 'penalty' &&
                node.penalty === -linebreak.infinity &&
                i > breakPointIndex)) {
            break;
        }
    }
    return result;
}
function findBestBreakpoints(activeNodes) {
    const breakpoints = [];
    if (activeNodes.size() === 0)
        return [];
    let tmp = { data: { demerits: Infinity } };
    // Find the best active node (the one with the least total demerits.)
    activeNodes.forEach((node) => {
        if (node.data.demerits < tmp.data.demerits) {
            tmp = node;
        }
    });
    while (tmp !== null) {
        breakpoints.push(tmp.data.position);
        tmp = tmp.data.previous;
    }
    return breakpoints.reverse();
}
/**
 * @param nodes
 * @param availableWidths
 * @param tolerance
 * @preserve Knuth and Plass line breaking algorithm in JavaScript
 */
const linebreak = (nodes, availableWidths, tolerance) => {
    // Demerits are used as a way to penalize bad line breaks
    //  - line: applied to each line, depending on how much spaces need to stretch or shrink
    //  - flagged: applied when consecutive lines end in hyphenation
    //  - fitness: algorithm groups lines into fitness classes based on how loose or tight the spacing is.
    //             if a paragraph has consecutive lines from different fitness classes,
    //             a fitness demerit is applied to maintain visual consistency.
    const options = {
        demerits: { line: 10, flagged: 100, fitness: 3000 },
        tolerance: tolerance || 3,
    };
    const activeNodes = new LinkedList();
    const sum = { width: 0, stretch: 0, shrink: 0 };
    const lineLengths = availableWidths;
    // Add an active node for the start of the paragraph.
    activeNodes.push(new LinkedList.Node(breakpoint(0, 0, 0, 0, undefined, null)));
    // The main loop of the algorithm
    function mainLoop(node, index, nodes) {
        let active = activeNodes.first();
        // The inner loop iterates through all the active nodes with line < currentLine and then
        // breaks out to insert the new active node candidates before looking at the next active
        // nodes for the next lines. The result of this is that the active node list is always
        // sorted by line number.
        while (active !== null) {
            let currentLine = 0;
            // Candidates fo each fitness class
            const candidates = [
                { active: undefined, demerits: Infinity },
                { active: undefined, demerits: Infinity },
                { active: undefined, demerits: Infinity },
                { active: undefined, demerits: Infinity },
            ];
            // Iterate through the linked list of active nodes to find new potential active nodes and deactivate current active nodes.
            while (active !== null) {
                currentLine = active.data.line + 1;
                const ratio = computeCost(nodes, lineLengths, sum, index, active.data, currentLine);
                // Deactive nodes when the distance between the current active node and the
                // current node becomes too large (i.e. it exceeds the stretch limit and the stretch
                // ratio becomes negative) or when the current node is a forced break (i.e. the end
                // of the paragraph when we want to remove all active nodes, but possibly have a final
                // candidate active node---if the paragraph can be set using the given tolerance value.)
                if (ratio < -1 ||
                    (node.type === 'penalty' && node.penalty === -linebreak.infinity)) {
                    activeNodes.remove(active);
                }
                // If the ratio is within the valid range of -1 <= ratio <= tolerance calculate the
                // total demerits and record a candidate active node.
                if (ratio >= -1 && ratio <= options.tolerance) {
                    const badness = 100 * Math.pow(Math.abs(ratio), 3);
                    let demerits = 0;
                    // Positive penalty
                    if (node.type === 'penalty' && node.penalty >= 0) {
                        demerits =
                            Math.pow(options.demerits.line + badness, 2) +
                                Math.pow(node.penalty, 2);
                        // Negative penalty but not a forced break
                    }
                    else if (node.type === 'penalty' &&
                        node.penalty !== -linebreak.infinity) {
                        demerits =
                            Math.pow(options.demerits.line + badness, 2) -
                                Math.pow(node.penalty, 2);
                        // All other cases
                    }
                    else {
                        demerits = Math.pow(options.demerits.line + badness, 2);
                    }
                    if (node.type === 'penalty' &&
                        nodes[active.data.position].type === 'penalty') {
                        demerits +=
                            options.demerits.flagged *
                                node.flagged *
                                // @ts-expect-error node is penalty here
                                nodes[active.data.position].flagged;
                    }
                    // Calculate the fitness class for this candidate active node.
                    let currentClass;
                    if (ratio < -0.5) {
                        currentClass = 0;
                    }
                    else if (ratio <= 0.5) {
                        currentClass = 1;
                    }
                    else if (ratio <= 1) {
                        currentClass = 2;
                    }
                    else {
                        currentClass = 3;
                    }
                    // Add a fitness penalty to the demerits if the fitness classes of two adjacent lines differ too much.
                    if (Math.abs(currentClass - active.data.fitnessClass) > 1) {
                        demerits += options.demerits.fitness;
                    }
                    // Add the total demerits of the active node to get the total demerits of this candidate node.
                    demerits += active.data.demerits;
                    // Only store the best candidate for each fitness class
                    if (demerits < candidates[currentClass].demerits) {
                        candidates[currentClass] = { active, demerits };
                    }
                }
                active = active.next;
                // Stop iterating through active nodes to insert new candidate active nodes in the active list
                // before moving on to the active nodes for the next line.
                // TODO: The Knuth and Plass paper suggests a conditional for currentLine < j0. This means paragraphs
                // with identical line lengths will not be sorted by line number. Find out if that is a desirable outcome.
                // For now I left this out, as it only adds minimal overhead to the algorithm and keeping the active node
                // list sorted has a higher priority.
                if (active !== null && active.data.line >= currentLine) {
                    break;
                }
            }
            const tmpSum = computeSum(nodes, sum, index);
            for (let fitnessClass = 0; fitnessClass < candidates.length; fitnessClass += 1) {
                const candidate = candidates[fitnessClass];
                if (candidate.demerits === Infinity)
                    continue;
                const newNode = new LinkedList.Node(breakpoint(index, candidate.demerits, candidate.active.data.line + 1, fitnessClass, tmpSum, candidate.active));
                if (active !== null) {
                    activeNodes.insertBefore(active, newNode);
                }
                else {
                    activeNodes.push(newNode);
                }
            }
        }
    }
    nodes.forEach((node, index, nodes) => {
        if (node.type === 'box') {
            sum.width += node.width;
            return;
        }
        if (node.type === 'glue') {
            const precedesBox = index > 0 && nodes[index - 1].type === 'box';
            if (precedesBox)
                mainLoop(node, index, nodes);
            sum.width += node.width;
            sum.stretch += node.stretch;
            sum.shrink += node.shrink;
            return;
        }
        if (node.type === 'penalty' && node.penalty !== linebreak.infinity) {
            mainLoop(node, index, nodes);
        }
    });
    return findBestBreakpoints(activeNodes);
};
linebreak.infinity = 10000;
linebreak.glue = (width, start, end, stretch, shrink) => ({
    type: 'glue',
    start,
    end,
    width,
    stretch,
    shrink,
});
linebreak.box = (width, start, end, hyphenated = false) => ({
    type: 'box',
    width,
    start,
    end,
    hyphenated,
});
linebreak.penalty = (width, penalty, flagged) => ({
    type: 'penalty',
    width,
    penalty,
    flagged,
});

/**
 * Add scalar to run
 *
 * @param index - Scalar
 * @param run - Run
 * @returns Added run
 */
const add = (index, run) => {
    const start = run.start + index;
    const end = run.end + index;
    return Object.assign({}, run, { start, end });
};

/**
 * Get run length
 *
 * @param run - Run
 * @returns Length
 */
const length = (run) => {
    return run.end - run.start;
};

const concatStringIndices = (runA, runB) => {
    const runAIndices = runA.stringIndices || [];
    const runALastIndex = last(runAIndices) || 0;
    const runBIndices = (runB.stringIndices || []).map((i) => i + runALastIndex + 1);
    return normalize(runAIndices.concat(runBIndices));
};
const concatGlyphIndices = (runA, runB) => {
    const runAIndices = runA.glyphIndices || [];
    const runALength = runA.stringIndices?.length || 0;
    const runBIndices = (runB.glyphIndices || []).map((i) => i + runALength);
    return normalize(runAIndices.concat(runBIndices));
};
/**
 * Concats two runs into one
 *
 * @param runA - First run
 * @param runB - Second run
 * @returns Concatenated run
 */
const concat = (runA, runB) => {
    const end = runA.end + length(runB);
    const glyphs = (runA.glyphs || []).concat(runB.glyphs || []);
    const positions = (runA.positions || []).concat(runB.positions || []);
    const attributes = Object.assign({}, runA.attributes, runB.attributes);
    const stringIndices = concatStringIndices(runA, runB);
    const glyphIndices = concatGlyphIndices(runA, runB);
    return Object.assign({}, runA, {
        end,
        glyphs,
        positions,
        attributes,
        stringIndices,
        glyphIndices,
    });
};

/**
 * Insert glyph to run in the given index
 *
 * @param index - Index
 * @param glyph - Glyph
 * @param run - Run
 * @returns Run with glyph
 */
const insertGlyph$1 = (index, glyph, run) => {
    if (!glyph)
        return run;
    // Split resolves ligature splitting in case new glyph breaks some
    const leadingRun = slice$1(0, index, run);
    const trailingRun = slice$1(index, Infinity, run);
    return concat(append$1(glyph, leadingRun), trailingRun);
};
/**
 * Insert either glyph or code point to run in the given index
 *
 * @param index - Index
 * @param value - Glyph or codePoint
 * @param run - Run
 * @returns Run with glyph
 */
const insert = (index, value, run) => {
    const font = getFont(run);
    const glyph = isNumber(value) ? fromCodePoint(value, font) : value;
    return insertGlyph$1(index, glyph, run);
};

/**
 * Get run index at char index
 *
 * @param index - Char index
 * @param attributedString - Attributed string
 * @returns Run index
 */
const runIndexAt = (index, attributedString) => {
    return runIndexAt$1(index, attributedString.runs);
};

/**
 * Insert glyph into attributed string
 *
 * @param index - Index
 * @param glyph - Glyph or code point
 * @param attributedString - Attributed string
 * @returns Attributed string with new glyph
 */
const insertGlyph = (index, glyph, attributedString) => {
    const runIndex = runIndexAt(index, attributedString);
    // Add glyph to the end if run index invalid
    if (runIndex === -1)
        return append(glyph, attributedString);
    const codePoints = [glyph] ;
    const string = attributedString.string.slice(0, index) +
        stringFromCodePoints(codePoints) +
        attributedString.string.slice(index);
    const runs = attributedString.runs.map((run, i) => {
        if (i === runIndex)
            return insert(index - run.start, glyph, run);
        if (i > runIndex)
            return add(codePoints.length, run);
        return run;
    });
    return Object.assign({}, attributedString, { string, runs });
};

/**
 * Advance width between two string indices
 *
 * @param start - Glyph index
 * @param end - Glyph index
 * @param run - Run
 * @returns Advanced width run
 */
const advanceWidthBetween$1 = (start, end, run) => {
    const runStart = run.start || 0;
    const glyphStartIndex = Math.max(0, glyphIndexAt(start - runStart, run));
    const glyphEndIndex = Math.max(0, glyphIndexAt(end - runStart, run));
    const positions = (run.positions || []).slice(glyphStartIndex, glyphEndIndex);
    return advanceWidth$2(positions);
};

/**
 * Advance width between start and end
 * Does not consider ligature splitting for the moment.
 * Check performance impact on supporting this
 *
 * @param start - Start offset
 * @param end - End offset
 * @param attributedString
 * @returns Advance width
 */
const advanceWidthBetween = (start, end, attributedString) => {
    const runs = filter(start, end, attributedString.runs);
    return runs.reduce((acc, run) => acc + advanceWidthBetween$1(start, end, run), 0);
};

const HYPHEN = 0x002d;
const TOLERANCE_STEPS = 5;
const TOLERANCE_LIMIT = 50;
const opts = {
    width: 3,
    stretch: 6,
    shrink: 9,
};
/**
 * Slice attributed string to many lines
 *
 * @param attributedString - Attributed string
 * @param nodes
 * @param breaks
 * @returns Attributed strings
 */
const breakLines = (attributedString, nodes, breaks) => {
    let start = 0;
    let end = null;
    const lines = breaks.reduce((acc, breakPoint) => {
        const node = nodes[breakPoint];
        const prevNode = nodes[breakPoint - 1];
        // Last breakpoint corresponds to K&P mandatory final glue
        if (breakPoint === nodes.length - 1)
            return acc;
        let line;
        if (node.type === 'penalty') {
            // @ts-expect-error penalty node will always preceed box or glue node
            end = prevNode.end;
            line = slice(start, end, attributedString);
            line = insertGlyph(line.string.length, HYPHEN, line);
        }
        else {
            end = node.end;
            line = slice(start, end, attributedString);
        }
        start = end;
        return [...acc, line];
    }, []);
    lines.push(slice(start, attributedString.string.length, attributedString));
    return lines;
};
/**
 * Return Knuth & Plass nodes based on line and previously calculated syllables
 *
 * @param attributedString - Attributed string
 * @param attributes - Attributes
 * @param options - Layout options
 * @returns ?
 */
const getNodes = (attributedString, { align }, options) => {
    let start = 0;
    const hyphenWidth = 5;
    const { syllables } = attributedString;
    const hyphenPenalty = options.hyphenationPenalty || (align === 'justify' ? 100 : 600);
    const result = syllables.reduce((acc, s, index) => {
        const width = advanceWidthBetween(start, start + s.length, attributedString);
        if (s.trim() === '') {
            const stretch = (width * opts.width) / opts.stretch;
            const shrink = (width * opts.width) / opts.shrink;
            const end = start + s.length;
            // Add glue node. Glue nodes are used to fill the space between words.
            acc.push(linebreak.glue(width, start, end, stretch, shrink));
        }
        else {
            const hyphenated = syllables[index + 1] !== ' ';
            const end = start + s.length;
            // Add box node. Box nodes are used to represent words.
            acc.push(linebreak.box(width, start, end, hyphenated));
            if (syllables[index + 1] && hyphenated) {
                // Add penalty node. Penalty nodes are used to represent hyphenation points.
                acc.push(linebreak.penalty(hyphenWidth, hyphenPenalty, 1));
            }
        }
        start += s.length;
        return acc;
    }, []);
    // Add mandatory final glue
    result.push(linebreak.glue(0, start, start, linebreak.infinity, 0));
    result.push(linebreak.penalty(0, -linebreak.infinity, 1));
    return result;
};
/**
 * @param attributedString - Attributed string
 * @returns Attributes
 */
const getAttributes = (attributedString) => {
    return attributedString.runs?.[0]?.attributes || {};
};
/**
 * Performs Knuth & Plass line breaking algorithm
 * Fallbacks to best fit algorithm if latter not successful
 *
 * @param options - Layout options
 */
const linebreaker = (options) => {
    /**
     * @param attributedString - Attributed string
     * @param availableWidths - Available widths
     * @returns Attributed string
     */
    return (attributedString, availableWidths) => {
        let tolerance = options.tolerance || 4;
        const attributes = getAttributes(attributedString);
        const nodes = getNodes(attributedString, attributes, options);
        let breaks = linebreak(nodes, availableWidths, tolerance);
        // Try again with a higher tolerance if the line breaking failed.
        while (breaks.length === 0 && tolerance < TOLERANCE_LIMIT) {
            tolerance += TOLERANCE_STEPS;
            breaks = linebreak(nodes, availableWidths, tolerance);
        }
        if (breaks.length === 0 || (breaks.length === 1 && breaks[0] === 0)) {
            breaks = applyBestFit(nodes, availableWidths);
        }
        return breakLines(attributedString, nodes, breaks.slice(1));
    };
};

var Direction;
(function (Direction) {
    Direction[Direction["GROW"] = 0] = "GROW";
    Direction[Direction["SHRINK"] = 1] = "SHRINK";
})(Direction || (Direction = {}));
const WHITESPACE_PRIORITY = 1;
const LETTER_PRIORITY = 2;
const EXPAND_WHITESPACE_FACTOR = {
    before: 0.5,
    after: 0.5,
    priority: WHITESPACE_PRIORITY,
    unconstrained: false,
};
const EXPAND_CHAR_FACTOR = {
    before: 0.14453125, // 37/256
    after: 0.14453125,
    priority: LETTER_PRIORITY,
    unconstrained: false,
};
const SHRINK_WHITESPACE_FACTOR = {
    before: -0.04296875, // -11/256
    after: -0.04296875,
    priority: WHITESPACE_PRIORITY,
    unconstrained: false,
};
const SHRINK_CHAR_FACTOR = {
    before: -0.04296875,
    after: -0.04296875,
    priority: LETTER_PRIORITY,
    unconstrained: false,
};
const getCharFactor = (direction, options) => {
    const expandCharFactor = options.expandCharFactor || {};
    const shrinkCharFactor = options.shrinkCharFactor || {};
    return direction === Direction.GROW
        ? Object.assign({}, EXPAND_CHAR_FACTOR, expandCharFactor)
        : Object.assign({}, SHRINK_CHAR_FACTOR, shrinkCharFactor);
};
const getWhitespaceFactor = (direction, options) => {
    const expandWhitespaceFactor = options.expandWhitespaceFactor || {};
    const shrinkWhitespaceFactor = options.shrinkWhitespaceFactor || {};
    return direction === Direction.GROW
        ? Object.assign({}, EXPAND_WHITESPACE_FACTOR, expandWhitespaceFactor)
        : Object.assign({}, SHRINK_WHITESPACE_FACTOR, shrinkWhitespaceFactor);
};
const factor = (direction, options) => (glyphs) => {
    const charFactor = getCharFactor(direction, options);
    const whitespaceFactor = getWhitespaceFactor(direction, options);
    const factors = [];
    for (let index = 0; index < glyphs.length; index += 1) {
        let f;
        const glyph = glyphs[index];
        if (isWhiteSpace$1(glyph)) {
            f = Object.assign({}, whitespaceFactor);
            if (index === glyphs.length - 1) {
                f.before = 0;
                if (index > 0) {
                    factors[index - 1].after = 0;
                }
            }
        }
        else if (glyph.isMark && index > 0) {
            f = Object.assign({}, factors[index - 1]);
            f.before = 0;
            factors[index - 1].after = 0;
        }
        else {
            f = Object.assign({}, charFactor);
        }
        factors.push(f);
    }
    return factors;
};
const getFactors = (gap, line, options) => {
    const direction = gap > 0 ? Direction.GROW : Direction.SHRINK;
    const getFactor = factor(direction, options);
    const factors = line.runs.reduce((acc, run) => {
        return acc.concat(getFactor(run.glyphs));
    }, []);
    factors[0].before = 0;
    factors[factors.length - 1].after = 0;
    return factors;
};

const KASHIDA_PRIORITY = 0;
const NULL_PRIORITY = 3;
const getDistances = (gap, factors) => {
    let total = 0;
    const priorities = [];
    const unconstrained = [];
    for (let priority = KASHIDA_PRIORITY; priority <= NULL_PRIORITY; priority += 1) {
        priorities[priority] = unconstrained[priority] = 0;
    }
    // sum the factors at each priority
    for (let j = 0; j < factors.length; j += 1) {
        const f = factors[j];
        const sum = f.before + f.after;
        total += sum;
        priorities[f.priority] += sum;
        if (f.unconstrained) {
            unconstrained[f.priority] += sum;
        }
    }
    // choose the priorities that need to be applied
    let highestPriority = -1;
    let highestPrioritySum = 0;
    let remainingGap = gap;
    let priority;
    for (priority = KASHIDA_PRIORITY; priority <= NULL_PRIORITY; priority += 1) {
        const prioritySum = priorities[priority];
        if (prioritySum !== 0) {
            if (highestPriority === -1) {
                highestPriority = priority;
                highestPrioritySum = prioritySum;
            }
            // if this priority covers the remaining gap, we're done
            if (Math.abs(remainingGap) <= Math.abs(prioritySum)) {
                priorities[priority] = remainingGap / prioritySum;
                unconstrained[priority] = 0;
                remainingGap = 0;
                break;
            }
            // mark that we need to use 100% of the adjustment from
            // this priority, and subtract the space that it consumes
            priorities[priority] = 1;
            remainingGap -= prioritySum;
            // if this priority has unconstrained glyphs, let them consume the remaining space
            if (unconstrained[priority] !== 0) {
                unconstrained[priority] = remainingGap / unconstrained[priority];
                remainingGap = 0;
                break;
            }
        }
    }
    // zero out remaining priorities (if any)
    for (let p = priority + 1; p <= NULL_PRIORITY; p += 1) {
        priorities[p] = 0;
        unconstrained[p] = 0;
    }
    // if there is still space left over, assign it to the highest priority that we saw.
    // this violates their factors, but it only happens in extreme cases
    if (remainingGap > 0 && highestPriority > -1) {
        priorities[highestPriority] =
            (highestPrioritySum + (gap - total)) / highestPrioritySum;
    }
    // create and return an array of distances to add to each glyph's advance
    const distances = [];
    for (let index = 0; index < factors.length; index += 1) {
        // the distance to add to this glyph is the sum of the space to add
        // after this glyph, and the space to add before the next glyph
        const f = factors[index];
        const next = factors[index + 1];
        let dist = f.after * priorities[f.priority];
        if (next) {
            dist += next.before * priorities[next.priority];
        }
        // if this glyph is unconstrained, add the unconstrained distance as well
        if (f.unconstrained) {
            dist += f.after * unconstrained[f.priority];
            if (next) {
                dist += next.before * unconstrained[next.priority];
            }
        }
        distances.push(dist);
    }
    return distances;
};

/**
 * Adjust run positions by given distances
 *
 * @param distances
 * @param line
 * @returns Line
 */
const justifyLine = (distances, line) => {
    let index = 0;
    for (const run of line.runs) {
        for (const position of run.positions) {
            position.xAdvance += distances[index++];
        }
    }
    return line;
};
/**
 * A JustificationEngine is used by a Typesetter to perform line fragment
 * justification. This implementation is based on a description of Apple's
 * justification algorithm from a PDF in the Apple Font Tools package.
 *
 * @param options - Layout options
 */
const justification = (options) => {
    /**
     * @param line
     * @returns Line
     */
    return (line) => {
        const gap = line.box.width - advanceWidth(line);
        if (gap === 0)
            return line; // Exact fit
        const factors = getFactors(gap, line, options);
        const distances = getDistances(gap, factors);
        return justifyLine(distances, line);
    };
};

/**
 * Returns attributed string ascent
 *
 * @param attributedString - Attributed string
 * @returns Ascent
 */
const ascent = (attributedString) => {
    const reducer = (acc, run) => Math.max(acc, ascent$1(run));
    return attributedString.runs.reduce(reducer, 0);
};

// The base font size used for calculating underline thickness.
const BASE_FONT_SIZE = 12;
/**
 * A TextDecorationEngine is used by a Typesetter to generate
 * DecorationLines for a line fragment, including underlines
 * and strikes.
 */
const textDecoration = () => (line) => {
    let x = line.overflowLeft || 0;
    const overflowRight = line.overflowRight || 0;
    const maxX = advanceWidth(line) - overflowRight;
    line.decorationLines = [];
    for (let i = 0; i < line.runs.length; i += 1) {
        const run = line.runs[i];
        const width = Math.min(maxX - x, advanceWidth$1(run));
        const thickness = Math.max(0.5, Math.floor(run.attributes.fontSize / BASE_FONT_SIZE));
        if (run.attributes.underline) {
            const rect = {
                x,
                y: ascent(line) + thickness * 2,
                width,
                height: thickness,
            };
            const decorationLine = {
                rect,
                opacity: run.attributes.opacity,
                color: run.attributes.underlineColor || 'black',
                style: run.attributes.underlineStyle || 'solid',
            };
            line.decorationLines.push(decorationLine);
        }
        if (run.attributes.strike) {
            const y = ascent(line) - ascent$1(run) / 3;
            const rect = { x, y, width, height: thickness };
            const decorationLine = {
                rect,
                opacity: run.attributes.opacity,
                color: run.attributes.strikeColor || 'black',
                style: run.attributes.strikeStyle || 'solid',
            };
            line.decorationLines.push(decorationLine);
        }
        x += width;
    }
    return line;
};

const ignoredScripts = ['Common', 'Inherited', 'Unknown'];
/**
 * Resolves unicode script in runs, grouping equal runs together
 */
const scriptItemizer = () => {
    /**
     * @param attributedString - Attributed string
     * @returns Attributed string
     */
    return (attributedString) => {
        const { string } = attributedString;
        let lastScript = 'Unknown';
        let lastIndex = 0;
        let index = 0;
        const runs = [];
        if (!string)
            return empty();
        for (let i = 0; i < string.length; i += 1) {
            const char = string[i];
            const codePoint = char.codePointAt(0);
            const script = unicode.getScript(codePoint);
            if (script !== lastScript && !ignoredScripts.includes(script)) {
                if (lastScript !== 'Unknown') {
                    runs.push({
                        start: lastIndex,
                        end: index,
                        attributes: { script: lastScript },
                    });
                }
                lastIndex = index;
                lastScript = script;
            }
            index += char.length;
        }
        if (lastIndex < string.length) {
            runs.push({
                start: lastIndex,
                end: string.length,
                attributes: { script: lastScript },
            });
        }
        const result = { string, runs: runs };
        return result;
    };
};

const SOFT_HYPHEN = '\u00ad';
const hyphenator = hyphen(pattern);
/**
 * @param word
 * @returns Word parts
 */
const splitHyphen = (word) => {
    return word.split(SOFT_HYPHEN);
};
const cache = {};
/**
 * @param word
 * @returns Word parts
 */
const getParts = (word) => {
    const base = word.includes(SOFT_HYPHEN) ? word : hyphenator(word);
    return splitHyphen(base);
};
const wordHyphenation = () => {
    /**
     * @param word - Word
     * @returns Word parts
     */
    return (word) => {
        const cacheKey = `_${word}`;
        if (isNil(word))
            return [];
        if (cache[cacheKey])
            return cache[cacheKey];
        cache[cacheKey] = getParts(word);
        return cache[cacheKey];
    };
};

const IGNORED_CODE_POINTS = [173]; // U+00AD Soft Hyphen
const getFontSize = (run) => run.attributes.fontSize || 12;
const pickFontFromFontStack = (codePoint, fontStack, lastFont) => {
    if (IGNORED_CODE_POINTS.includes(codePoint))
        return lastFont;
    const fontStackWithFallback = [...fontStack, lastFont];
    for (let i = 0; i < fontStackWithFallback.length; i += 1) {
        const font = fontStackWithFallback[i];
        if (font &&
            font.hasGlyphForCodePoint &&
            font.hasGlyphForCodePoint(codePoint)) {
            return font;
        }
    }
    return fontStack.at(-1);
};
const fontSubstitution = () => ({ string, runs }) => {
    let lastFont = null;
    let lastFontSize = null;
    let lastIndex = 0;
    let index = 0;
    const res = [];
    for (let i = 0; i < runs.length; i += 1) {
        const run = runs[i];
        if (string.length === 0) {
            res.push({
                start: 0,
                end: 0,
                attributes: { font: run.attributes.font },
            });
            break;
        }
        const chars = string.slice(run.start, run.end);
        for (let j = 0; j < chars.length; j += 1) {
            const char = chars[j];
            const codePoint = char.codePointAt(0);
            // If the default font does not have a glyph and the fallback font does, we use it
            const font = pickFontFromFontStack(codePoint, run.attributes.font, lastFont);
            const fontSize = getFontSize(run);
            // If anything that would impact res has changed, update it
            if (font !== lastFont ||
                fontSize !== lastFontSize ||
                font.unitsPerEm !== lastFont?.unitsPerEm) {
                if (lastFont) {
                    res.push({
                        start: lastIndex,
                        end: index,
                        attributes: {
                            font: [lastFont],
                            scale: lastFontSize / lastFont.unitsPerEm,
                        },
                    });
                }
                lastFont = font;
                lastFontSize = fontSize;
                lastIndex = index;
            }
            index += char.length;
        }
    }
    if (lastIndex < string.length) {
        const fontSize = getFontSize(last(runs));
        res.push({
            start: lastIndex,
            end: string.length,
            attributes: {
                font: [lastFont],
                scale: fontSize / lastFont.unitsPerEm,
            },
        });
    }
    return { string, runs: res };
};

export { bidiEngine as bidi, layoutEngine as default, fontSubstitution, fromFragments, justification, linebreaker, scriptItemizer, textDecoration, wordHyphenation };