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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
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
import { upperFirst, capitalize, parseFloat as parseFloat$1, without, pick, compose, evolve, mapValues, matchPercent, castArray, isNil, omit, asyncCompose } from '@react-pdf/fns';
import * as P from '@react-pdf/primitives';
import resolveStyle, { transformColor, flatten } from '@react-pdf/stylesheet';
import layoutEngine, { fontSubstitution, wordHyphenation, scriptItemizer, textDecoration, justification, linebreaker, bidi, fromFragments } from '@react-pdf/textkit';
import * as Yoga from 'yoga-layout/load';
import { loadYoga as loadYoga$1 } from 'yoga-layout/load';
import emojiRegex from 'emoji-regex-xs';
import resolveImage from '@react-pdf/image';

/**
 * Apply transformation to text string
 *
 * @param {string} text
 * @param {string} transformation type
 * @returns {string} transformed text
 */
const transformText = (text, transformation) => {
    switch (transformation) {
        case 'uppercase':
            return text.toUpperCase();
        case 'lowercase':
            return text.toLowerCase();
        case 'capitalize':
            return capitalize(text);
        case 'upperfirst':
            return upperFirst(text);
        default:
            return text;
    }
};

const isTspan = (node) => node.type === P.Tspan;
const isTextInstance$4 = (node) => node.type === P.TextInstance;
const engines$1 = {
    bidi,
    linebreaker,
    justification,
    textDecoration,
    scriptItemizer,
    wordHyphenation,
    fontSubstitution,
};
const engine$1 = layoutEngine(engines$1);
const getFragments$1 = (fontStore, instance) => {
    if (!instance)
        return [{ string: '' }];
    const fragments = [];
    const { fill = 'black', fontFamily = 'Helvetica', fontWeight, fontStyle, fontSize = 18, textDecorationColor, textDecorationStyle, textTransform, opacity, } = instance.props;
    const _textDecoration = instance.props.textDecoration;
    const fontFamilies = typeof fontFamily === 'string' ? [fontFamily] : [...(fontFamily || [])];
    // Fallback font
    fontFamilies.push('Helvetica');
    const font = fontFamilies.map((fontFamilyName) => {
        const opts = { fontFamily: fontFamilyName, fontWeight, fontStyle };
        const obj = fontStore.getFont(opts);
        return obj?.data;
    });
    const attributes = {
        font,
        opacity,
        fontSize,
        color: fill,
        underlineStyle: textDecorationStyle,
        underline: _textDecoration === 'underline' ||
            _textDecoration === 'underline line-through' ||
            _textDecoration === 'line-through underline',
        underlineColor: textDecorationColor || fill,
        strike: _textDecoration === 'line-through' ||
            _textDecoration === 'underline line-through' ||
            _textDecoration === 'line-through underline',
        strikeStyle: textDecorationStyle,
        strikeColor: textDecorationColor || fill,
    };
    for (let i = 0; i < instance.children.length; i += 1) {
        const child = instance.children[i];
        if (isTextInstance$4(child)) {
            fragments.push({
                string: transformText(child.value, textTransform),
                attributes,
            });
        }
        else if (child) {
            fragments.push(...getFragments$1(fontStore, child));
        }
    }
    return fragments;
};
const getAttributedString$1 = (fontStore, instance) => fromFragments(getFragments$1(fontStore, instance));
const AlmostInfinity = 999999999999;
const shrinkWhitespaceFactor = { before: -0.5, after: -0.5 };
const layoutTspan = (fontStore) => (node, xOffset) => {
    const attributedString = getAttributedString$1(fontStore, node);
    const x = node.props.x === undefined ? xOffset : node.props.x;
    const y = node.props?.y || 0;
    const container = { x, y, width: AlmostInfinity, height: AlmostInfinity };
    const hyphenationCallback = node.props.hyphenationCallback ||
        fontStore?.getHyphenationCallback() ||
        null;
    const layoutOptions = { hyphenationCallback, shrinkWhitespaceFactor };
    const lines = engine$1(attributedString, container, layoutOptions).flat();
    return Object.assign({}, node, { lines });
};
// Consecutive TSpan elements should be joined with a space
const joinTSpanLines = (node) => {
    const children = node.children.map((child, index) => {
        if (!isTspan(child))
            return child;
        const textInstance = child.children[0];
        if (child.props.x === undefined &&
            index < node.children.length - 1 &&
            textInstance?.value) {
            return Object.assign({}, child, {
                children: [{ ...textInstance, value: `${textInstance.value} ` }],
            });
        }
        return child;
    }, []);
    return Object.assign({}, node, { children });
};
const layoutText$1 = (fontStore, node) => {
    if (!node.children)
        return node;
    let currentXOffset = node.props?.x || 0;
    const layoutFn = layoutTspan(fontStore);
    const joinedNode = joinTSpanLines(node);
    const children = joinedNode.children.map((child) => {
        const childWithLayout = layoutFn(child, currentXOffset);
        currentXOffset += childWithLayout.lines[0].xAdvance;
        return childWithLayout;
    });
    return Object.assign({}, node, { children });
};

const isDefs$1 = (node) => node.type === P.Defs;
const getDefs = (node) => {
    const children = node.children || [];
    const defs = children.find(isDefs$1);
    const values = defs?.children || [];
    return values.reduce((acc, value) => {
        const id = value.props?.id;
        if (id)
            acc[id] = value;
        return acc;
    }, {});
};

const isNotDefs = (node) => node.type !== P.Defs;
const detachDefs = (node) => {
    if (!node.children)
        return node;
    const children = node.children.filter(isNotDefs);
    return Object.assign({}, node, { children });
};
const URL_REGEX$1 = /url\(['"]?#([^'"]+)['"]?\)/;
const replaceDef = (defs, value) => {
    if (!value)
        return undefined;
    if (!URL_REGEX$1.test(value))
        return value;
    const match = value.match(URL_REGEX$1);
    return defs[match[1]];
};
const parseNodeDefs = (defs) => (node) => {
    const props = node.props;
    const fill = `fill` in props ? replaceDef(defs, props?.fill) : undefined;
    const clipPath = `clipPath` in props
        ? replaceDef(defs, props?.clipPath)
        : undefined;
    const markerStart = `markerStart` in props
        ? replaceDef(defs, props?.markerStart)
        : undefined;
    const markerMid = `markerMid` in props
        ? replaceDef(defs, props?.markerMid)
        : undefined;
    const markerEnd = `markerEnd` in props
        ? replaceDef(defs, props?.markerEnd)
        : undefined;
    const newProps = Object.assign({}, node.props, {
        fill,
        clipPath,
        markerStart,
        markerMid,
        markerEnd,
    });
    const children = node.children
        ? node.children.map(parseNodeDefs(defs))
        : undefined;
    return Object.assign({}, node, { props: newProps, children });
};
const parseDefs = (root) => {
    if (!root.children)
        return root;
    const defs = getDefs(root);
    const children = root.children.map(parseNodeDefs(defs));
    return Object.assign({}, root, { children });
};
const replaceDefs = (node) => {
    return detachDefs(parseDefs(node));
};

const parseViewbox = (value) => {
    if (!value)
        return null;
    if (typeof value !== 'string')
        return value;
    const values = value.split(/[,\s]+/).map(parseFloat$1);
    if (values.length !== 4)
        return null;
    return { minX: values[0], minY: values[1], maxX: values[2], maxY: values[3] };
};

const getContainer$1 = (node) => {
    const viewbox = parseViewbox(node.props.viewBox);
    if (viewbox) {
        return { width: viewbox.maxX, height: viewbox.maxY };
    }
    if (node.props.width && node.props.height) {
        return {
            width: parseFloat$1(node.props.width),
            height: parseFloat$1(node.props.height),
        };
    }
    return { width: 0, height: 0 };
};

const BASE_SVG_INHERITED_PROPS = [
    'x',
    'y',
    'clipPath',
    'clipRule',
    'opacity',
    'fill',
    'fillOpacity',
    'fillRule',
    'stroke',
    'strokeLinecap',
    'strokeLinejoin',
    'strokeOpacity',
    'strokeWidth',
    'textAnchor',
    'dominantBaseline',
    'color',
    'fontFamily',
    'fontSize',
    'fontStyle',
    'fontWeight',
    'letterSpacing',
    'opacity',
    'textDecoration',
    'lineHeight',
    'textAlign',
    'visibility',
    'wordSpacing',
];
// Do not inherit "x" for <tspan> elements from <text> parent
const TEXT_SVG_INHERITED_PROPS = without(['x'], BASE_SVG_INHERITED_PROPS);
const SVG_INHERITED_PROPS = {
    [P.Text]: TEXT_SVG_INHERITED_PROPS,
};
const getInheritProps = (node) => {
    const props = node.props || {};
    const svgInheritedProps = SVG_INHERITED_PROPS[node.type] ?? BASE_SVG_INHERITED_PROPS;
    return pick(svgInheritedProps, props);
};
const inheritProps = (node) => {
    if (!node.children)
        return node;
    const inheritedProps = getInheritProps(node);
    const children = node.children.map((child) => {
        const props = Object.assign({}, inheritedProps, child.props || {});
        const newChild = Object.assign({}, child, { props });
        return inheritProps(newChild);
    });
    return Object.assign({}, node, { children });
};

const parseAspectRatio = (value) => {
    if (typeof value !== 'string')
        return value;
    const match = value
        .replace(/[\s\r\t\n]+/gm, ' ')
        .replace(/^defer\s/, '')
        .split(' ');
    const align = (match[0] || 'xMidYMid');
    const meetOrSlice = (match[1] ||
        'meet');
    return { align, meetOrSlice };
};

const isMarker = (node) => node.type === P.Marker;
const STYLE_PROPS = [
    'width',
    'height',
    'color',
    'stroke',
    'strokeWidth',
    'opacity',
    'fillOpacity',
    'strokeOpacity',
    'fill',
    'fillRule',
    'clipPath',
    'offset',
    'transform',
    'strokeLinejoin',
    'strokeLinecap',
    'strokeDasharray',
    'gradientUnits',
    'gradientTransform',
    'stopColor',
    'stopOpacity',
];
const VERTICAL_PROPS = ['y', 'y1', 'y2', 'height', 'cy', 'ry'];
const HORIZONTAL_PROPS = ['x', 'x1', 'x2', 'width', 'cx', 'rx'];
const isSvg$3 = (node) => node.type === P.Svg;
const isText$5 = (node) => node.type === P.Text;
const isTextInstance$3 = (node) => node.type === P.TextInstance;
const transformPercent = (container) => (props) => mapValues(props, (value, key) => {
    const match = matchPercent(value);
    if (match && VERTICAL_PROPS.includes(key)) {
        return match.percent * container.height;
    }
    if (match && HORIZONTAL_PROPS.includes(key)) {
        return match.percent * container.width;
    }
    return value;
});
const parsePercent = (value) => {
    const match = matchPercent(value);
    return match ? match.percent : parseFloat$1(value);
};
const parseTransform = (container) => (value) => {
    return resolveStyle(container, { transform: value }).transform;
};
// Skip transformColor for url() references (gradients, patterns)
const URL_REGEX = /^url\(/;
const transformColorSafe = (value) => {
    if (typeof value === 'string' && URL_REGEX.test(value)) {
        return value;
    }
    return transformColor(value);
};
const parseProps = (container) => (node) => {
    let props = transformPercent(container)(node.props);
    props = evolve({
        x: parseFloat$1,
        x1: parseFloat$1,
        x2: parseFloat$1,
        y: parseFloat$1,
        y1: parseFloat$1,
        y2: parseFloat$1,
        r: parseFloat$1,
        rx: parseFloat$1,
        ry: parseFloat$1,
        cx: parseFloat$1,
        cy: parseFloat$1,
        width: parseFloat$1,
        height: parseFloat$1,
        fontSize: parseFloat$1,
        strokeWidth: parseFloat$1,
        strokeMiterlimit: parseFloat$1,
        strokeDashoffset: parseFloat$1,
        offset: parsePercent,
        fill: transformColorSafe,
        fillOpacity: parsePercent,
        opacity: parsePercent,
        stroke: transformColorSafe,
        strokeOpacity: parsePercent,
        stopOpacity: parsePercent,
        stopColor: transformColor,
        transform: parseTransform(container),
        gradientTransform: parseTransform(container),
    }, props);
    return Object.assign({}, node, { props });
};
// SVG spec: if rx is specified but ry is not, ry defaults to rx (and vice versa)
const resolveRectRadius = (node) => {
    if (node.type !== P.Rect || !node.props)
        return node;
    const { rx, ry } = node.props;
    // If both are specified or neither is specified, no change needed
    if ((rx && ry) || (!rx && !ry))
        return node;
    const newProps = Object.assign({}, node.props, {
        rx: rx ?? ry,
        ry: ry ?? rx,
    });
    return Object.assign({}, node, { props: newProps });
};
const mergeStyles$1 = (node) => {
    const style = node.style || {};
    const props = Object.assign({}, style, node.props);
    return Object.assign({}, node, { props });
};
const removeNoneValues = (node) => {
    const removeNone = (value) => (value === 'none' ? null : value);
    const props = mapValues(node.props, removeNone);
    return Object.assign({}, node, { props });
};
const pickStyleProps = (node) => {
    const props = node.props || {};
    const styleProps = pick(STYLE_PROPS, props);
    const style = Object.assign({}, styleProps, node.style || {});
    return Object.assign({}, node, { style });
};
const parseSvgProps = (node) => {
    const props = evolve({
        width: parseFloat$1,
        height: parseFloat$1,
        viewBox: parseViewbox,
        preserveAspectRatio: parseAspectRatio,
    }, node.props);
    return Object.assign({}, node, { props });
};
const wrapBetweenTspan = (node) => ({
    type: P.Tspan,
    props: {},
    style: {},
    children: [node],
});
const addMissingTspan = (node) => {
    if (!isText$5(node))
        return node;
    if (!node.children)
        return node;
    const resolveChild = (child) => isTextInstance$3(child) ? wrapBetweenTspan(child) : child;
    const children = node.children.map(resolveChild);
    return Object.assign({}, node, { children });
};
const parseText = (fontStore) => (node) => {
    if (isText$5(node))
        return layoutText$1(fontStore, node);
    if (!node.children)
        return node;
    const children = node.children.map(parseText(fontStore));
    return Object.assign({}, node, { children });
};
const resolveSvgNode = (container) => compose(parseProps(container), resolveRectRadius, pickStyleProps, addMissingTspan, removeNoneValues, mergeStyles$1);
// Gradient transforms typically don't use percentages, so use minimal container
const ZERO_CONTAINER = { width: 0, height: 0 };
const parseGradientTransform = parseTransform(ZERO_CONTAINER);
// Process DEFS children (LINEAR_GRADIENT, RADIAL_GRADIENT, STOP) without container-based percent transform
const parseDefsProps = (node) => {
    const props = evolve({
        // Gradient coordinates (percent becomes 0-1 range)
        x1: parsePercent,
        y1: parsePercent,
        x2: parsePercent,
        y2: parsePercent,
        cx: parsePercent,
        cy: parsePercent,
        fx: parsePercent,
        fy: parsePercent,
        r: parsePercent,
        gradientTransform: parseGradientTransform,
        // Stop properties
        offset: parsePercent,
        stopColor: transformColor,
        stopOpacity: parsePercent,
        // Marker properties
        refX: parseFloat$1,
        refY: parseFloat$1,
        markerWidth: parseFloat$1,
        markerHeight: parseFloat$1,
        viewBox: parseViewbox,
    }, node.props || {});
    return Object.assign({}, node, { props });
};
const getMarkerContainer = (node) => {
    const props = node.props || {};
    const viewBox = 'viewBox' in props
        ? props.viewBox
        : null;
    if (viewBox) {
        return { width: viewBox.maxX, height: viewBox.maxY };
    }
    const markerWidth = 'markerWidth' in props ? props.markerWidth : 3;
    const markerHeight = 'markerHeight' in props ? props.markerHeight : 3;
    return { width: markerWidth, height: markerHeight };
};
const resolveMarkerChildren = (node) => {
    if (!node.children)
        return node;
    const container = getMarkerContainer(node);
    const resolveChild = compose(resolveChildren(container), resolveSvgNode(container));
    const children = node.children.map(resolveChild);
    return Object.assign({}, node, { children });
};
const resolveDefsChildren = (node) => {
    if (!node.children)
        return node;
    const children = node.children.map((child) => {
        const parsed = parseDefsProps(child);
        if (isMarker(parsed))
            return resolveMarkerChildren(parsed);
        return resolveDefsChildren(parsed);
    });
    return Object.assign({}, node, { children });
};
const isDefs = (node) => node.type === P.Defs;
const resolveChildren = (container) => (node) => {
    if (!node.children)
        return node;
    const resolveChild = compose(resolveChildren(container), resolveSvgNode(container));
    // Process DEFS separately without container-based percent transform
    const children = node.children.map((child) => isDefs(child) ? resolveDefsChildren(child) : resolveChild(child));
    return Object.assign({}, node, { children });
};
const buildXLinksIndex = (node) => {
    const idIndex = {};
    const listToExplore = node.children?.slice(0) || [];
    while (listToExplore.length > 0) {
        const child = listToExplore.shift();
        if (child.props && 'id' in child.props) {
            idIndex[child.props.id] = child;
        }
        if (child.children)
            listToExplore.push(...child.children);
    }
    return idIndex;
};
const replaceXLinks = (node, idIndex) => {
    if (node.props && 'xlinkHref' in node.props) {
        const linkedNode = idIndex[node.props.xlinkHref.replace(/^#/, '')];
        // No node to extend from
        if (!linkedNode)
            return node;
        const newProps = Object.assign({}, linkedNode.props, node.props);
        delete newProps.xlinkHref;
        return Object.assign({}, linkedNode, { props: newProps });
    }
    const children = node.children?.map((child) => replaceXLinks(child, idIndex));
    return Object.assign({}, node, { children });
};
const resolveXLinks = (node) => {
    const idIndex = buildXLinksIndex(node);
    return replaceXLinks(node, idIndex);
};
const resolveSvgRoot = (node, fontStore) => {
    const container = getContainer$1(node);
    return compose(replaceDefs, parseText(fontStore), parseSvgProps, pickStyleProps, inheritProps, resolveChildren(container), resolveXLinks)(node);
};
const isSvgImage = (node) => node.type === P.Image && node.image?.format === 'svg';
function convertParsedNode(node) {
    return {
        type: node.type,
        props: node.props,
        style: {},
        children: node.children?.map(convertParsedNode),
        ...('value' in node && { value: node.value }),
    };
}
function convertToSvgNode(imageNode) {
    const image = imageNode.image;
    const width = imageNode.style?.width ?? image.width;
    const height = imageNode.style?.height ?? image.height;
    const viewBox = parseViewbox(image.data.props.viewBox);
    return {
        type: P.Svg,
        props: {
            width,
            height,
            viewBox,
            preserveAspectRatio: { align: 'xMidYMid', meetOrSlice: 'meet' },
        },
        style: { ...imageNode.style, width, height },
        box: imageNode.box,
        origin: imageNode.origin,
        yogaNode: imageNode.yogaNode,
        children: image.data.children.map(convertParsedNode),
    };
}
/**
 * Pre-process SVG nodes so they can be rendered in the next steps.
 * Also converts Image nodes containing SVG data into SvgNodes.
 *
 * @param node - Root node
 * @param fontStore - Font store
 * @returns Root node
 */
const resolveSvg = (node, fontStore) => {
    const resolved = isSvgImage(node) ? convertToSvgNode(node) : node;
    if (!('children' in resolved))
        return resolved;
    const resolveChild = (child) => resolveSvg(child, fontStore);
    const root = isSvg$3(resolved) ? resolveSvgRoot(resolved, fontStore) : resolved;
    const children = root.children?.map(resolveChild);
    return Object.assign({}, root, { children });
};

let instancePromise;
const loadYoga = async () => {
    // Yoga WASM binaries must be asynchronously compiled and loaded
    // to prevent Event emitter memory leak warnings, Yoga must be loaded only once
    const instance = await (instancePromise ??= loadYoga$1());
    const config = instance.Config.create();
    config.setPointScaleFactor(0);
    const node = { create: () => instance.Node.createWithConfig(config) };
    return { node };
};

const resolveYoga = async (root) => {
    const yoga = await loadYoga();
    return Object.assign({}, root, { yoga });
};

const getZIndex = (node) => node.style.zIndex;
const shouldSort = (node) => node.type !== P.Document && node.type !== P.Svg;
const sortZIndex = (a, b) => {
    const za = getZIndex(a);
    const zb = getZIndex(b);
    if (!za && !zb)
        return 0;
    if (!za)
        return 1;
    if (!zb)
        return -1;
    return zb - za;
};
/**
 * Sort children by zIndex value
 *
 * @param node
 * @returns Node
 */
const resolveNodeZIndex = (node) => {
    if (!node.children)
        return node;
    const sortedChildren = shouldSort(node)
        ? node.children.sort(sortZIndex)
        : node.children;
    const children = sortedChildren.map(resolveNodeZIndex);
    return Object.assign({}, node, { children });
};
/**
 * Sort children by zIndex value
 *
 * @param node
 * @returns Node
 */
const resolveZIndex = (root) => resolveNodeZIndex(root);

/* eslint-disable no-console */
// Caches emoji images data
const emojis = {};
const regex = emojiRegex();
/**
 * When an emoji as no variations, it might still have 2 parts,
 * the canonical emoji and an empty string.
 * ex.
 *   (no color) Array.from('❤️') => ["❤", "️"]
 *   (w/ color) Array.from('👍🏿') => ["👍", "🏿"]
 *
 * The empty string needs to be removed otherwise the generated
 * url will be incorect.
 */
const removeVariationSelectors = (x) => x !== '️';
const getCodePoints = (string, withVariationSelectors = false) => Array.from(string)
    .filter(withVariationSelectors ? () => true : removeVariationSelectors)
    .map((char) => char.codePointAt(0).toString(16))
    .join('-');
const buildEmojiUrl = (emoji, source) => {
    if ('builder' in source) {
        return source.builder(getCodePoints(emoji, source.withVariationSelectors));
    }
    const { url, format = 'png', withVariationSelectors } = source;
    return `${url}${getCodePoints(emoji, withVariationSelectors)}.${format}`;
};
const fetchEmojis = (string, source) => {
    if (!source)
        return [];
    const promises = [];
    Array.from(string.matchAll(regex)).forEach((match) => {
        const emoji = match[0];
        if (!emojis[emoji] || emojis[emoji].loading) {
            const emojiUrl = buildEmojiUrl(emoji, source);
            emojis[emoji] = { loading: true };
            promises.push(resolveImage({ uri: emojiUrl })
                .then((image) => {
                emojis[emoji].loading = false;
                emojis[emoji].data = image.data;
            })
                .catch((e) => {
                console.warn(e, 'Failed to load emoji image');
                emojis[emoji].loading = false;
            }));
        }
    });
    return promises;
};
const embedEmojis = (fragments) => {
    const result = [];
    for (let i = 0; i < fragments.length; i += 1) {
        const fragment = fragments[i];
        let lastIndex = 0;
        Array.from(fragment.string.matchAll(regex)).forEach((match) => {
            const { index } = match;
            const emoji = match[0];
            const emojiSize = fragment.attributes.fontSize;
            const chunk = fragment.string.slice(lastIndex, index + match[0].length);
            // If emoji image was found, we create a new fragment with the
            // correct attachment and object substitution character;
            if (emojis[emoji] && emojis[emoji].data) {
                result.push({
                    string: chunk.replace(match[0], String.fromCharCode(0xfffc)),
                    attributes: {
                        ...fragment.attributes,
                        attachment: {
                            width: emojiSize,
                            height: emojiSize,
                            yOffset: Math.floor(emojiSize * 0.1),
                            image: emojis[emoji].data,
                        },
                    },
                });
            }
            else {
                // If no emoji data, we try to use emojis in the font
                result.push({
                    string: chunk,
                    attributes: fragment.attributes,
                });
            }
            lastIndex = index + emoji.length;
        });
        if (lastIndex < fragment.string.length) {
            result.push({
                string: fragment.string.slice(lastIndex),
                attributes: fragment.attributes,
            });
        }
    }
    return result;
};

/**
 * Parses an HTML-compatible srcSet string into structured entries.
 * Only width descriptors (e.g. "300w") are supported.
 */
const parseSrcSet = (srcSet) => {
    return srcSet
        .split(',')
        .map((entry) => entry.trim())
        .filter(Boolean)
        .reduce((acc, entry) => {
        const parts = entry.split(/\s+/);
        const uri = parts[0];
        const descriptor = parts[1];
        if (descriptor && descriptor.endsWith('w')) {
            const width = parseFloat(descriptor);
            if (!Number.isNaN(width))
                acc.push({ uri, width });
        }
        return acc;
    }, []);
};
/**
 * Selects the most appropriate image source from a parsed srcSet
 * based on the target display width.
 *
 * Picks the smallest source that is >= targetWidth,
 * or the largest available if none are large enough.
 */
const selectSource = (entries, targetWidth) => {
    if (entries.length === 0)
        return '';
    const sorted = [...entries].sort((a, b) => a.width - b.width);
    const match = sorted.find((e) => e.width >= targetWidth);
    return match ? match.uri : sorted[sorted.length - 1].uri;
};
// TODO: Unify with page/getSize.ts parseValue/transformUnit into a shared unit parser
/**
 * Parses a CSS length value into points.
 * Supports: px, pt (default), in, mm, cm, vw, %.
 * vw and % are resolved relative to containerWidth.
 */
const parseLength = (value, containerWidth) => {
    const match = /^(-?\d*\.?\d+)\s*(px|pt|in|mm|cm|vw|%)?$/i.exec(value.trim());
    if (!match)
        return undefined;
    const num = parseFloat(match[1]);
    if (Number.isNaN(num))
        return undefined;
    const unit = match[2]?.toLowerCase();
    switch (unit) {
        case 'in':
            return num * 72;
        case 'mm':
            return num * (72 / 25.4);
        case 'cm':
            return num * (72 / 2.54);
        case 'px':
            return num;
        case 'vw':
            return (num / 100) * containerWidth;
        case '%':
            return (num / 100) * containerWidth;
        case 'pt':
        default:
            return num;
    }
};
/**
 * Evaluates a media condition like "(min-width: 600px)" or "(max-width: 400px)"
 * against the container width.
 */
const matchesCondition = (condition, containerWidth) => {
    const match = /\(\s*(min-width|max-width)\s*:\s*(-?\d*\.?\d+)\s*(px|pt|in|mm|cm|vw|%)?\s*\)/i.exec(condition);
    if (!match)
        return false;
    const feature = match[1].toLowerCase();
    const threshold = parseLength(`${match[2]}${match[3] || ''}`, containerWidth);
    if (threshold == null)
        return false;
    if (feature === 'min-width')
        return containerWidth >= threshold;
    if (feature === 'max-width')
        return containerWidth <= threshold;
    return false;
};
/**
 * Parses sizes attribute to get the target display width.
 *
 * Accepts a number (used directly as points) or a string.
 * For strings, evaluates media conditions against containerWidth
 * and returns the first matching entry's length value.
 *
 * Format: "(media-condition) length, (media-condition) length, default-length"
 */
const parseSizes = (sizes, containerWidth) => {
    if (sizes == null)
        return undefined;
    if (typeof sizes === 'number')
        return sizes;
    const entries = sizes.split(',').map((s) => s.trim());
    for (const entry of entries) {
        const conditionMatch = /^\(([^)]+)\)\s+(.+)$/.exec(entry);
        if (conditionMatch) {
            const condition = `(${conditionMatch[1]})`;
            const lengthStr = conditionMatch[2];
            if (matchesCondition(condition, containerWidth)) {
                return parseLength(lengthStr, containerWidth);
            }
        }
        else {
            return parseLength(entry, containerWidth);
        }
    }
    return undefined;
};
/**
 * Get image source, resolving srcSet if present.
 *
 * @param node - Image node
 * @param pageWidth - Page width for srcSet resolution
 * @returns Image src
 */
const getSource = (node, pageWidth) => {
    const { srcSet, sizes } = node.props;
    if (srcSet) {
        const entries = parseSrcSet(srcSet);
        if (entries.length > 0) {
            const targetWidth = parseSizes(sizes, pageWidth) || pageWidth;
            const uri = selectSource(entries, targetWidth);
            if (uri)
                return uri;
        }
    }
    if (node.props.src)
        return node.props.src;
    if (node.props.source)
        return node.props.source;
};

/**
 * Resolves `src` to `@react-pdf/image` interface.
 *
 * Also it handles factories and async sources.
 *
 * @param src
 * @returns Resolved src
 */
const resolveSource = async (src) => {
    const source = typeof src === 'function' ? await src() : await src;
    return typeof source === 'string' ? { uri: source } : source;
};

/**
 * Fetches image and appends data to node.
 * Ideally this fn should be immutable.
 *
 * @param node - Image or ImageBackground node
 * @param pageWidth - Page width for srcSet resolution
 */
const fetchImage = async (node, pageWidth) => {
    const { cache } = node.props;
    const src = getSource(node, pageWidth);
    if (!src) {
        console.warn(false, 'Image should receive either a "src" or "source" prop');
        return;
    }
    try {
        const source = await resolveSource(src);
        if (!source) {
            throw new Error(`Image's "src" or "source" prop returned ${source}`);
        }
        node.image = await resolveImage(source, { cache });
        if (Buffer.isBuffer(source) || source instanceof Blob)
            return;
        node.image.key = 'data' in source ? source.data.toString() : source.uri;
    }
    catch (e) {
        console.warn(e.message);
    }
};

const isImage$2 = (node) => node.type === P.Image;
const isImageBackground = (node) => node.type === P.ImageBackground;
/**
 * Get all asset promises that need to be resolved
 *
 * @param fontStore - Font store
 * @param node - Root node
 * @returns Asset promises
 */
const fetchAssets = (fontStore, node, pageWidth) => {
    const promises = [];
    const listToExplore = [node];
    const emojiSource = fontStore ? fontStore.getEmojiSource() : null;
    while (listToExplore.length > 0) {
        const n = listToExplore.shift();
        if (isImage$2(n) || isImageBackground(n)) {
            promises.push(fetchImage(n, pageWidth));
        }
        if (fontStore && n.style?.fontFamily) {
            const fontFamilies = castArray(n.style.fontFamily);
            promises.push(...fontFamilies.map((fontFamily) => fontStore.load({
                fontFamily,
                fontStyle: n.style.fontStyle,
                fontWeight: n.style.fontWeight,
            })));
        }
        if (typeof n === 'string') {
            promises.push(...fetchEmojis(n, emojiSource));
        }
        if ('value' in n && typeof n.value === 'string') {
            promises.push(...fetchEmojis(n.value, emojiSource));
        }
        if (n.children) {
            n.children.forEach((childNode) => {
                listToExplore.push(childNode);
            });
        }
    }
    return promises;
};
/**
 * Fetch assets for a page
 *
 * @param fontStore - Font store
 * @param page - Page node
 * @returns Asset promises
 */
const fetchPageAssets = (fontStore, page) => {
    const pageWidth = page.style?.width;
    return page.children
        ?.map((child) => fetchAssets(fontStore, child, pageWidth))
        .flat();
};
/**
 * Fetch image, font and emoji assets in parallel.
 * Layout process will not be resumed until promise resolves.
 *
 * @param node root node
 * @param fontStore font store
 * @returns Root node
 */
const resolveAssets = async (node, fontStore) => {
    const promises = node.children
        .map((page) => fetchPageAssets(fontStore, page))
        .flat();
    await Promise.all(promises);
    return node;
};

const isLink$1 = (node) => node.type === P.Link;
const DEFAULT_LINK_STYLES = {
    color: 'blue',
    textDecoration: 'underline',
};
/**
 * Computes styles using stylesheet
 *
 * @param container
 * @param node - Document node
 * @returns Computed styles
 */
const computeStyle = (container, node) => {
    let baseStyle = [node.style];
    if (isLink$1(node)) {
        baseStyle = Array.isArray(node.style)
            ? [DEFAULT_LINK_STYLES, ...node.style]
            : [DEFAULT_LINK_STYLES, node.style];
    }
    return resolveStyle(container, baseStyle);
};
/**
 * Resolves node styles
 *
 * @param container
 * @returns Resolve node styles
 */
const resolveNodeStyles = (container) => (node) => {
    const style = computeStyle(container, node);
    if (!node.children)
        return Object.assign({}, node, { style });
    const children = node.children.map(resolveNodeStyles(container));
    return Object.assign({}, node, { style, children });
};
/**
 * Resolves page styles
 *
 * @param page Document page
 * @returns Document page with resolved styles
 */
const resolvePageStyles = (page) => {
    const dpi = page.props?.dpi || 72;
    const style = page.style;
    const width = page.box?.width || style.width;
    const height = page.box?.height || style.height;
    const orientation = page.props?.orientation || 'portrait';
    const remBase = style?.fontSize || 18;
    const container = { width, height, orientation, dpi, remBase };
    return resolveNodeStyles(container)(page);
};
/**
 * Resolves document styles
 *
 * @param root - Document root
 * @returns Document root with resolved styles
 */
const resolveStyles = (root) => {
    if (!root.children)
        return root;
    const children = root.children.map(resolvePageStyles);
    return Object.assign({}, root, { children });
};

const getTransformStyle = (s) => (node) => isNil(node.style?.[s]) ? '50%' : node.style?.[s] ?? null;
/**
 * Get node origin
 *
 * @param node
 * @returns {{ left?: number, top?: number }} node origin
 */
const getOrigin = (node) => {
    if (!node.box)
        return null;
    const { left, top, width, height } = node.box;
    const transformOriginX = getTransformStyle('transformOriginX')(node);
    const transformOriginY = getTransformStyle('transformOriginY')(node);
    const percentX = matchPercent(transformOriginX);
    const percentY = matchPercent(transformOriginY);
    const offsetX = percentX ? width * percentX.percent : transformOriginX;
    const offsetY = percentY ? height * percentY.percent : transformOriginY;
    if (isNil(offsetX) || typeof offsetX === 'string')
        throw new Error(`Invalid origin offsetX: ${offsetX}`);
    if (isNil(offsetY) || typeof offsetY === 'string')
        throw new Error(`Invalid origin offsetY: ${offsetY}`);
    return { left: left + offsetX, top: top + offsetY };
};

/**
 * Resolve node origin
 *
 * @param node
 * @returns Node with origin attribute
 */
const resolveNodeOrigin = (node) => {
    const origin = getOrigin(node);
    const newNode = Object.assign({}, node, { origin });
    if (!node.children)
        return newNode;
    const children = node.children.map(resolveNodeOrigin);
    return Object.assign({}, newNode, { children });
};
/**
 * Resolve document origins
 *
 * @param root - Document root
 * @returns Document root
 */
const resolveOrigin = (root) => {
    if (!root.children)
        return root;
    const children = root.children.map(resolveNodeOrigin);
    return Object.assign({}, root, { children });
};

/**
 * Normalize bookmark value, expanding a plain string title into a full
 * bookmark object with default fit and expanded values
 *
 * @param bookmark - Bookmark value
 * @returns Normalized bookmark object
 */
const getBookmarkValue = (bookmark) => {
    return typeof bookmark === 'string'
        ? { title: bookmark, fit: false, expanded: false }
        : bookmark;
};
/**
 * Traverse document tree and resolve bookmark hierarchy, assigning each
 * bookmark a ref index and a reference to its nearest bookmark ancestor
 *
 * @param node - Document node
 * @returns Document node with resolved bookmarks
 */
const resolveBookmarks = (node) => {
    let refs = 0;
    const listToExplore = (node.children || []).map((value) => ({
        value,
        parent: null,
    }));
    while (listToExplore.length > 0) {
        const element = listToExplore.shift();
        if (!element)
            break;
        const child = element.value;
        let parent = element.parent;
        if (child.props && 'bookmark' in child.props && child.props.bookmark) {
            const bookmark = getBookmarkValue(child.props.bookmark);
            const ref = refs++;
            const newHierarchy = { ref, parent: parent?.ref, ...bookmark };
            child.props.bookmark = newHierarchy;
            parent = newHierarchy;
        }
        if (child.children) {
            child.children.forEach((childNode) => {
                listToExplore.push({ value: childNode, parent });
            });
        }
    }
    return node;
};

const VALID_ORIENTATIONS = ['portrait', 'landscape'];
/**
 * Get page orientation. Defaults to portrait
 *
 * @param page - Page object
 * @returns Page orientation
 */
const getOrientation = (page) => {
    const value = page.props?.orientation || 'portrait';
    return VALID_ORIENTATIONS.includes(value) ? value : 'portrait';
};

/**
 * Return true if page is landscape
 *
 * @param page - Page instance
 * @returns Is page landscape
 */
const isLandscape = (page) => getOrientation(page) === 'landscape';

// Page sizes for 72dpi. 72dpi is used internally by pdfkit.
const PAGE_SIZES = {
    '4A0': [4767.87, 6740.79],
    '2A0': [3370.39, 4767.87],
    A0: [2383.94, 3370.39],
    A1: [1683.78, 2383.94],
    A2: [1190.55, 1683.78],
    A3: [841.89, 1190.55],
    A4: [595.28, 841.89],
    A5: [419.53, 595.28],
    A6: [297.64, 419.53],
    A7: [209.76, 297.64],
    A8: [147.4, 209.76],
    A9: [104.88, 147.4],
    A10: [73.7, 104.88],
    B0: [2834.65, 4008.19],
    B1: [2004.09, 2834.65],
    B2: [1417.32, 2004.09],
    B3: [1000.63, 1417.32],
    B4: [708.66, 1000.63],
    B5: [498.9, 708.66],
    B6: [354.33, 498.9],
    B7: [249.45, 354.33],
    B8: [175.75, 249.45],
    B9: [124.72, 175.75],
    B10: [87.87, 124.72],
    C0: [2599.37, 3676.54],
    C1: [1836.85, 2599.37],
    C2: [1298.27, 1836.85],
    C3: [918.43, 1298.27],
    C4: [649.13, 918.43],
    C5: [459.21, 649.13],
    C6: [323.15, 459.21],
    C7: [229.61, 323.15],
    C8: [161.57, 229.61],
    C9: [113.39, 161.57],
    C10: [79.37, 113.39],
    RA0: [2437.8, 3458.27],
    RA1: [1729.13, 2437.8],
    RA2: [1218.9, 1729.13],
    RA3: [864.57, 1218.9],
    RA4: [609.45, 864.57],
    SRA0: [2551.18, 3628.35],
    SRA1: [1814.17, 2551.18],
    SRA2: [1275.59, 1814.17],
    SRA3: [907.09, 1275.59],
    SRA4: [637.8, 907.09],
    EXECUTIVE: [521.86, 756.0],
    FOLIO: [612.0, 936.0],
    LEGAL: [612.0, 1008.0],
    LETTER: [612.0, 792.0],
    TABLOID: [792.0, 1224.0],
    ID1: [153, 243],
};
/**
 * Parses scalar value in value and unit pairs
 *
 * @param value - Scalar value
 * @returns Parsed value
 */
const parseValue = (value) => {
    if (typeof value === 'number')
        return { value, unit: undefined };
    const match = /^(-?\d*\.?\d+)(in|mm|cm|pt|px)?$/g.exec(value);
    return match
        ? { value: parseFloat(match[1]), unit: match[2] || 'pt' }
        : { value, unit: undefined };
};
/**
 * Transform given scalar value to 72dpi equivalent of size
 *
 * @param value - Styles value
 * @param inputDpi - User defined dpi
 * @returns Transformed value
 */
const transformUnit = (value, inputDpi) => {
    if (!value || value === 'auto')
        return undefined;
    const scalar = parseValue(value);
    const outputDpi = 72;
    const mmFactor = (1 / 25.4) * outputDpi;
    const cmFactor = (1 / 2.54) * outputDpi;
    if (typeof scalar.value === 'string')
        throw new Error(`Invalid page size: ${value}`);
    switch (scalar.unit) {
        case 'in':
            return scalar.value * outputDpi;
        case 'mm':
            return scalar.value * mmFactor;
        case 'cm':
            return scalar.value * cmFactor;
        case 'px':
            return Math.round(scalar.value * (outputDpi / inputDpi));
        default:
            return scalar.value;
    }
};
const transformUnits = ({ width, height }, dpi) => {
    const result = { width: transformUnit(width, dpi) || 0 };
    const h = transformUnit(height, dpi);
    if (h !== undefined)
        result.height = h;
    return result;
};
/**
 * Transforms array into size object
 *
 * @param v - Values array
 * @returns Size object with width and height
 */
const toSizeObject = (v) => ({
    width: v[0],
    height: v[1],
});
/**
 * Flip size object
 *
 * @param v - Size object
 * @returns Flipped size object
 */
const flipSizeObject = (v) => {
    const result = { width: v.height || 0 };
    if (v.width !== undefined)
        result.height = v.width;
    return result;
};
/**
 * Returns size object from a given string
 *
 * @param v - Page size string
 * @returns Size object with width and height
 */
const getStringSize = (v) => {
    return toSizeObject(PAGE_SIZES[v.toUpperCase()]);
};
/**
 * Returns size object from a single number
 *
 * @param n - Page size number
 * @returns Size object with width and height
 */
const getNumberSize = (n) => toSizeObject([n, n]);
/**
 * Return page size in an object { width, height }
 *
 * @param page - Page node
 * @returns Size object with width and height
 */
const getSize = (page) => {
    const value = page.props?.size || 'A4';
    const dpi = page.props?.dpi || 72;
    let size;
    if (typeof value === 'string') {
        size = getStringSize(value);
    }
    else if (Array.isArray(value)) {
        size = transformUnits(toSizeObject(value), dpi);
    }
    else if (typeof value === 'number') {
        size = transformUnits(getNumberSize(value), dpi);
    }
    else {
        size = transformUnits(value, dpi);
    }
    return isLandscape(page) ? flipSizeObject(size) : size;
};

/**
 * Resolves page size
 *
 * @param page
 * @returns Page with resolved size in style attribute
 */
const resolvePageSize = (page) => {
    const size = getSize(page);
    const style = flatten(page.style || {});
    return { ...page, style: { ...style, ...size } };
};
/**
 * Resolves page sizes
 *
 * @param root  -Document root
 * @returns Document root with resolved page sizes
 */
const resolvePageSizes = (root) => {
    if (!root.children)
        return root;
    const children = root.children.map(resolvePageSize);
    return Object.assign({}, root, { children });
};

const isFixed = (node) => {
    if (!node.props)
        return false;
    return 'fixed' in node.props ? node.props.fixed === true : false;
};

/**
 * Get line index at given height
 *
 * @param node
 * @param height
 */
const lineIndexAtHeight = (node, height) => {
    let y = 0;
    if (!node.lines)
        return 0;
    for (let i = 0; i < node.lines.length; i += 1) {
        const line = node.lines[i];
        if (y + line.box.height > height)
            return i;
        y += line.box.height;
    }
    return node.lines.length;
};

/**
 * Get height for given text line index
 *
 * @param node
 * @param index
 */
const heightAtLineIndex = (node, index) => {
    let counter = 0;
    if (!node.lines)
        return counter;
    for (let i = 0; i < index; i += 1) {
        const line = node.lines[i];
        if (!line)
            break;
        counter += line.box.height;
    }
    return counter;
};

const getLineBreak = (node, height) => {
    const top = node.box?.top || 0;
    const widows = node.props.widows || 2;
    const orphans = node.props.orphans || 2;
    const linesQuantity = node.lines.length;
    const slicedLine = lineIndexAtHeight(node, height - top);
    if (slicedLine === 0) {
        return 0;
    }
    if (linesQuantity < orphans) {
        return linesQuantity;
    }
    if (slicedLine < orphans || linesQuantity < orphans + widows) {
        return 0;
    }
    if (linesQuantity === orphans + widows) {
        return orphans;
    }
    if (linesQuantity - slicedLine < widows) {
        return linesQuantity - widows;
    }
    return slicedLine;
};
// Also receives contentArea in case it's needed
const splitText = (node, height) => {
    const slicedLineIndex = getLineBreak(node, height);
    const currentHeight = heightAtLineIndex(node, slicedLineIndex);
    const nextHeight = node.box.height - currentHeight;
    const current = Object.assign({}, node, {
        box: {
            ...node.box,
            height: currentHeight,
            borderBottomWidth: 0,
        },
        style: {
            ...node.style,
            marginBottom: 0,
            paddingBottom: 0,
            borderBottomWidth: 0,
            borderBottomLeftRadius: 0,
            borderBottomRightRadius: 0,
        },
        lines: node.lines.slice(0, slicedLineIndex),
    });
    const next = Object.assign({}, node, {
        box: {
            ...node.box,
            top: 0,
            height: nextHeight,
            borderTopWidth: 0,
        },
        style: {
            ...node.style,
            marginTop: 0,
            paddingTop: 0,
            borderTopWidth: 0,
            borderTopLeftRadius: 0,
            borderTopRightRadius: 0,
        },
        lines: node.lines.slice(slicedLineIndex),
    });
    return [current, next];
};

const getTop$1 = (node) => node.box?.top || 0;
const hasFixedHeight = (node) => !isNil(node.style?.height);
const splitNode = (node, height) => {
    if (!node)
        return [null, null];
    const nodeTop = getTop$1(node);
    const current = Object.assign({}, node, {
        box: {
            ...node.box,
            borderBottomWidth: 0,
        },
        style: {
            ...node.style,
            marginBottom: 0,
            paddingBottom: 0,
            borderBottomWidth: 0,
            borderBottomLeftRadius: 0,
            borderBottomRightRadius: 0,
        },
    });
    current.style.height = height - nodeTop;
    const nextHeight = hasFixedHeight(node)
        ? node.box.height - (height - nodeTop)
        : null;
    const next = Object.assign({}, node, {
        box: {
            ...node.box,
            top: 0,
            borderTopWidth: 0,
        },
        style: {
            ...node.style,
            marginTop: 0,
            paddingTop: 0,
            borderTopWidth: 0,
            borderTopLeftRadius: 0,
            borderTopRightRadius: 0,
        },
        props: {
            ...node.props,
            bookmark: null,
        },
    });
    if (nextHeight) {
        next.style.height = nextHeight;
    }
    return [current, next];
};

const NON_WRAP_TYPES = [P.Svg, P.Note, P.Image, P.Canvas];
const getWrap = (node) => {
    if (NON_WRAP_TYPES.includes(node.type))
        return false;
    if (!node.props)
        return true;
    return 'wrap' in node.props ? node.props.wrap : true;
};

const getComputedPadding = (node, edge) => {
    const { yogaNode } = node;
    return yogaNode ? yogaNode.getComputedPadding(edge) : null;
};
/**
 * Get Yoga computed paddings. Zero otherwise
 *
 * @param  node
 * @returns paddings
 */
const getPadding = (node) => {
    const { style, box } = node;
    const paddingTop = getComputedPadding(node, Yoga.Edge.Top) ||
        box?.paddingTop ||
        style?.paddingTop ||
        0;
    const paddingRight = getComputedPadding(node, Yoga.Edge.Right) ||
        box?.paddingRight ||
        style?.paddingRight ||
        0;
    const paddingBottom = getComputedPadding(node, Yoga.Edge.Bottom) ||
        box?.paddingBottom ||
        style?.paddingBottom ||
        0;
    const paddingLeft = getComputedPadding(node, Yoga.Edge.Left) ||
        box?.paddingLeft ||
        style?.paddingLeft ||
        0;
    return { paddingTop, paddingRight, paddingBottom, paddingLeft };
};

const getWrapArea = (page) => {
    const height = page.style?.height;
    const { paddingBottom } = getPadding(page);
    return height - paddingBottom;
};

const getContentArea = (page) => {
    const height = page.style?.height;
    const { paddingTop, paddingBottom } = getPadding(page);
    return height - paddingBottom - paddingTop;
};

const isString = (value) => typeof value === 'string';
const isNumber = (value) => typeof value === 'number';
const isBoolean = (value) => typeof value === 'boolean';
const isFragment = (value) => value && value.type === Symbol.for('react.fragment');
/**
 * Transforms a react element instance to internal element format.
 *
 * Can return multiple instances in the case of arrays or fragments.
 *
 * @param element - React element
 * @returns Parsed React elements
 */
const createInstances = (element) => {
    if (!element)
        return [];
    if (Array.isArray(element)) {
        return element.reduce((acc, el) => acc.concat(createInstances(el)), []);
    }
    if (isBoolean(element)) {
        return [];
    }
    if (isString(element) || isNumber(element)) {
        return [{ type: P.TextInstance, value: `${element}` }];
    }
    if (isFragment(element)) {
        // @ts-expect-error figure out why this is complains
        return createInstances(element.props.children);
    }
    if (!isString(element.type)) {
        // @ts-expect-error figure out why this is complains
        return createInstances(element.type(element.props));
    }
    const { type, props: { style = {}, children, ...props }, } = element;
    const nextChildren = castArray(children).reduce((acc, child) => acc.concat(createInstances(child)), []);
    return [
        {
            type,
            style,
            props,
            children: nextChildren,
        },
    ];
};

const getBreak = (node) => 'break' in node.props ? node.props.break : false;
const getMinPresenceAhead = (node) => 'minPresenceAhead' in node.props ? node.props.minPresenceAhead : 0;
const getFurthestEnd = (elements) => {
    if (elements.length === 0)
        return null;
    return Math.max(...elements.map((node) => node.box.top + node.box.height));
};
const getEndOfMinPresenceAhead = (child) => {
    return (child.box.top +
        child.box.height +
        child.box.marginBottom +
        getMinPresenceAhead(child));
};
const getEndOfPresence = (child, futureElements) => {
    const afterMinPresenceAhead = getEndOfMinPresenceAhead(child);
    const nonFixedFuture = futureElements.filter((node) => !('fixed' in node.props));
    const endOfFurthestFutureElement = getFurthestEnd(nonFixedFuture);
    // When there are no future non-fixed siblings, use only minPresenceAhead
    if (endOfFurthestFutureElement === null)
        return afterMinPresenceAhead;
    return Math.min(afterMinPresenceAhead, endOfFurthestFutureElement);
};
const shouldBreak = (child, futureElements, height, previousElements) => {
    if ('fixed' in child.props)
        return false;
    const shouldSplit = height < child.box.top + child.box.height;
    const canWrap = getWrap(child);
    // Calculate the y coordinate where the desired presence of the child ends
    const endOfPresence = getEndOfPresence(child, futureElements);
    // If the child is already at the top of the page, breaking won't improve its presence
    // (as long as react-pdf does not support breaking into differently sized containers)
    const breakingImprovesPresence = previousElements.filter((node) => !isFixed(node)).length > 0;
    return (getBreak(child) ||
        (shouldSplit && !canWrap) ||
        (!shouldSplit && endOfPresence > height && breakingImprovesPresence));
};

const IGNORABLE_CODEPOINTS = [
    8232, // LINE_SEPARATOR
    8233, // PARAGRAPH_SEPARATOR
    8288, // WORD_JOINER
];
const buildSubsetForFont = (font) => IGNORABLE_CODEPOINTS.reduce((acc, codePoint) => {
    if (font &&
        font.hasGlyphForCodePoint &&
        font.hasGlyphForCodePoint(codePoint)) {
        return acc;
    }
    return [...acc, String.fromCharCode(codePoint)];
}, []);
const ignoreChars = (fragments) => fragments.map((fragment) => {
    const charSubset = buildSubsetForFont(fragment.attributes.font[0]);
    const subsetRegex = new RegExp(charSubset.join('|'));
    return {
        string: fragment.string.replace(subsetRegex, ''),
        attributes: fragment.attributes,
    };
});

const PREPROCESSORS = [ignoreChars, embedEmojis];
const isImage$1 = (node) => node.type === P.Image;
const isRasterImage = (node) => !!node.image && node.image.format !== 'svg';
const isTextInstance$2 = (node) => node.type === P.TextInstance;
/**
 * Get textkit fragments of given node object
 *
 * @param fontStore - Font store
 * @param instance - Node
 * @param parentLink - Parent link
 * @param level - Fragment level
 * @returns Text fragments
 */
const getFragments = (fontStore, instance, parentLink = null, level = 0) => {
    if (!instance)
        return [{ string: '' }];
    let fragments = [];
    const { color = 'black', direction = 'ltr', fontFamily = 'Helvetica', fontWeight, fontStyle, fontSize = 18, textAlign, lineHeight, textDecoration, textDecorationColor, textDecorationStyle, textTransform, letterSpacing, textIndent, opacity, verticalAlign, } = instance.style;
    const fontFamilies = typeof fontFamily === 'string' ? [fontFamily] : [...(fontFamily || [])];
    // Fallback font
    fontFamilies.push('Helvetica');
    const font = fontFamilies.map((fontFamilyName) => {
        const opts = { fontFamily: fontFamilyName, fontWeight, fontStyle };
        const obj = fontStore.getFont(opts);
        return obj?.data;
    });
    // Don't pass main background color to textkit. Will be rendered by the render package instead
    const backgroundColor = level === 0 ? null : instance.style.backgroundColor;
    const attributes = {
        font,
        color,
        opacity,
        fontSize,
        lineHeight,
        direction,
        verticalAlign,
        backgroundColor,
        indent: textIndent,
        characterSpacing: letterSpacing,
        strikeStyle: textDecorationStyle,
        underlineStyle: textDecorationStyle,
        underline: textDecoration === 'underline' ||
            textDecoration === 'underline line-through' ||
            textDecoration === 'line-through underline',
        strike: textDecoration === 'line-through' ||
            textDecoration === 'underline line-through' ||
            textDecoration === 'line-through underline',
        strikeColor: textDecorationColor || color,
        underlineColor: textDecorationColor || color,
        // @ts-expect-error allow this props access
        link: parentLink || instance.props?.src || instance.props?.href,
        align: textAlign || (direction === 'rtl' ? 'right' : 'left'),
    };
    for (let i = 0; i < instance.children.length; i += 1) {
        const child = instance.children[i];
        if (isImage$1(child) && isRasterImage(child)) {
            fragments.push({
                string: String.fromCharCode(0xfffc),
                attributes: {
                    ...attributes,
                    attachment: {
                        width: (child.style.width || fontSize),
                        height: (child.style.height || fontSize),
                        image: child.image.data,
                    },
                },
            });
        }
        else if (isTextInstance$2(child)) {
            fragments.push({
                string: transformText(child.value, textTransform),
                attributes,
            });
        }
        else if (child && !isImage$1(child)) {
            fragments.push(...getFragments(fontStore, child, attributes.link, level + 1));
        }
    }
    for (let i = 0; i < PREPROCESSORS.length; i += 1) {
        const preprocessor = PREPROCESSORS[i];
        fragments = preprocessor(fragments);
    }
    return fragments;
};
/**
 * Get textkit attributed string from text node
 *
 * @param fontStore - Font store
 * @param instance Node
 * @returns Attributed string
 */
const getAttributedString = (fontStore, instance) => {
    const fragments = getFragments(fontStore, instance);
    return fromFragments(fragments);
};

const engines = {
    bidi,
    linebreaker,
    justification,
    textDecoration,
    scriptItemizer,
    wordHyphenation,
    fontSubstitution,
};
const engine = layoutEngine(engines);
const getMaxLines = (node) => node.style?.maxLines;
const getTextOverflow = (node) => node.style?.textOverflow;
/**
 * Get layout container for specific text node
 *
 * @param {number} width
 * @param {number} height
 * @param {Object} node
 * @returns {Object} layout container
 */
const getContainer = (width, height, node) => {
    const maxLines = getMaxLines(node);
    const textOverflow = getTextOverflow(node);
    return {
        x: 0,
        y: 0,
        width,
        maxLines,
        height: height || Infinity,
        truncateMode: textOverflow,
    };
};
/**
 * Get text layout options for specific text node
 *
 * @param {Object} node instance
 * @returns {Object} layout options
 */
const getLayoutOptions = (fontStore, node) => ({
    hyphenationPenalty: node.props.hyphenationPenalty,
    shrinkWhitespaceFactor: { before: -0.5, after: -0.5 },
    hyphenationCallback: node.props.hyphenationCallback ||
        fontStore?.getHyphenationCallback() ||
        null,
});
/**
 * Get text lines for given node
 *
 * @param node - Node
 * @param width - Container width
 * @param height - Container height
 * @param fontStore - Font store
 * @returns Layout lines
 */
const layoutText = (node, width, height, fontStore) => {
    const attributedString = getAttributedString(fontStore, node);
    const container = getContainer(width, height, node);
    const options = getLayoutOptions(fontStore, node);
    const lines = engine(attributedString, container, options);
    return lines.reduce((acc, line) => [...acc, ...line], []);
};

const isSvg$2 = (node) => node.type === P.Svg;
const isText$4 = (node) => node.type === P.Text;
const shouldIterate = (node) => !isSvg$2(node) && !isText$4(node);
const shouldLayoutText = (node) => isText$4(node) && !node.lines;
/**
 * Performs text layout on text node if wasn't calculated before.
 * Text layout is usually performed on Yoga's layout process (via setMeasureFunc),
 * but we need to layout those nodes with fixed width and height.
 *
 * @param node
 * @returns Layout node
 */
const resolveTextLayout = (node, fontStore) => {
    if (shouldLayoutText(node)) {
        const width = node.box.width - (node.box.paddingRight + node.box.paddingLeft);
        const height = node.box.height - (node.box.paddingTop + node.box.paddingBottom);
        node.lines = layoutText(node, width, height, fontStore);
    }
    if (shouldIterate(node)) {
        if (!node.children)
            return node;
        const mapChild = (child) => resolveTextLayout(child, fontStore);
        const children = node.children.map(mapChild);
        return Object.assign({}, node, { children });
    }
    return node;
};

const BASE_INHERITABLE_PROPERTIES = [
    'color',
    'fontFamily',
    'fontSize',
    'fontStyle',
    'fontWeight',
    'letterSpacing',
    'opacity',
    'textDecoration',
    'textTransform',
    'lineHeight',
    'textAlign',
    'visibility',
    'wordSpacing',
];
const TEXT_INHERITABLE_PROPERTIES = [
    ...BASE_INHERITABLE_PROPERTIES,
    'backgroundColor',
];
const isType$2 = (type) => (node) => node.type === type;
const isSvg$1 = isType$2(P.Svg);
const isText$3 = isType$2(P.Text);
// Merge style values
const mergeValues = (styleName, value, inheritedValue) => {
    switch (styleName) {
        case 'textDecoration': {
            // merge not none and not false textDecoration values to one rule
            return [inheritedValue, value].filter((v) => v && v !== 'none').join(' ');
        }
        default:
            return value;
    }
};
// Merge inherited and node styles
const merge = (inheritedStyles, style) => {
    const mergedStyles = { ...inheritedStyles };
    Object.entries(style).forEach(([styleName, value]) => {
        mergedStyles[styleName] = mergeValues(styleName, value, inheritedStyles[styleName]);
    });
    return mergedStyles;
};
/**
 * Merges styles with node
 *
 * @param inheritedStyles - Style object
 * @returns Merge styles function
 */
const mergeStyles = (inheritedStyles) => (node) => {
    const style = merge(inheritedStyles, node.style || {});
    return Object.assign({}, node, { style });
};
/**
 * Inherit style values from the root to the leafs
 *
 * @param node - Document root
 * @returns Document root with inheritance
 *
 */
const resolveInheritance = (node) => {
    if (isSvg$1(node))
        return node;
    if (!('children' in node))
        return node;
    const inheritableProperties = isText$3(node)
        ? TEXT_INHERITABLE_PROPERTIES
        : BASE_INHERITABLE_PROPERTIES;
    const inheritStyles = pick(inheritableProperties, node.style || {});
    const resolveChild = compose(resolveInheritance, mergeStyles(inheritStyles));
    const children = node.children.map(resolveChild);
    return Object.assign({}, node, { children });
};

const getComputedMargin = (node, edge) => {
    const { yogaNode } = node;
    return yogaNode ? yogaNode.getComputedMargin(edge) : null;
};
/**
 * Get Yoga computed magins. Zero otherwise
 *
 * @param node
 * @returns Margins
 */
const getMargin = (node) => {
    const { style, box } = node;
    const marginTop = getComputedMargin(node, Yoga.Edge.Top) ||
        box?.marginTop ||
        style?.marginTop ||
        0;
    const marginRight = getComputedMargin(node, Yoga.Edge.Right) ||
        box?.marginRight ||
        style?.marginRight ||
        0;
    const marginBottom = getComputedMargin(node, Yoga.Edge.Bottom) ||
        box?.marginBottom ||
        style?.marginBottom ||
        0;
    const marginLeft = getComputedMargin(node, Yoga.Edge.Left) ||
        box?.marginLeft ||
        style?.marginLeft ||
        0;
    return { marginTop, marginRight, marginBottom, marginLeft };
};

/**
 * Get Yoga computed position. Zero otherwise
 *
 * @param node
 * @returns Position
 */
const getPosition = (node) => {
    const { yogaNode } = node;
    return {
        top: yogaNode?.getComputedTop() || 0,
        right: yogaNode?.getComputedRight() || 0,
        bottom: yogaNode?.getComputedBottom() || 0,
        left: yogaNode?.getComputedLeft() || 0,
    };
};

const DEFAULT_DIMENSION = {
    width: 0,
    height: 0,
};
/**
 * Get Yoga computed dimensions. Zero otherwise
 *
 * @param node
 * @returns Dimensions
 */
const getDimension = (node) => {
    const { yogaNode } = node;
    if (!yogaNode)
        return DEFAULT_DIMENSION;
    return {
        width: yogaNode.getComputedWidth(),
        height: yogaNode.getComputedHeight(),
    };
};

const getComputedBorder = (yogaNode, edge) => (yogaNode ? yogaNode.getComputedBorder(edge) : 0);
/**
 * Get Yoga computed border width. Zero otherwise
 *
 * @param node
 * @returns Border widths
 */
const getBorderWidth = (node) => {
    const { yogaNode } = node;
    return {
        borderTopWidth: getComputedBorder(yogaNode, Yoga.Edge.Top),
        borderRightWidth: getComputedBorder(yogaNode, Yoga.Edge.Right),
        borderBottomWidth: getComputedBorder(yogaNode, Yoga.Edge.Bottom),
        borderLeftWidth: getComputedBorder(yogaNode, Yoga.Edge.Left),
    };
};

/**
 * Set display attribute to node's Yoga instance
 *
 * @param value - Display
 * @returns Node instance wrapper
 */
const setDisplay = (value) => (node) => {
    const { yogaNode } = node;
    if (yogaNode) {
        yogaNode.setDisplay(value === 'none' ? Yoga.Display.None : Yoga.Display.Flex);
    }
    return node;
};

const OVERFLOW = {
    hidden: Yoga.Overflow.Hidden,
    scroll: Yoga.Overflow.Scroll,
};
/**
 * Set overflow attribute to node's Yoga instance
 *
 * @param value - Overflow value
 * @returns Node instance wrapper
 */
const setOverflow = (value) => (node) => {
    const { yogaNode } = node;
    if (!isNil(value) && yogaNode) {
        const overflow = OVERFLOW[value] || Yoga.Overflow.Visible;
        yogaNode.setOverflow(overflow);
    }
    return node;
};

const FLEX_WRAP = {
    wrap: Yoga.Wrap.Wrap,
    'wrap-reverse': Yoga.Wrap.WrapReverse,
};
/**
 * Set flex wrap attribute to node's Yoga instance
 *
 * @param value - Flex wrap value
 * @returns Node instance wrapper
 */
const setFlexWrap = (value) => (node) => {
    const { yogaNode } = node;
    if (yogaNode) {
        const flexWrap = FLEX_WRAP[value] || Yoga.Wrap.NoWrap;
        yogaNode.setFlexWrap(flexWrap);
    }
    return node;
};

/**
 * Set generic yoga attribute to node's Yoga instance, handing `auto`, edges and percentage cases
 *
 * @param attr - Property
 * @param edge - Edge
 * @returns Node instance wrapper
 */
const setYogaValue = (attr, edge) => (value) => (node) => {
    const { yogaNode } = node;
    if (!isNil(value) && yogaNode) {
        const hasEdge = !isNil(edge);
        const fixedMethod = `set${upperFirst(attr)}`;
        const autoMethod = `${fixedMethod}Auto`;
        const percentMethod = `${fixedMethod}Percent`;
        const percent = matchPercent(value);
        if (percent && !yogaNode[percentMethod]) {
            throw new Error(`You can't pass percentage values to ${attr} property`);
        }
        if (percent) {
            if (hasEdge) {
                yogaNode[percentMethod]?.(edge, percent.value);
            }
            else {
                yogaNode[percentMethod]?.(percent.value);
            }
        }
        else if (value === 'auto') {
            if (hasEdge) {
                yogaNode[autoMethod]?.(edge);
            }
            else {
                yogaNode[autoMethod]?.();
            }
        }
        else if (hasEdge) {
            yogaNode[fixedMethod]?.(edge, value);
        }
        else {
            yogaNode[fixedMethod]?.(value);
        }
    }
    return node;
};

/**
 * Set flex grow attribute to node's Yoga instance
 *
 * @param  value - Flex grow value
 * @returns Node instance wrapper
 */
const setFlexGrow = (value) => (node) => {
    return setYogaValue('flexGrow')(value || 0)(node);
};

/**
 * Set flex basis attribute to node's Yoga instance
 *
 * @param flex - Basis value
 * @param node - Node instance
 * @returns Node instance
 */
const setFlexBasis = setYogaValue('flexBasis');

const ALIGN = {
    'flex-start': Yoga.Align.FlexStart,
    center: Yoga.Align.Center,
    'flex-end': Yoga.Align.FlexEnd,
    stretch: Yoga.Align.Stretch,
    baseline: Yoga.Align.Baseline,
    'space-between': Yoga.Align.SpaceBetween,
    'space-around': Yoga.Align.SpaceAround,
    'space-evenly': Yoga.Align.SpaceEvenly,
};
/**
 * Set generic align attribute to node's Yoga instance
 *
 * @param attr - Specific align property
 * @param value - Specific align value
 * @param node - Node
 * @returns Node
 */
const setAlign = (attr) => (value) => (node) => {
    const { yogaNode } = node;
    const defaultValue = attr === 'items' ? Yoga.Align.Stretch : Yoga.Align.Auto;
    if (yogaNode) {
        const align = ALIGN[value] || defaultValue;
        yogaNode[`setAlign${upperFirst(attr)}`](align);
    }
    return node;
};

/**
 * Set align self attribute to node's Yoga instance
 *
 * @param align - Value
 * @param node - Node instance
 * @returns Node instance
 */
const setAlignSelf = setAlign('self');

/**
 * Set align items attribute to node's Yoga instance
 *
 * @param align - Value
 * @param node - Node instance
 * @returns Node instance
 */
const setAlignItems = setAlign('items');

/**
 * Set flex shrink attribute to node's Yoga instance
 *
 * @param value - Flex shrink value
 * @returns Node instance wrapper
 */
const setFlexShrink = (value) => (node) => {
    return setYogaValue('flexShrink')(value || 1)(node);
};

/**
 * Set aspect ratio attribute to node's Yoga instance
 *
 * @param value - Ratio
 * @returns Node instance
 */
const setAspectRatio = (value) => (node) => {
    const { yogaNode } = node;
    if (!isNil(value) && yogaNode) {
        yogaNode.setAspectRatio(value);
    }
    return node;
};

/**
 * Set align content attribute to node's Yoga instance
 *
 * @param align - Value
 * @param node - Instance
 * @returns Node instance
 */
const setAlignContent = setAlign('content');

const POSITION = {
    absolute: Yoga.PositionType.Absolute,
    relative: Yoga.PositionType.Relative,
    static: Yoga.PositionType.Static,
};
/**
 * Set position type attribute to node's Yoga instance
 *
 * @param value - Position position type
 * @returns Node instance
 */
const setPositionType = (value) => (node) => {
    const { yogaNode } = node;
    if (!isNil(value) && yogaNode) {
        yogaNode.setPositionType(POSITION[value]);
    }
    return node;
};

const FLEX_DIRECTIONS = {
    row: Yoga.FlexDirection.Row,
    'row-reverse': Yoga.FlexDirection.RowReverse,
    'column-reverse': Yoga.FlexDirection.ColumnReverse,
};
/**
 * Set flex direction attribute to node's Yoga instance
 *
 * @param value - Flex direction value
 * @returns Node instance wrapper
 */
const setFlexDirection = (value) => (node) => {
    const { yogaNode } = node;
    if (yogaNode) {
        const flexDirection = FLEX_DIRECTIONS[value] || Yoga.FlexDirection.Column;
        yogaNode.setFlexDirection(flexDirection);
    }
    return node;
};

const JUSTIFY_CONTENT = {
    center: Yoga.Justify.Center,
    'flex-end': Yoga.Justify.FlexEnd,
    'space-between': Yoga.Justify.SpaceBetween,
    'space-around': Yoga.Justify.SpaceAround,
    'space-evenly': Yoga.Justify.SpaceEvenly,
};
/**
 * Set justify content attribute to node's Yoga instance
 *
 * @param value - Justify content value
 * @returns Node instance wrapper
 */
const setJustifyContent = (value) => (node) => {
    const { yogaNode } = node;
    if (!isNil(value) && yogaNode) {
        const justifyContent = JUSTIFY_CONTENT[value] || Yoga.Justify.FlexStart;
        yogaNode.setJustifyContent(justifyContent);
    }
    return node;
};

/**
 * Set margin top attribute to node's Yoga instance
 *
 * @param margin - Margin top
 * @param node - Node instance
 * @returns Node instance
 */
const setMarginTop = setYogaValue('margin', Yoga.Edge.Top);
/**
 * Set margin right attribute to node's Yoga instance
 *
 * @param margin - Margin right
 * @param node - Node instance
 * @returns Node instance
 */
const setMarginRight = setYogaValue('margin', Yoga.Edge.Right);
/**
 * Set margin bottom attribute to node's Yoga instance
 *
 * @param margin - Margin bottom
 * @param node - Node instance
 * @returns Node instance
 */
const setMarginBottom = setYogaValue('margin', Yoga.Edge.Bottom);
/**
 * Set margin left attribute to node's Yoga instance
 *
 * @param margin - Margin left
 * @param node - Node instance
 * @returns Node instance
 */
const setMarginLeft = setYogaValue('margin', Yoga.Edge.Left);

/**
 * Set padding top attribute to node's Yoga instance
 *
 * @param padding - Padding top
 * @param node - Node instance
 * @returns Node instance
 */
const setPaddingTop = setYogaValue('padding', Yoga.Edge.Top);
/**
 * Set padding right attribute to node's Yoga instance
 *
 * @param padding - Padding right
 * @param node - Node instance
 * @returns Node instance
 */
const setPaddingRight = setYogaValue('padding', Yoga.Edge.Right);
/**
 * Set padding bottom attribute to node's Yoga instance
 *
 * @param padding - Padding bottom
 * @param node Node instance
 * @returns Node instance
 */
const setPaddingBottom = setYogaValue('padding', Yoga.Edge.Bottom);
/**
 * Set padding left attribute to node's Yoga instance
 *
 * @param padding - Padding left
 * @param node - Node instance
 * @returns Node instance
 */
const setPaddingLeft = setYogaValue('padding', Yoga.Edge.Left);

/**
 * Set border top attribute to node's Yoga instance
 *
 * @param border - Border top width
 * @param node - Node instance
 * @returns Node instance
 */
const setBorderTop = setYogaValue('border', Yoga.Edge.Top);
/**
 * Set border right attribute to node's Yoga instance
 *
 * @param border - Border right width
 * @param node - Node instance
 * @returns Node instance
 */
const setBorderRight = setYogaValue('border', Yoga.Edge.Right);
/**
 * Set border bottom attribute to node's Yoga instance
 *
 * @param border - Border bottom width
 * @param node - Node instance
 * @returns Node instance
 */
const setBorderBottom = setYogaValue('border', Yoga.Edge.Bottom);
/**
 * Set border left attribute to node's Yoga instance
 *
 * @param border - Border left width
 * @param node - Node instance
 * @returns Node instance
 */
const setBorderLeft = setYogaValue('border', Yoga.Edge.Left);

/**
 * Set position top attribute to node's Yoga instance
 *
 * @param position - Position top
 * @param node - Node instance
 * @returns Node instance
 */
const setPositionTop = setYogaValue('position', Yoga.Edge.Top);
/**
 * Set position right attribute to node's Yoga instance
 *
 * @param position - Position right
 * @param node - Node instance
 * @returns Node instance
 */
const setPositionRight = setYogaValue('position', Yoga.Edge.Right);
/**
 * Set position bottom attribute to node's Yoga instance
 *
 * @param position - Position bottom
 * @param node - Node instance
 * @returns Node instance
 */
const setPositionBottom = setYogaValue('position', Yoga.Edge.Bottom);
/**
 * Set position left attribute to node's Yoga instance
 *
 * @param position - Position left
 * @param node - Node instance
 * @returns Node instance
 */
const setPositionLeft = setYogaValue('position', Yoga.Edge.Left);

/**
 * Set width to node's Yoga instance
 *
 * @param width - Width
 * @param node - Node instance
 * @returns Node instance
 */
const setWidth = setYogaValue('width');
/**
 * Set min width to node's Yoga instance
 *
 * @param min - Width
 * @param node - Node instance
 * @returns Node instance
 */
const setMinWidth = setYogaValue('minWidth');
/**
 * Set max width to node's Yoga instance
 *
 * @param max - Width
 * @param node - Node instance
 * @returns Node instance
 */
const setMaxWidth = setYogaValue('maxWidth');
/**
 * Set height to node's Yoga instance
 *
 * @param height - Height
 * @param node - Node instance
 * @returns Node instance
 */
const setHeight = setYogaValue('height');
/**
 * Set min height to node's Yoga instance
 *
 * @param min - Height
 * @param node - Node instance
 * @returns Node instance
 */
const setMinHeight = setYogaValue('minHeight');
/**
 * Set max height to node's Yoga instance
 *
 * @param max - Height
 * @param node - Node instance
 * @returns Node instance
 */
const setMaxHeight = setYogaValue('maxHeight');

/**
 * Set rowGap value to node's Yoga instance
 *
 * @param value - Gap value
 * @returns Node instance wrapper
 */
const setRowGap = setYogaValue('gap', Yoga.Gutter.Row);
/**
 * Set columnGap value to node's Yoga instance
 *
 * @param value - Gap value
 * @returns Node instance wrapper
 */
const setColumnGap = setYogaValue('gap', Yoga.Gutter.Column);

const getAspectRatio = (viewbox) => {
    if (!viewbox)
        return null;
    if (typeof viewbox === 'string')
        return null;
    return (viewbox.maxX - viewbox.minX) / (viewbox.maxY - viewbox.minY);
};
/**
 * Yoga svg measure function
 *
 * @param page
 * @param node
 * @returns Measure svg
 */
const measureCanvas$1 = (page, node) => (width, widthMode, height, heightMode) => {
    const aspectRatio = getAspectRatio(node.props.viewBox) || 1;
    if (widthMode === Yoga.MeasureMode.Exactly ||
        widthMode === Yoga.MeasureMode.AtMost) {
        return { width, height: width / aspectRatio };
    }
    if (heightMode === Yoga.MeasureMode.Exactly) {
        return { width: height * aspectRatio };
    }
    return {};
};

/**
 * Get lines width (if any)
 *
 * @param node
 * @returns Lines width
 */
const linesWidth = (node) => {
    if (!node.lines)
        return 0;
    return Math.max(0, ...node.lines.map((line) => line.xAdvance));
};

/**
 * Get lines height (if any)
 *
 * @param node
 * @returns Lines height
 */
const linesHeight = (node) => {
    if (!node.lines)
        return -1;
    return node.lines.reduce((acc, line) => acc + line.box.height, 0);
};

const ALIGNMENT_FACTORS = { center: 0.5, right: 1 };
/**
 * Yoga text measure function
 *
 * @param page
 * @param node
 * @param fontStore
 * @returns {MeasureText} measure text function
 */
const measureText = (page, node, fontStore) => (width, widthMode, height) => {
    if (widthMode === Yoga.MeasureMode.Exactly) {
        if (!node.lines)
            node.lines = layoutText(node, width, height, fontStore);
        return { height: linesHeight(node), width };
    }
    if (widthMode === Yoga.MeasureMode.AtMost) {
        const alignFactor = ALIGNMENT_FACTORS[node.style?.textAlign] || 0;
        if (!node.lines) {
            node.lines = layoutText(node, width, height, fontStore);
            node.alignOffset = (width - linesWidth(node)) * alignFactor; // Compensate align in variable width containers
        }
        return {
            height: linesHeight(node),
            width: Math.min(width, linesWidth(node)),
        };
    }
    return {};
};

/**
 * Get image ratio
 *
 * @param node - Image node
 * @returns Image ratio
 */
const getRatio = (node) => {
    return node.image?.data ? node.image.width / node.image.height : 1;
};

/**
 * Checks if page has auto height
 *
 * @param page
 * @returns Is page height auto
 */
const isHeightAuto = (page) => isNil(page.box?.height);

const SAFETY_HEIGHT$1 = 10;
/**
 * Yoga image measure function
 *
 * @param page - Page
 * @param node - Node
 * @returns Measure image
 */
const measureImage = (page, node) => (width, widthMode, height, heightMode) => {
    const imageRatio = getRatio(node);
    const imageMargin = getMargin(node);
    const pagePadding = getPadding(page);
    // TODO: Check image percentage margins
    const pageArea = isHeightAuto(page)
        ? Infinity
        : (page.box?.height || 0) -
            pagePadding.paddingTop -
            pagePadding.paddingBottom -
            imageMargin.marginTop -
            imageMargin.marginBottom -
            SAFETY_HEIGHT$1;
    // Skip measure if image data not present yet
    if (!node.image)
        return { width: 0, height: 0 };
    if (widthMode === Yoga.MeasureMode.Exactly &&
        heightMode === Yoga.MeasureMode.Undefined) {
        const scaledHeight = width / imageRatio;
        return { height: Math.min(pageArea, scaledHeight) };
    }
    if (heightMode === Yoga.MeasureMode.Exactly &&
        (widthMode === Yoga.MeasureMode.AtMost ||
            widthMode === Yoga.MeasureMode.Undefined)) {
        return { width: Math.min(height * imageRatio, width) };
    }
    if (widthMode === Yoga.MeasureMode.Exactly &&
        heightMode === Yoga.MeasureMode.AtMost) {
        const scaledHeight = width / imageRatio;
        return { height: Math.min(height, pageArea, scaledHeight) };
    }
    if (widthMode === Yoga.MeasureMode.AtMost &&
        heightMode === Yoga.MeasureMode.AtMost) {
        if (imageRatio > 1) {
            return {
                width,
                height: Math.min(width / imageRatio, height),
            };
        }
        return {
            height,
            width: Math.min(height * imageRatio, width),
        };
    }
    return { height, width };
};

const SAFETY_HEIGHT = 10;
const getMax = (values) => Math.max(-Infinity, ...values);
/**
 * Helper object to predict canvas size
 * TODO: Implement remaining functions (as close as possible);
 */
const measureCtx = () => {
    const ctx = {};
    const points = [];
    const nil = () => ctx;
    const addPoint = (x, y) => points.push([x, y]);
    const moveTo = (x, y) => {
        addPoint(x, y);
        return ctx;
    };
    const rect = (x, y, w, h) => {
        addPoint(x, y);
        addPoint(x + w, y);
        addPoint(x, y + h);
        addPoint(x + w, y + h);
        return ctx;
    };
    const ellipse = (x, y, rx, ry) => {
        ry = ry || rx;
        addPoint(x - rx, y - ry);
        addPoint(x + rx, y - ry);
        addPoint(x + rx, y + ry);
        addPoint(x - rx, y + ry);
        return ctx;
    };
    const polygon = (...pts) => {
        points.push(...pts);
        return ctx;
    };
    // Change dimensions
    ctx.rect = rect;
    ctx.moveTo = moveTo;
    ctx.lineTo = moveTo;
    ctx.circle = ellipse;
    ctx.polygon = polygon;
    ctx.ellipse = ellipse;
    ctx.roundedRect = rect;
    // To be implemented
    ctx.text = nil;
    ctx.path = nil;
    ctx.lineWidth = nil;
    ctx.bezierCurveTo = nil;
    ctx.quadraticCurveTo = nil;
    ctx.scale = nil;
    ctx.rotate = nil;
    ctx.translate = nil;
    // These don't change dimensions
    ctx.dash = nil;
    ctx.clip = nil;
    ctx.save = nil;
    ctx.fill = nil;
    ctx.font = nil;
    ctx.stroke = nil;
    ctx.lineCap = nil;
    ctx.opacity = nil;
    ctx.restore = nil;
    ctx.lineJoin = nil;
    ctx.fontSize = nil;
    ctx.fillColor = nil;
    ctx.miterLimit = nil;
    ctx.strokeColor = nil;
    ctx.fillOpacity = nil;
    ctx.strokeOpacity = nil;
    ctx.linearGradient = nil;
    ctx.radialGradient = nil;
    ctx.getWidth = () => getMax(points.map((p) => p[0]));
    ctx.getHeight = () => getMax(points.map((p) => p[1]));
    return ctx;
};
/**
 * @typedef {Function} MeasureCanvas
 * @returns {{ width: number, height: number }} canvas width and height
 */
/**
 * Yoga canvas measure function
 *
 * @param {Object} page
 * @param {Object} node
 * @returns {MeasureCanvas} measure canvas
 */
const measureCanvas = (page, node) => () => {
    const imageMargin = getMargin(node);
    const pagePadding = getPadding(page);
    // TODO: Check image percentage margins
    const pageArea = isHeightAuto(page)
        ? Infinity
        : (page.box?.height || 0) -
            pagePadding.paddingTop -
            pagePadding.paddingBottom -
            imageMargin.marginTop -
            imageMargin.marginBottom -
            SAFETY_HEIGHT;
    const ctx = measureCtx();
    node.props.paint(ctx);
    const width = ctx.getWidth();
    const height = Math.min(pageArea, ctx.getHeight());
    return { width, height };
};

const isType$1 = (type) => (node) => node.type === type;
const isSvg = isType$1(P.Svg);
const isText$2 = isType$1(P.Text);
const isNote = isType$1(P.Note);
const isPage = isType$1(P.Page);
const isImage = isType$1(P.Image);
const isCanvas = isType$1(P.Canvas);
const isTextInstance$1 = isType$1(P.TextInstance);
const setNodeHeight = (node) => {
    const value = isPage(node) ? node.box?.height : node.style?.height;
    return setHeight(value);
};
/**
 * Set styles valeus into yoga node before layout calculation
 *
 * @param node
 */
const setYogaValues = (node) => {
    compose(setNodeHeight(node), setWidth(node.style.width), setMinWidth(node.style.minWidth), setMaxWidth(node.style.maxWidth), setMinHeight(node.style.minHeight), setMaxHeight(node.style.maxHeight), setMarginTop(node.style.marginTop), setMarginRight(node.style.marginRight), setMarginBottom(node.style.marginBottom), setMarginLeft(node.style.marginLeft), setPaddingTop(node.style.paddingTop), setPaddingRight(node.style.paddingRight), setPaddingBottom(node.style.paddingBottom), setPaddingLeft(node.style.paddingLeft), setPositionType(node.style.position), setPositionTop(node.style.top), setPositionRight(node.style.right), setPositionBottom(node.style.bottom), setPositionLeft(node.style.left), setBorderTop(node.style.borderTopWidth), setBorderRight(node.style.borderRightWidth), setBorderBottom(node.style.borderBottomWidth), setBorderLeft(node.style.borderLeftWidth), setDisplay(node.style.display), setFlexDirection(node.style.flexDirection), setAlignSelf(node.style.alignSelf), setAlignContent(node.style.alignContent), setAlignItems(node.style.alignItems), setJustifyContent(node.style.justifyContent), setFlexWrap(node.style.flexWrap), setOverflow(node.style.overflow), setAspectRatio(node.style.aspectRatio), setFlexBasis(node.style.flexBasis), setFlexGrow(node.style.flexGrow), setFlexShrink(node.style.flexShrink), setRowGap(node.style.rowGap), setColumnGap(node.style.columnGap))(node);
};
/**
 * Inserts child into parent' yoga node
 *
 * @param parent parent
 * @returns Insert yoga nodes
 */
const insertYogaNodes = (parent) => (child) => {
    parent.insertChild(child.yogaNode, parent.getChildCount());
    return child;
};
const setMeasureFunc = (node, page, fontStore) => {
    const { yogaNode } = node;
    if (isText$2(node)) {
        yogaNode.setMeasureFunc(measureText(page, node, fontStore));
    }
    if (isImage(node)) {
        yogaNode.setMeasureFunc(measureImage(page, node));
    }
    if (isCanvas(node)) {
        yogaNode.setMeasureFunc(measureCanvas(page, node));
    }
    if (isSvg(node)) {
        yogaNode.setMeasureFunc(measureCanvas$1(page, node));
    }
    return node;
};
const isLayoutElement = (node) => !isText$2(node) && !isNote(node) && !isSvg(node);
/**
 * @typedef {Function} CreateYogaNodes
 * @param {Object} node
 * @returns {Object} node with appended yoga node
 */
/**
 * Creates and add yoga node to document tree
 * Handles measure function for text and image nodes
 *
 * @returns Create yoga nodes
 */
const createYogaNodes = (page, fontStore, yoga) => (node) => {
    const yogaNode = yoga.node.create();
    const result = Object.assign({}, node, { yogaNode });
    setYogaValues(result);
    if (isLayoutElement(node) && node.children) {
        const resolveChild = compose(insertYogaNodes(yogaNode), createYogaNodes(page, fontStore, yoga));
        result.children = node.children.map(resolveChild);
    }
    setMeasureFunc(result, page, fontStore);
    return result;
};
/**
 * Performs yoga calculation
 *
 * @param page - Page node
 * @returns Page node
 */
const calculateLayout = (page) => {
    page.yogaNode.calculateLayout();
    return page;
};
/**
 * Saves Yoga layout result into 'box' attribute of node
 *
 * @param node
 * @returns Node with box data
 */
const persistDimensions = (node) => {
    if (isTextInstance$1(node))
        return node;
    const box = Object.assign(getPadding(node), getMargin(node), getBorderWidth(node), getPosition(node), getDimension(node));
    const newNode = Object.assign({}, node, { box });
    if (!node.children)
        return newNode;
    const children = node.children.map(persistDimensions);
    return Object.assign({}, newNode, { children });
};
/**
 * Removes yoga node from document tree
 *
 * @param node
 * @returns Node without yoga node
 */
const destroyYogaNodes = (node) => {
    const newNode = Object.assign({}, node);
    delete newNode.yogaNode;
    if (!node.children)
        return newNode;
    const children = node.children.map(destroyYogaNodes);
    return Object.assign({}, newNode, { children });
};
/**
 * Free yoga node from document tree
 *
 * @param node
 * @returns Node without yoga node
 */
const freeYogaNodes = (node) => {
    if (node.yogaNode)
        node.yogaNode.freeRecursive();
    return node;
};
/**
 * Calculates page object layout using Yoga.
 * Takes node values from 'box' and 'style' attributes, and persist them back into 'box'
 * Destroy yoga values at the end.
 *
 * @param page - Object
 * @returns Page object with correct 'box' layout attributes
 */
const resolvePageDimensions = (page, fontStore, yoga) => {
    if (isNil(page))
        return null;
    return compose(destroyYogaNodes, freeYogaNodes, persistDimensions, calculateLayout, createYogaNodes(page, fontStore, yoga))(page);
};
/**
 * Calculates root object layout using Yoga.
 *
 * @param node - Root object
 * @param fontStore - Font store
 * @returns Root object with correct 'box' layout attributes
 */
const resolveDimensions = (node, fontStore) => {
    if (!node.children)
        return node;
    const resolveChild = (child) => resolvePageDimensions(child, fontStore, node.yoga);
    const children = node.children.map(resolveChild);
    return Object.assign({}, node, { children });
};

const isText$1 = (node) => node.type === P.Text;
// Prevent splitting elements by low decimal numbers
const SAFETY_THRESHOLD = 0.001;
const assingChildren = (children, node) => Object.assign({}, node, { children });
const getTop = (node) => node.box?.top || 0;
const allFixed = (nodes) => nodes.every(isFixed);
const isDynamic = (node) => node.props && 'render' in node.props;
const relayoutPage = compose(resolveTextLayout, resolvePageDimensions, resolveInheritance, resolvePageStyles);
const warnUnavailableSpace = (node) => {
    console.warn(`Node of type ${node.type} can't wrap between pages and it's bigger than available page height`);
};
const splitNodes = (height, contentArea, nodes) => {
    const currentChildren = [];
    const nextChildren = [];
    for (let i = 0; i < nodes.length; i += 1) {
        const child = nodes[i];
        const futureNodes = nodes.slice(i + 1);
        const futureFixedNodes = futureNodes.filter(isFixed);
        const nodeTop = getTop(child);
        const nodeHeight = child.box.height;
        const isOutside = height <= nodeTop;
        const shouldBreak$1 = shouldBreak(child, futureNodes, height, currentChildren);
        const shouldSplit = height + SAFETY_THRESHOLD < nodeTop + nodeHeight;
        const canWrap = getWrap(child);
        const fitsInsidePage = nodeHeight <= contentArea;
        if (isFixed(child)) {
            nextChildren.push(child);
            currentChildren.push(child);
            continue;
        }
        if (isOutside) {
            const box = Object.assign({}, child.box, { top: child.box.top - height });
            const next = Object.assign({}, child, { box });
            nextChildren.push(next);
            continue;
        }
        if (!fitsInsidePage && !canWrap) {
            currentChildren.push(child);
            nextChildren.push(...futureNodes);
            warnUnavailableSpace(child);
            break;
        }
        if (shouldBreak$1) {
            const box = Object.assign({}, child.box, { top: child.box.top - height });
            const props = Object.assign({}, child.props, {
                wrap: true,
                break: false,
            });
            const next = Object.assign({}, child, { box, props });
            currentChildren.push(...futureFixedNodes);
            nextChildren.push(next, ...futureNodes);
            break;
        }
        if (shouldSplit) {
            const [currentChild, nextChild] = split(child, height, contentArea);
            // All children are moved to the next page, it doesn't make sense to show the parent on the current page
            if (child.children.length > 0 && currentChild.children.length === 0) {
                // But if the current page is empty then we can just include the parent on the current page
                if (currentChildren.length === 0) {
                    currentChildren.push(child, ...futureFixedNodes);
                    nextChildren.push(...futureNodes);
                }
                else {
                    const box = Object.assign({}, child.box, {
                        top: child.box.top - height,
                    });
                    const next = Object.assign({}, child, { box });
                    currentChildren.push(...futureFixedNodes);
                    nextChildren.push(next, ...futureNodes);
                }
                break;
            }
            if (currentChild)
                currentChildren.push(currentChild);
            if (nextChild)
                nextChildren.push(nextChild);
            continue;
        }
        currentChildren.push(child);
    }
    return [currentChildren, nextChildren];
};
const splitChildren = (height, contentArea, node) => {
    const children = node.children || [];
    const availableHeight = height - getTop(node);
    return splitNodes(availableHeight, contentArea, children);
};
const splitView = (node, height, contentArea) => {
    const [currentNode, nextNode] = splitNode(node, height);
    const [currentChilds, nextChildren] = splitChildren(height, contentArea, node);
    return [
        assingChildren(currentChilds, currentNode),
        assingChildren(nextChildren, nextNode),
    ];
};
const split = (node, height, contentArea) => isText$1(node) ? splitText(node, height) : splitView(node, height, contentArea);
const shouldResolveDynamicNodes = (node) => {
    const children = node.children || [];
    return isDynamic(node) || children.some(shouldResolveDynamicNodes);
};
const resolveDynamicNodes = (props, node) => {
    const isNodeDynamic = isDynamic(node);
    // Call render prop on dynamic nodes and append result to children
    const resolveChildren = (children = []) => {
        if (isNodeDynamic) {
            const res = node.props.render(props);
            return (createInstances(res)
                .filter(Boolean)
                // @ts-expect-error rework dynamic nodes. conflicting types
                .map((n) => resolveDynamicNodes(props, n)));
        }
        return children.map((c) => resolveDynamicNodes(props, c));
    };
    // We reset dynamic text box so it can be computed again later on
    const resetHeight = isNodeDynamic && isText$1(node);
    const box = resetHeight ? { ...node.box, height: 0 } : node.box;
    const children = resolveChildren(node.children);
    // @ts-expect-error handle text here specifically
    const lines = isNodeDynamic ? null : node.lines;
    return Object.assign({}, node, { box, lines, children });
};
const resolveDynamicPage = (props, page, fontStore, yoga) => {
    if (shouldResolveDynamicNodes(page)) {
        const resolvedPage = resolveDynamicNodes(props, page);
        return relayoutPage(resolvedPage, fontStore, yoga);
    }
    return page;
};
const splitPage = (page, pageNumber, fontStore, yoga) => {
    const wrapArea = getWrapArea(page);
    const contentArea = getContentArea(page);
    const dynamicPage = resolveDynamicPage({ pageNumber }, page, fontStore, yoga);
    const height = page.style.height;
    const [currentChilds, nextChilds] = splitNodes(wrapArea, contentArea, dynamicPage.children);
    const relayout = (node) => 
    // @ts-expect-error rework pagination
    relayoutPage(node, fontStore, yoga);
    const currentBox = { ...page.box, height };
    const currentPage = relayout(Object.assign({}, page, { box: currentBox, children: currentChilds }));
    if (nextChilds.length === 0 || allFixed(nextChilds))
        return [currentPage, null];
    const nextBox = omit('height', page.box);
    const nextProps = omit('bookmark', page.props);
    const nextPage = relayout(Object.assign({}, page, {
        props: nextProps,
        box: nextBox,
        children: nextChilds,
    }));
    return [currentPage, nextPage];
};
const resolvePageIndices = (fontStore, yoga, page, pageNumber, pages) => {
    const totalPages = pages.length;
    const props = {
        totalPages,
        pageNumber: pageNumber + 1,
        subPageNumber: page.subPageNumber + 1,
        subPageTotalPages: page.subPageTotalPages,
    };
    return resolveDynamicPage(props, page, fontStore, yoga);
};
const assocSubPageData = (subpages) => {
    return subpages.map((page, i) => ({
        ...page,
        subPageNumber: i,
        subPageTotalPages: subpages.length,
    }));
};
const dissocSubPageData = (page) => {
    return omit(['subPageNumber', 'subPageTotalPages'], page);
};
const paginate = (page, pageNumber, fontStore, yoga) => {
    if (!page)
        return [];
    if (page.props?.wrap === false)
        return [page];
    let splittedPage = splitPage(page, pageNumber, fontStore, yoga);
    const pages = [splittedPage[0]];
    let nextPage = splittedPage[1];
    while (nextPage !== null) {
        splittedPage = splitPage(nextPage, pageNumber + pages.length, fontStore, yoga);
        pages.push(splittedPage[0]);
        nextPage = splittedPage[1];
    }
    return pages;
};
/**
 * Performs pagination. This is the step responsible of breaking the whole document
 * into pages following pagiation rules, such as `fixed`, `break` and dynamic nodes.
 *
 * @param root - Document node
 * @param fontStore - Font store
 * @returns Layout node
 */
const resolvePagination = (root, fontStore) => {
    let pages = [];
    let pageNumber = 1;
    for (let i = 0; i < root.children.length; i += 1) {
        const page = root.children[i];
        let subpages = paginate(page, pageNumber, fontStore, root.yoga);
        subpages = assocSubPageData(subpages);
        pageNumber += subpages.length;
        pages = pages.concat(subpages);
    }
    pages = pages.map((...args) => dissocSubPageData(resolvePageIndices(fontStore, root.yoga, ...args)));
    return assingChildren(pages, root);
};

/**
 * Translates page percentage horizontal paddings in fixed ones
 *
 * @param container - Page container
 * @returns Resolve page horizontal padding
 */
const resolvePageHorizontalPadding = (container) => (value) => {
    const match = matchPercent(value);
    const width = container.width;
    return match ? match.percent * width : value;
};
/**
 * Translates page percentage vertical paddings in fixed ones
 *
 * @param container - Page container
 * @returns Resolve page vertical padding
 */
const resolvePageVerticalPadding = (container) => (value) => {
    const match = matchPercent(value);
    const height = container.height;
    return match ? match.percent * height : value;
};
/**
 * Translates page percentage paddings in fixed ones
 *
 * @param page
 * @returns Page with fixed paddings
 */
const resolvePagePaddings = (page) => {
    const container = page.style;
    const style = evolve({
        paddingTop: resolvePageVerticalPadding(container),
        paddingLeft: resolvePageHorizontalPadding(container),
        paddingRight: resolvePageHorizontalPadding(container),
        paddingBottom: resolvePageVerticalPadding(container),
    }, page.style);
    return Object.assign({}, page, { style });
};
/**
 * Translates all pages percentage paddings in fixed ones
 * This has to be computed from pages calculated size and not by Yoga
 * because at this point we didn't performed pagination yet.
 *
 * @param root - Document root
 * @returns Document root with translated page paddings
 */
const resolvePagesPaddings = (root) => {
    if (!root.children)
        return root;
    const children = root.children.map(resolvePagePaddings);
    return Object.assign({}, root, { children });
};

const resolveRadius = (box) => (value) => {
    if (!value)
        return undefined;
    const match = matchPercent(value);
    return match ? match.percent * Math.min(box.width, box.height) : value;
};
/**
 * Transforms percent border radius into fixed values
 *
 * @param node
 * @returns Node
 */
const resolvePercentRadius = (node) => {
    const style = evolve({
        borderTopLeftRadius: resolveRadius(node.box),
        borderTopRightRadius: resolveRadius(node.box),
        borderBottomRightRadius: resolveRadius(node.box),
        borderBottomLeftRadius: resolveRadius(node.box),
    }, node.style || {});
    const newNode = Object.assign({}, node, { style });
    if (!node.children)
        return newNode;
    const children = node.children.map(resolvePercentRadius);
    return Object.assign({}, newNode, { children });
};

/**
 * Transform percent height into fixed
 *
 * @param height
 * @returns Height
 */
const transformHeight = (pageArea, height) => {
    const match = matchPercent(height);
    return match ? match.percent * pageArea : height;
};
/**
 * Get page area (height minus paddings)
 *
 * @param page
 * @returns Page area
 */
const getPageArea = (page) => {
    const pageHeight = page.style.height;
    const pagePaddingTop = (page.style?.paddingTop || 0);
    const pagePaddingBottom = (page.style?.paddingBottom || 0);
    return pageHeight - pagePaddingTop - pagePaddingBottom;
};
/**
 * Transform node percent height to fixed
 *
 * @param page
 * @param node
 * @returns Transformed node
 */
const resolveNodePercentHeight = (page, node) => {
    if (isNil(page.style?.height))
        return node;
    if (isNil(node.style?.height))
        return node;
    const pageArea = getPageArea(page);
    const height = transformHeight(pageArea, node.style.height);
    const style = Object.assign({}, node.style, { height });
    return Object.assign({}, node, { style });
};
/**
 * Transform page immediate children with percent height to fixed
 *
 * @param page
 * @returns Transformed page
 */
const resolvePagePercentHeight = (page) => {
    if (!page.children)
        return page;
    const resolveChild = (child) => resolveNodePercentHeight(page, child);
    const children = page.children.map(resolveChild);
    return Object.assign({}, page, { children });
};
/**
 * Transform all page immediate children with percent height to fixed.
 * This is needed for computing correct dimensions on pre-pagination layout.
 *
 * @param root - Document root
 * @returns Transformed document root
 */
const resolvePercentHeight = (root) => {
    if (!root.children)
        return root;
    const children = root.children.map(resolvePagePercentHeight);
    return Object.assign({}, root, { children });
};

const isType = (type) => (node) => node.type === type;
const isLink = isType(P.Link);
const isText = isType(P.Text);
const isTextInstance = isType(P.TextInstance);
/**
 * Checks if node has render prop
 *
 * @param node
 * @returns Has render prop?
 */
const hasRenderProp = (node) => 'render' in node.props;
/**
 * Checks if node is text type (Text or TextInstance)
 *
 * @param node
 * @returns Are all children text instances?
 */
const isTextType = (node) => isText(node) || isTextInstance(node);
/**
 * Checks if is tet link that needs to be wrapped in Text
 *
 * @param node
 * @returns Are all children text instances?
 */
const isTextLink = (node) => {
    const children = node.children || [];
    // Text string inside a Link
    if (children.every(isTextInstance))
        return true;
    // Text node inside a Link
    if (children.every(isText))
        return false;
    return children.every(isTextType);
};
/**
 * Wraps node children inside Text node
 *
 * @param node
 * @returns Node with intermediate Text child
 */
const wrapText = (node) => {
    const textElement = {
        type: P.Text,
        props: {},
        style: {},
        box: {},
        children: node.children,
    };
    return Object.assign({}, node, { children: [textElement] });
};
const transformLink = (node) => {
    if (!isLink(node))
        return node;
    // If has render prop substitute the instance by a Text, that will
    // ultimately render the inline Link via the textkit PDF renderer.
    if (hasRenderProp(node))
        return Object.assign({}, node, { type: P.Text });
    // If is a text link (either contains Text or TextInstance), wrap it
    // inside a Text element so styles are applied correctly
    if (isTextLink(node))
        return wrapText(node);
    return node;
};
/**
 * Transforms Link layout to correctly render text and dynamic rendered links
 *
 * @param node
 * @returns Node with link substitution
 */
const resolveLinkSubstitution = (node) => {
    if (!node.children)
        return node;
    const resolveChild = compose(transformLink, resolveLinkSubstitution);
    const children = node.children.map(resolveChild);
    return Object.assign({}, node, { children });
};

const layout = asyncCompose(resolveZIndex, resolveOrigin, resolveAssets, resolvePagination, resolveTextLayout, resolvePercentRadius, resolveDimensions, resolveSvg, resolveAssets, resolveInheritance, resolvePercentHeight, resolvePagesPaddings, resolveStyles, resolveLinkSubstitution, resolveBookmarks, resolvePageSizes, resolveYoga);

export { layout as default };