All files / yaml / _loader_state.ts

90.34% Branches 421/466
85.98% Lines 1159/1348
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
 
 
 
 
 
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
x13
 
x13
 
x13
 
x13
x13
x13
x13
 
x13
x13
x13
 
x13
 
x13
x13
x13
x13
x13
x13
 
 
 
 
 
 
 
 
 
 
x13
x52
x52
x39
x13
 
x13
x52
x52
x52
x52
x52
x52
x52
x52
x52
x52
x52
x52
x52
x52
x52
x52
x52
x39
x13
 
 
 
 
x13
 
x40
 
 
x43
 
 
x40
 
x41
x40
 
 
 
 
x13
 
x32
x46
x32
 
 
 
 
x13
 
x19
 
 
 
x20
x20
x20
 
x19
 
x13
x13
x13
 
x67
 
x67
x67
x67
x67
 
x67
x200
 
 
 
 
 
x200
 
x67
x137
 
 
 
 
 
x137
 
x67
x67
x67
x67
x67
 
x67
x67
x67
x67
x67
 
x67
x67
x67
x67
x67
 
x13
x13
x161
x161
x161
x161
x161
x161
x161
x161
x161
 
x161
x161
x161
x161
x161
x161
x161
x13
 
x13
x13
x13
x13
x13
x13
x13
x13
x161
x161
x161
x161
x161
x161
x161
 
x161
x161
 
x13
x1671
x1671
x2004
x2004
x1671
 
x13
x1183
x1183
x2213
x1183
x1238
x1238
x1183
 
x13
x614
x614
x1511
x1511
x1511
x614
 
x13
x18863
x18863
x13
x4334
x4334
x4334
 
x13
x67
x67
x67
x67
x67
 
x67
x67
 
x13
x17
x17
x17
 
x13
x24
x25
x25
 
x25
 
x24
x25
x25
 
x25
 
x33
x24
x25
x25
 
x25
 
x32
x32
x24
x25
x25
 
x25
 
 
x24
x24
x26
x26
 
x26
x24
x13
x19
x20
x20
 
x20
 
x24
x24
 
x19
x20
x20
 
x20
 
x19
x20
x20
 
x20
 
x19
x20
x20
 
x20
 
x21
x19
x13
x411
x774
 
x774
x789
x789
x789
x789
x789
x842
x842
x842
x842
x842
x843
x843
 
x843
x842
x774
x1123
x1123
 
x1135
x1135
x411
x13
x247
 
x247
x247
x247
 
x247
x248
x248
 
x247
 
x247
x535
x723
x723
 
x912
 
x812
x817
x817
 
x907
x907
 
 
 
 
 
 
 
 
 
x1169
x1169
x1169
x1169
 
x1169
 
 
 
 
 
 
x916
x916
x535
 
x247
x275
x275
x275
x275
x275
x275
x449
x247
x13
x13
x13
x13
x13
x18
x19
x19
 
x19
 
x18
 
x24
x24
x24
x24
x24
x24
x24
x24
x18
x13
x13
x13
x13
x13
x13
x13
x13
x13
 
 
 
x140
x144
 
x144
x150
x151
x151
 
x151
 
x150
x151
x151
x150
x147
 
 
 
 
x140
x141
x141
 
x266
 
x140
x144
x145
x145
x145
x145
x145
x147
x147
x144
x147
x147
x147
x147
 
x147
x140
x262
x262
x262
x262
x262
 
 
x263
x263
x383
x383
x383
x383
x383
x383
x383
x383
 
x264
x140
x13
x529
 
x529
x1040
x529
x534
x534
x534
x534
 
 
 
 
x529
x529
x529
x13
x1239
x1239
 
x1239
x2653
x2653
 
x2653
x3779
x3779
x3779
 
x2653
x3106
 
x3106
x3106
x3106
 
x3106
x3106
x2653
x3614
x3614
x2653
 
 
 
 
 
 
 
 
 
x1239
x1239
x13
x210
 
 
 
x210
x210
x210
x210
x210
x225
 
x225
x225
x225
x225
 
x392
x210
x13
x17
x17
 
 
 
x17
x13
x356
x356
x356
 
x356
x356
x356
x356
x356
x356
x356
x356
x356
x356
x356
x356
x356
x356
x356
x360
x360
 
x695
x356
x367
 
 
 
 
 
 
 
x367
 
x695
x695
x695
x695
x695
x695
x356
x2446
x2590
 
 
 
 
 
x2717
x2717
 
 
 
 
 
 
 
 
 
 
x4427
x4392
x6471
x6471
x6471
x6471
 
x6471
x6482
x6482
x6482
x6471
x6628
x6628
x6628
x6628
x6628
x6628
x6471
 
 
 
 
 
 
 
 
x4498
x6181
x6181
 
x6258
x6258
 
x695
 
x356
x679
x679
 
x372
x372
x372
x356
x13
x385
 
x385
x752
x752
 
x698
x698
x698
x698
x698
 
x698
x693
x720
x725
x725
 
x725
x727
x727
x727
x725
x728
x728
x720
x745
x745
x745
x742
x742
x742
x742
x762
x762
 
x761
x779
x779
x779
x743
x743
 
x694
x694
 
x385
x13
x380
 
x380
x730
x730
 
x700
x700
x700
x700
x700
x700
x700
x683
x742
x756
x756
x756
x756
x742
x753
x753
 
x753
x754
x753
x765
x765
x763
x778
x778
 
x778
x805
 
x805
x831
x805
x806
x806
 
x806
x805
 
x784
 
x784
x771
x772
x772
 
x772
 
x762
x742
x777
x777
x777
 
 
 
 
 
 
 
 
x809
x809
x809
x785
x785
 
x684
x684
 
x380
x13
x422
x422
x422
x422
x422
x430
x430
x430
x422
x835
x823
x1212
x1212
 
x422
x768
x768
 
x787
 
x787
x787
x787
x787
x787
x787
x787
x787
x787
x787
x787
x767
x817
 
x817
 
x817
x837
x837
x837
x837
x837
x837
x837
 
 
 
 
 
 
x847
x847
 
 
 
 
 
 
 
 
 
 
 
x847
x847
x817
x817
x817
 
x817
 
x817
x833
x833
x833
x833
x833
x833
 
x817
x833
x833
x833
x833
x833
x833
 
 
 
 
 
 
 
 
 
 
 
 
x831
x831
 
x847
 
x847
 
x817
x832
x832
x832
x832
x832
x817
 
 
 
 
 
 
 
x13
x144
x144
x144
x144
x144
x144
 
x144
 
x144
x144
x158
x144
x264
x261
x375
x375
 
x267
x267
 
x267
x250
x274
 
x274
x279
x283
x279
x280
x280
 
x280
x274
x298
x299
x299
 
x298
x305
x305
x302
x303
x303
 
x303
x293
x307
x307
x274
 
x250
x252
x252
x252
x252
 
x250
x295
x295
 
x295
 
x295
x295
x295
x295
x345
x345
x345
 
x295
x306
x306
 
x295
x302
x302
x302
 
 
x295
 
x308
x310
x310
 
x308
x329
 
x329
x329
x329
 
 
x308
x308
 
 
x295
 
x306
x311
 
x311
x311
 
 
 
x306
x313
x313
 
 
x312
x320
 
x322
x322
 
 
x317
x319
x319
 
 
x295
 
x309
x309
 
x309
 
x320
x320
x320
x320
 
x295
x431
x431
 
x320
x320
 
x263
x144
x13
x214
x214
x214
x214
 
x214
x214
x214
x214
x214
x214
x214
x214
 
x214
x215
x215
 
x214
 
x214
x454
x454
x454
 
 
 
 
 
x454
x469
x478
x480
x480
x480
x480
x480
x480
 
x480
x480
x480
x480
 
x478
x478
x478
x469
 
x480
x480
x475
x476
x476
 
x476
 
x483
x483
 
 
 
 
x454
x887
x1087
 
x1087
x1087
 
x1087
x1198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1198
x1198
x1198
x1198
x1198
 
 
 
 
 
x1176
x1176
x1176
x1176
 
 
 
 
 
x895
x895
x895
x895
x679
x688
x688
 
 
 
 
 
x579
x579
x579
x694
x702
x694
x801
x801
x694
 
x579
x687
x687
x687
x687
x687
x687
x687
x687
 
x687
x687
 
x692
x692
x692
 
 
 
 
 
 
x584
x584
x454
 
 
 
 
 
 
x214
x215
x215
x215
x215
x215
x215
 
x215
 
 
x407
x480
x480
x480
x480
x480
 
x490
x214
x13
x708
x708
x708
x708
 
x708
 
x708
 
 
 
 
 
 
 
x1373
 
x1319
x1325
x1325
x1319
x1367
x1367
x1367
 
 
 
 
x1373
 
x1319
x1325
x1487
x1325
 
x1325
x1325
x1325
 
 
 
 
 
x1319
x1367
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1633
x1633
 
x1367
 
 
 
 
 
 
x1367
 
 
 
 
 
 
 
x1319
x1325
 
 
 
 
 
x1367
 
 
 
 
 
 
x1373
x708
x13
x654
x654
 
 
 
 
 
 
x1209
 
x1209
x654
x1244
x1244
 
 
 
 
 
 
 
x1209
x1209
x654
x13
x363
 
x656
 
x656
 
x363
x686
x686
 
x649
x650
x650
 
x650
 
x655
x649
x650
x650
 
x650
 
x654
x654
x654
x363
 
x13
x13
x13
x13
x13
x13
x647
x647
x647
x647
 
x647
x647
x647
x647
 
x647
x647
 
x647
x647
 
x647
x772
x778
 
x778
x778
 
 
 
 
 
x778
x772
 
x647
x647
x708
x728
x728
 
x728
x746
x728
x730
 
 
 
x708
x749
x749
x708
x647
 
x647
x970
x970
 
x647
x1280
x1280
x1280
 
x1280
 
x1280
x1912
x1912
x1912
x1912
x1912
x1912
x2130
x1912
x2301
x2301
x2301
x2301
x2301
x2330
x2301
x2656
 
 
 
 
 
 
x2651
x2651
x2651
x3317
 
x3317
x3617
x3617
x3317
 
x2301
x2306
x2306
x2301
x1280
 
 
x1281
x1281
x1281
x1280
 
x647
x1001
x1301
x1301
x1301
x1301
x1301
x2998
 
 
 
 
 
x2998
 
x3078
x3078
x3078
x3079
x3079
x3078
x3078
x2998
x1001
x1107
x1107
 
 
 
 
 
 
 
x1107
 
x1126
x1126
 
x1107
x1140
x1140
x1141
x1141
x1140
x1055
x1057
x1057
x1001
 
x647
x647
 
x13
x166
 
x166
 
x166
x166
x166
x166
 
x166
x166
x328
 
x328
 
x328
x471
x471
 
x492
x492
x492
 
x328
x541
x541
 
x492
x492
 
x473
x474
x474
 
x474
 
x473
x515
x515
x515
 
x515
 
x539
 
x515
x650
x650
 
x539
x539
 
x491
 
x491
x473
x484
x484
x328
x334
x334
x328
x329
x329
 
x329
x328
 
x338
x338
 
x310
 
x166
x166
x166
x166
x166
x166
x190
x190
x166
x287
x287
 
x287
 
x309
x309
 
x166
x166
x166
x166
 
x166
x167
x167
 
x166
x173
x174
x174
x174
x166
x268
x268
 
x268
 
x269
x166
 
x13
x161
x314
x416
x161
x13












































































































































I







I








I











































































































































I



























































































I














I





























I




































































I
I























I





































I



























I
































I
I
















I



I





























I





































































































































I



























































I








I

































I























I





































































































































































































































I





I

















I








I















I



























I











































I














I













I






I























I






I







I

I



I











I











I

































































I

















I





































I





















































I















































































































































// Ported from js-yaml v3.13.1:
// https://github.com/nodeca/js-yaml/commit/665aadda42349dcae869f12040d9b10ef18d12da
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2025 the Deno authors. MIT license.

import {
  AMPERSAND,
  ASTERISK,
  BACKSLASH,
  CARRIAGE_RETURN,
  COLON,
  COMMA,
  COMMERCIAL_AT,
  DOT,
  DOUBLE_QUOTE,
  EXCLAMATION,
  GRAVE_ACCENT,
  GREATER_THAN,
  isEOL,
  isFlowIndicator,
  isWhiteSpace,
  isWhiteSpaceOrEOL,
  LEFT_CURLY_BRACKET,
  LEFT_SQUARE_BRACKET,
  LINE_FEED,
  MINUS,
  PERCENT,
  PLUS,
  QUESTION,
  RIGHT_CURLY_BRACKET,
  RIGHT_SQUARE_BRACKET,
  SHARP,
  SINGLE_QUOTE,
  SMALLER_THAN,
  SPACE,
  VERTICAL_LINE,
} from "./_chars.ts";

import { DEFAULT_SCHEMA, type Schema, type TypeMap } from "./_schema.ts";
import type { KindType, Type } from "./_type.ts";
import { isObject, isPlainObject } from "./_utils.ts";

const CONTEXT_FLOW_IN = 1;
const CONTEXT_FLOW_OUT = 2;
const CONTEXT_BLOCK_IN = 3;
const CONTEXT_BLOCK_OUT = 4;

const CHOMPING_CLIP = 1;
const CHOMPING_STRIP = 2;
const CHOMPING_KEEP = 3;

const PATTERN_NON_PRINTABLE =
  // deno-lint-ignore no-control-regex
  /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
const PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
const PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
const PATTERN_TAG_URI =
  /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;

export interface LoaderStateOptions {
  /** specifies a schema to use. */
  schema?: Schema;
  /** compatibility with JSON.parse behaviour. */
  allowDuplicateKeys?: boolean;
  /** function to call on warning messages. */
  onWarning?(error: Error): void;
}

const ESCAPED_HEX_LENGTHS = new Map<number, number>([
  [0x78, 2], // x
  [0x75, 4], // u
  [0x55, 8], // U
]);

const SIMPLE_ESCAPE_SEQUENCES = new Map<number, string>([
  [0x30, "\x00"], // 0
  [0x61, "\x07"], // a
  [0x62, "\x08"], // b
  [0x74, "\x09"], // t
  [0x09, "\x09"], // Tab
  [0x6e, "\x0A"], // n
  [0x76, "\x0B"], // v
  [0x66, "\x0C"], // f
  [0x72, "\x0D"], // r
  [0x65, "\x1B"], // e
  [0x20, " "], // Space
  [0x22, '"'], // "
  [0x2f, "/"], // /
  [0x5c, "\\"], // \
  [0x4e, "\x85"], // N
  [0x5f, "\xA0"], // _
  [0x4c, "\u2028"], // L
  [0x50, "\u2029"], // P
]);

/**
 * Converts a hexadecimal character code to its decimal value.
 */
function hexCharCodeToNumber(charCode: number) {
  // Check if the character code is in the range for '0' to '9'
  if (0x30 <= charCode && charCode <= 0x39) return charCode - 0x30; // Convert '0'-'9' to 0-9

  // Normalize the character code to lowercase if it's a letter
  const lc = charCode | 0x20;

  // Check if the character code is in the range for 'a' to 'f'
  if (0x61 <= lc && lc <= 0x66) return lc - 0x61 + 10; // Convert 'a'-'f' to 10-15

  return -1;
}

/**
 * Converts a decimal character code to its decimal value.
 */
function decimalCharCodeToNumber(charCode: number): number {
  // Check if the character code is in the range for '0' to '9'
  if (0x30 <= charCode && charCode <= 0x39) return charCode - 0x30; // Convert '0'-'9' to 0-9
  return -1;
}

/**
 * Converts a Unicode code point to a string.
 */
function codepointToChar(codepoint: number): string {
  // Check if the code point is within the Basic Multilingual Plane (BMP)
  if (codepoint <= 0xffff) return String.fromCharCode(codepoint); // Convert BMP code point to character

  // Encode UTF-16 surrogate pair for code points beyond BMP
  // Reference: https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
  return String.fromCharCode(
    ((codepoint - 0x010000) >> 10) + 0xd800, // High surrogate
    ((codepoint - 0x010000) & 0x03ff) + 0xdc00, // Low surrogate
  );
}

const INDENT = 4;
const MAX_LENGTH = 75;
const DELIMITERS = "\x00\r\n\x85\u2028\u2029";

function getSnippet(buffer: string, position: number): string | null {
  if (!buffer) return null;
  let start = position;
  let end = position;
  let head = "";
  let tail = "";

  while (start > 0 && !DELIMITERS.includes(buffer.charAt(start - 1))) {
    start--;
    if (position - start > MAX_LENGTH / 2 - 1) {
      head = " ... ";
      start += 5;
      break;
    }
  }

  while (end < buffer.length && !DELIMITERS.includes(buffer.charAt(end))) {
    end++;
    if (end - position > MAX_LENGTH / 2 - 1) {
      tail = " ... ";
      end -= 5;
      break;
    }
  }

  const snippet = buffer.slice(start, end);
  const indent = " ".repeat(INDENT);
  const caretIndent = " ".repeat(INDENT + position - start + head.length);
  return `${indent + head + snippet + tail}\n${caretIndent}^`;
}

function markToString(
  buffer: string,
  position: number,
  line: number,
  column: number,
): string {
  let where = `at line ${line + 1}, column ${column + 1}`;
  const snippet = getSnippet(buffer, position);
  if (snippet) where += `:\n${snippet}`;
  return where;
}

export class LoaderState {
  input: string;
  length: number;
  lineIndent = 0;
  lineStart = 0;
  position = 0;
  line = 0;
  onWarning: ((error: Error) => void) | undefined;
  allowDuplicateKeys: boolean;
  implicitTypes: Type<"scalar">[];
  typeMap: TypeMap;

  version: string | null;
  checkLineBreaks = false;
  tagMap = new Map();
  anchorMap = new Map();
  tag: string | null | undefined;
  anchor: string | null | undefined;
  kind: string | null | undefined;
  result: unknown[] | Record<string, unknown> | string | null = "";

  constructor(
    input: string,
    {
      schema = DEFAULT_SCHEMA,
      onWarning,
      allowDuplicateKeys = false,
    }: LoaderStateOptions,
  ) {
    this.input = input;
    this.onWarning = onWarning;
    this.allowDuplicateKeys = allowDuplicateKeys;
    this.implicitTypes = schema.implicitTypes;
    this.typeMap = schema.typeMap;
    this.length = input.length;
    this.version = null;

    this.readIndent();
  }

  skipWhitespaces() {
    let ch = this.peek();
    while (isWhiteSpace(ch)) {
      ch = this.next();
    }
  }

  skipComment() {
    let ch = this.peek();
    if (ch !== SHARP) return;
    ch = this.next();
    while (ch !== 0 && !isEOL(ch)) {
      ch = this.next();
    }
  }

  readIndent() {
    let char = this.peek();
    while (char === SPACE) {
      this.lineIndent += 1;
      char = this.next();
    }
  }

  peek(offset = 0) {
    return this.input.charCodeAt(this.position + offset);
  }
  next() {
    this.position += 1;
    return this.peek();
  }

  #createError(message: string): SyntaxError {
    const mark = markToString(
      this.input,
      this.position,
      this.line,
      this.position - this.lineStart,
    );
    return new SyntaxError(`${message} ${mark}`);
  }

  dispatchWarning(message: string) {
    const error = this.#createError(message);
    this.onWarning?.(error);
  }

  yamlDirectiveHandler(...args: string[]) {
    if (this.version !== null) {
      throw this.#createError(
        "Cannot handle YAML directive: duplication of %YAML directive",
      );
    }

    if (args.length !== 1) {
      throw this.#createError(
        "Cannot handle YAML directive: YAML directive accepts exactly one argument",
      );
    }

    const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]!);
    if (match === null) {
      throw this.#createError(
        "Cannot handle YAML directive: ill-formed argument",
      );
    }

    const major = parseInt(match[1]!, 10);
    const minor = parseInt(match[2]!, 10);
    if (major !== 1) {
      throw this.#createError(
        "Cannot handle YAML directive: unacceptable YAML version",
      );
    }

    this.version = args[0] ?? null;
    this.checkLineBreaks = minor < 2;
    if (minor !== 1 && minor !== 2) {
      return this.dispatchWarning(
        "Cannot handle YAML directive: unsupported YAML version",
      );
    }
  }
  tagDirectiveHandler(...args: string[]) {
    if (args.length !== 2) {
      throw this.#createError(
        `Cannot handle tag directive: directive accepts exactly two arguments, received ${args.length}`,
      );
    }

    const handle = args[0]!;
    const prefix = args[1]!;

    if (!PATTERN_TAG_HANDLE.test(handle)) {
      throw this.#createError(
        `Cannot handle tag directive: ill-formed handle (first argument) in "${handle}"`,
      );
    }

    if (this.tagMap.has(handle)) {
      throw this.#createError(
        `Cannot handle tag directive: previously declared suffix for "${handle}" tag handle`,
      );
    }

    if (!PATTERN_TAG_URI.test(prefix)) {
      throw this.#createError(
        "Cannot handle tag directive: ill-formed tag prefix (second argument) of the TAG directive",
      );
    }

    this.tagMap.set(handle, prefix);
  }
  captureSegment(start: number, end: number, checkJson: boolean) {
    if (start < end) {
      const result = this.input.slice(start, end);

      if (checkJson) {
        for (
          let position = 0;
          position < result.length;
          position++
        ) {
          const character = result.charCodeAt(position);
          if (
            !(character === 0x09 ||
              (0x20 <= character && character <= 0x10ffff))
          ) {
            throw this.#createError(
              `Expected valid JSON character: received "${character}"`,
            );
          }
        }
      } else if (PATTERN_NON_PRINTABLE.test(result)) {
        throw this.#createError("Stream contains non-printable characters");
      }

      this.result += result;
    }
  }
  readBlockSequence(nodeIndent: number): boolean {
    let detected = false;

    const tag = this.tag;
    const anchor = this.anchor;
    const result: unknown[] = [];

    if (this.anchor !== null && typeof this.anchor !== "undefined") {
      this.anchorMap.set(this.anchor, result);
    }

    let ch = this.peek();

    while (ch !== 0) {
      if (ch !== MINUS) {
        break;
      }

      const following = this.peek(1);

      if (!isWhiteSpaceOrEOL(following)) {
        break;
      }

      detected = true;
      this.position++;

      if (this.skipSeparationSpace(true, -1)) {
        if (this.lineIndent <= nodeIndent) {
          result.push(null);
          ch = this.peek();
          continue;
        }
      }

      const line = this.line;
      this.composeNode(nodeIndent, CONTEXT_BLOCK_IN, false, true);
      result.push(this.result);
      this.skipSeparationSpace(true, -1);

      ch = this.peek();

      if ((this.line === line || this.lineIndent > nodeIndent) && ch !== 0) {
        throw this.#createError(
          "Cannot read block sequence: bad indentation of a sequence entry",
        );
      } else if (this.lineIndent < nodeIndent) {
        break;
      }
    }

    if (detected) {
      this.tag = tag;
      this.anchor = anchor;
      this.kind = "sequence";
      this.result = result;
      return true;
    }
    return false;
  }
  mergeMappings(
    destination: Record<string, unknown>,
    source: Record<string, unknown>,
    overridableKeys: Set<string>,
  ) {
    if (!isObject(source)) {
      throw this.#createError(
        "Cannot merge mappings: the provided source object is unacceptable",
      );
    }

    for (const [key, value] of Object.entries(source)) {
      if (Object.hasOwn(destination, key)) continue;
      Object.defineProperty(destination, key, {
        value,
        writable: true,
        enumerable: true,
        configurable: true,
      });
      overridableKeys.add(key);
    }
  }
  storeMappingPair(
    result: Record<string, unknown>,
    overridableKeys: Set<string>,
    keyTag: string | null,
    keyNode: Record<PropertyKey, unknown> | unknown[] | string | null,
    valueNode: unknown,
    startLine?: number,
    startPos?: number,
  ): Record<string, unknown> {
    // The output is a plain object here, so keys can only be strings.
    // We need to convert keyNode to a string, but doing so can hang the process
    // (deeply nested arrays that explode exponentially using aliases).
    if (Array.isArray(keyNode)) {
      keyNode = Array.prototype.slice.call(keyNode);

      for (let index = 0; index < keyNode.length; index++) {
        if (Array.isArray(keyNode[index])) {
          throw this.#createError(
            "Cannot store mapping pair: nested arrays are not supported inside keys",
          );
        }

        if (typeof keyNode === "object" && isPlainObject(keyNode[index])) {
          keyNode[index] = "[object Object]";
        }
      }
    }

    // Avoid code execution in load() via toString property
    // (still use its own toString for arrays, timestamps,
    // and whatever user schema extensions happen to have @@toStringTag)
    if (typeof keyNode === "object" && isPlainObject(keyNode)) {
      keyNode = "[object Object]";
    }

    keyNode = String(keyNode);

    if (keyTag === "tag:yaml.org,2002:merge") {
      if (Array.isArray(valueNode)) {
        for (
          let index = 0;
          index < valueNode.length;
          index++
        ) {
          this.mergeMappings(result, valueNode[index], overridableKeys);
        }
      } else {
        this.mergeMappings(
          result,
          valueNode as Record<string, unknown>,
          overridableKeys,
        );
      }
    } else {
      if (
        !this.allowDuplicateKeys &&
        !overridableKeys.has(keyNode) &&
        Object.hasOwn(result, keyNode)
      ) {
        this.line = startLine || this.line;
        this.position = startPos || this.position;
        throw this.#createError("Cannot store mapping pair: duplicated key");
      }
      Object.defineProperty(result, keyNode, {
        value: valueNode,
        writable: true,
        enumerable: true,
        configurable: true,
      });
      overridableKeys.delete(keyNode);
    }

    return result;
  }
  readLineBreak() {
    const ch = this.peek();

    if (ch === LINE_FEED) {
      this.position++;
    } else if (ch === CARRIAGE_RETURN) {
      this.position++;
      if (this.peek() === LINE_FEED) {
        this.position++;
      }
    } else {
      throw this.#createError("Cannot read line: line break not found");
    }

    this.line += 1;
    this.lineStart = this.position;
  }
  skipSeparationSpace(allowComments: boolean, checkIndent: number): number {
    let lineBreaks = 0;
    let ch = this.peek();

    while (ch !== 0) {
      this.skipWhitespaces();
      ch = this.peek();

      if (allowComments) {
        this.skipComment();
        ch = this.peek();
      }

      if (isEOL(ch)) {
        this.readLineBreak();

        ch = this.peek();
        lineBreaks++;
        this.lineIndent = 0;

        this.readIndent();
        ch = this.peek();
      } else {
        break;
      }
    }

    if (
      checkIndent !== -1 &&
      lineBreaks !== 0 &&
      this.lineIndent < checkIndent
    ) {
      this.dispatchWarning("deficient indentation");
    }

    return lineBreaks;
  }
  testDocumentSeparator(): boolean {
    let ch = this.peek();

    // Condition this.position === this.lineStart is tested
    // in parent on each call, for efficiency. No needs to test here again.
    if (
      (ch === MINUS || ch === DOT) &&
      ch === this.peek(1) &&
      ch === this.peek(2)
    ) {
      ch = this.peek(3);

      if (ch === 0 || isWhiteSpaceOrEOL(ch)) {
        return true;
      }
    }

    return false;
  }
  writeFoldedLines(count: number) {
    if (count === 1) {
      this.result += " ";
    } else if (count > 1) {
      this.result += "\n".repeat(count - 1);
    }
  }
  readPlainScalar(nodeIndent: number, withinFlowCollection: boolean): boolean {
    const kind = this.kind;
    const result = this.result;
    let ch = this.peek();

    if (
      isWhiteSpaceOrEOL(ch) ||
      isFlowIndicator(ch) ||
      ch === SHARP ||
      ch === AMPERSAND ||
      ch === ASTERISK ||
      ch === EXCLAMATION ||
      ch === VERTICAL_LINE ||
      ch === GREATER_THAN ||
      ch === SINGLE_QUOTE ||
      ch === DOUBLE_QUOTE ||
      ch === PERCENT ||
      ch === COMMERCIAL_AT ||
      ch === GRAVE_ACCENT
    ) {
      return false;
    }

    let following: number;
    if (ch === QUESTION || ch === MINUS) {
      following = this.peek(1);

      if (
        isWhiteSpaceOrEOL(following) ||
        (withinFlowCollection && isFlowIndicator(following))
      ) {
        return false;
      }
    }

    this.kind = "scalar";
    this.result = "";
    let captureEnd = this.position;
    let captureStart = this.position;
    let hasPendingContent = false;
    let line = 0;
    while (ch !== 0) {
      if (ch === COLON) {
        following = this.peek(1);

        if (
          isWhiteSpaceOrEOL(following) ||
          (withinFlowCollection && isFlowIndicator(following))
        ) {
          break;
        }
      } else if (ch === SHARP) {
        const preceding = this.peek(-1);

        if (isWhiteSpaceOrEOL(preceding)) {
          break;
        }
      } else if (
        (this.position === this.lineStart && this.testDocumentSeparator()) ||
        (withinFlowCollection && isFlowIndicator(ch))
      ) {
        break;
      } else if (isEOL(ch)) {
        line = this.line;
        const lineStart = this.lineStart;
        const lineIndent = this.lineIndent;
        this.skipSeparationSpace(false, -1);

        if (this.lineIndent >= nodeIndent) {
          hasPendingContent = true;
          ch = this.peek();
          continue;
        } else {
          this.position = captureEnd;
          this.line = line;
          this.lineStart = lineStart;
          this.lineIndent = lineIndent;
          break;
        }
      }

      if (hasPendingContent) {
        this.captureSegment(captureStart, captureEnd, false);
        this.writeFoldedLines(this.line - line);
        captureStart = captureEnd = this.position;
        hasPendingContent = false;
      }

      if (!isWhiteSpace(ch)) {
        captureEnd = this.position + 1;
      }

      ch = this.next();
    }

    this.captureSegment(captureStart, captureEnd, false);

    if (this.result) {
      return true;
    }

    this.kind = kind;
    this.result = result;
    return false;
  }
  readSingleQuotedScalar(nodeIndent: number): boolean {
    let ch = this.peek();

    if (ch !== SINGLE_QUOTE) {
      return false;
    }

    this.kind = "scalar";
    this.result = "";
    this.position++;
    let captureStart = this.position;
    let captureEnd = this.position;

    ch = this.peek();
    while (ch !== 0) {
      if (ch === SINGLE_QUOTE) {
        this.captureSegment(captureStart, this.position, true);
        ch = this.next();

        if (ch === SINGLE_QUOTE) {
          captureStart = this.position;
          this.position++;
          captureEnd = this.position;
        } else {
          return true;
        }
      } else if (isEOL(ch)) {
        this.captureSegment(captureStart, captureEnd, true);
        this.writeFoldedLines(this.skipSeparationSpace(false, nodeIndent));
        captureStart = captureEnd = this.position;
      } else if (
        this.position === this.lineStart &&
        this.testDocumentSeparator()
      ) {
        throw this.#createError(
          "Unexpected end of the document within a single quoted scalar",
        );
      } else {
        this.position++;
        captureEnd = this.position;
      }
      ch = this.peek();
    }

    throw this.#createError(
      "Unexpected end of the stream within a single quoted scalar",
    );
  }
  readDoubleQuotedScalar(nodeIndent: number): boolean {
    let ch = this.peek();

    if (ch !== DOUBLE_QUOTE) {
      return false;
    }

    this.kind = "scalar";
    this.result = "";
    this.position++;
    let captureEnd = this.position;
    let captureStart = this.position;
    let tmp: number;
    ch = this.peek();
    while (ch !== 0) {
      if (ch === DOUBLE_QUOTE) {
        this.captureSegment(captureStart, this.position, true);
        this.position++;
        return true;
      }
      if (ch === BACKSLASH) {
        this.captureSegment(captureStart, this.position, true);
        ch = this.next();

        if (isEOL(ch)) {
          this.skipSeparationSpace(false, nodeIndent);
        } else if (ch < 256 && SIMPLE_ESCAPE_SEQUENCES.has(ch)) {
          this.result += SIMPLE_ESCAPE_SEQUENCES.get(ch);
          this.position++;
        } else if ((tmp = ESCAPED_HEX_LENGTHS.get(ch) ?? 0) > 0) {
          let hexLength = tmp;
          let hexResult = 0;

          for (; hexLength > 0; hexLength--) {
            ch = this.next();

            if ((tmp = hexCharCodeToNumber(ch)) >= 0) {
              hexResult = (hexResult << 4) + tmp;
            } else {
              throw this.#createError(
                "Cannot read double quoted scalar: expected hexadecimal character",
              );
            }
          }

          this.result += codepointToChar(hexResult);

          this.position++;
        } else {
          throw this.#createError(
            "Cannot read double quoted scalar: unknown escape sequence",
          );
        }

        captureStart = captureEnd = this.position;
      } else if (isEOL(ch)) {
        this.captureSegment(captureStart, captureEnd, true);
        this.writeFoldedLines(this.skipSeparationSpace(false, nodeIndent));
        captureStart = captureEnd = this.position;
      } else if (
        this.position === this.lineStart &&
        this.testDocumentSeparator()
      ) {
        throw this.#createError(
          "Unexpected end of the document within a double quoted scalar",
        );
      } else {
        this.position++;
        captureEnd = this.position;
      }
      ch = this.peek();
    }

    throw this.#createError(
      "Unexpected end of the stream within a double quoted scalar",
    );
  }
  readFlowCollection(nodeIndent: number): boolean {
    let ch = this.peek();
    let terminator: number;
    let isMapping = true;
    let result = {};
    if (ch === LEFT_SQUARE_BRACKET) {
      terminator = RIGHT_SQUARE_BRACKET;
      isMapping = false;
      result = [];
    } else if (ch === LEFT_CURLY_BRACKET) {
      terminator = RIGHT_CURLY_BRACKET;
    } else {
      return false;
    }

    if (this.anchor !== null && typeof this.anchor !== "undefined") {
      this.anchorMap.set(this.anchor, result);
    }

    ch = this.next();

    const tag = this.tag;
    const anchor = this.anchor;
    let readNext = true;
    let valueNode = null;
    let keyNode = null;
    let keyTag: string | null = null;
    let isExplicitPair = false;
    let isPair = false;
    let following = 0;
    let line = 0;
    const overridableKeys = new Set<string>();
    while (ch !== 0) {
      this.skipSeparationSpace(true, nodeIndent);

      ch = this.peek();

      if (ch === terminator) {
        this.position++;
        this.tag = tag;
        this.anchor = anchor;
        this.kind = isMapping ? "mapping" : "sequence";
        this.result = result;
        return true;
      }
      if (!readNext) {
        throw this.#createError(
          "Cannot read flow collection: missing comma between flow collection entries",
        );
      }

      keyTag = keyNode = valueNode = null;
      isPair = isExplicitPair = false;

      if (ch === QUESTION) {
        following = this.peek(1);

        if (isWhiteSpaceOrEOL(following)) {
          isPair = isExplicitPair = true;
          this.position++;
          this.skipSeparationSpace(true, nodeIndent);
        }
      }

      line = this.line;
      this.composeNode(nodeIndent, CONTEXT_FLOW_IN, false, true);
      keyTag = this.tag || null;
      keyNode = this.result;
      this.skipSeparationSpace(true, nodeIndent);

      ch = this.peek();

      if ((isExplicitPair || this.line === line) && ch === COLON) {
        isPair = true;
        ch = this.next();
        this.skipSeparationSpace(true, nodeIndent);
        this.composeNode(nodeIndent, CONTEXT_FLOW_IN, false, true);
        valueNode = this.result;
      }

      if (isMapping) {
        this.storeMappingPair(
          result as Record<string, unknown>,
          overridableKeys,
          keyTag,
          keyNode,
          valueNode,
        );
      } else if (isPair) {
        (result as Record<string, unknown>[]).push(
          this.storeMappingPair(
            {},
            overridableKeys,
            keyTag,
            keyNode,
            valueNode,
          ),
        );
      } else {
        (result as unknown[]).push(keyNode);
      }

      this.skipSeparationSpace(true, nodeIndent);

      ch = this.peek();

      if (ch === COMMA) {
        readNext = true;
        ch = this.next();
      } else {
        readNext = false;
      }
    }

    throw this.#createError(
      "Cannot read flow collection: unexpected end of the stream within a flow collection",
    );
  }
  // Handles block scaler styles: e.g. '|', '>', '|-' and '>-'.
  // https://yaml.org/spec/1.2.2/#81-block-scalar-styles
  readBlockScalar(nodeIndent: number): boolean {
    let chomping = CHOMPING_CLIP;
    let didReadContent = false;
    let detectedIndent = false;
    let textIndent = nodeIndent;
    let emptyLines = 0;
    let atMoreIndented = false;

    let ch = this.peek();

    let folding = false;
    if (ch === VERTICAL_LINE) {
      folding = false;
    } else if (ch === GREATER_THAN) {
      folding = true;
    } else {
      return false;
    }

    this.kind = "scalar";
    this.result = "";

    let tmp = 0;
    while (ch !== 0) {
      ch = this.next();

      if (ch === PLUS || ch === MINUS) {
        if (CHOMPING_CLIP === chomping) {
          chomping = ch === PLUS ? CHOMPING_KEEP : CHOMPING_STRIP;
        } else {
          throw this.#createError(
            "Cannot read block: chomping mode identifier repeated",
          );
        }
      } else if ((tmp = decimalCharCodeToNumber(ch)) >= 0) {
        if (tmp === 0) {
          throw this.#createError(
            "Cannot read block: indentation width must be greater than 0",
          );
        } else if (!detectedIndent) {
          textIndent = nodeIndent + tmp - 1;
          detectedIndent = true;
        } else {
          throw this.#createError(
            "Cannot read block: indentation width identifier repeated",
          );
        }
      } else {
        break;
      }
    }

    if (isWhiteSpace(ch)) {
      this.skipWhitespaces();
      this.skipComment();
      ch = this.peek();
    }

    while (ch !== 0) {
      this.readLineBreak();
      this.lineIndent = 0;

      ch = this.peek();

      while (
        (!detectedIndent || this.lineIndent < textIndent) &&
        ch === SPACE
      ) {
        this.lineIndent++;
        ch = this.next();
      }

      if (!detectedIndent && this.lineIndent > textIndent) {
        textIndent = this.lineIndent;
      }

      if (isEOL(ch)) {
        emptyLines++;
        continue;
      }

      // End of the scalar.
      if (this.lineIndent < textIndent) {
        // Perform the chomping.
        if (chomping === CHOMPING_KEEP) {
          this.result += "\n".repeat(
            didReadContent ? 1 + emptyLines : emptyLines,
          );
        } else if (chomping === CHOMPING_CLIP) {
          if (didReadContent) {
            // i.e. only if the scalar is not empty.
            this.result += "\n";
          }
        }

        // Break this `while` cycle and go to the function's epilogue.
        break;
      }

      // Folded style: use fancy rules to handle line breaks.
      if (folding) {
        // Lines starting with white space characters (more-indented lines) are not folded.
        if (isWhiteSpace(ch)) {
          atMoreIndented = true;
          // except for the first content line (cf. Example 8.1)
          this.result += "\n".repeat(
            didReadContent ? 1 + emptyLines : emptyLines,
          );

          // End of more-indented block.
        } else if (atMoreIndented) {
          atMoreIndented = false;
          this.result += "\n".repeat(emptyLines + 1);

          // Just one line break - perceive as the same line.
        } else if (emptyLines === 0) {
          if (didReadContent) {
            // i.e. only if we have already read some scalar content.
            this.result += " ";
          }

          // Several line breaks - perceive as different lines.
        } else {
          this.result += "\n".repeat(emptyLines);
        }

        // Literal style: just add exact number of line breaks between content lines.
      } else {
        // Keep all line breaks except the header line break.
        this.result += "\n".repeat(
          didReadContent ? 1 + emptyLines : emptyLines,
        );
      }

      didReadContent = true;
      detectedIndent = true;
      emptyLines = 0;
      const captureStart = this.position;

      while (!isEOL(ch) && ch !== 0) {
        ch = this.next();
      }

      this.captureSegment(captureStart, this.position, false);
    }

    return true;
  }
  readBlockMapping(nodeIndent: number, flowIndent: number): boolean {
    const tag = this.tag;
    const anchor = this.anchor;
    const result = {};
    const overridableKeys = new Set<string>();

    let allowCompact = false;
    let line: number;
    let pos: number;
    let keyTag = null;
    let keyNode = null;
    let valueNode = null;
    let atExplicitKey = false;
    let detected = false;

    if (this.anchor !== null && typeof this.anchor !== "undefined") {
      this.anchorMap.set(this.anchor, result);
    }

    let ch = this.peek();

    while (ch !== 0) {
      const following = this.peek(1);
      line = this.line; // Save the current line.
      pos = this.position;

      //
      // Explicit notation case. There are two separate blocks:
      // first for the key (denoted by "?") and second for the value (denoted by ":")
      //
      if ((ch === QUESTION || ch === COLON) && isWhiteSpaceOrEOL(following)) {
        if (ch === QUESTION) {
          if (atExplicitKey) {
            this.storeMappingPair(
              result,
              overridableKeys,
              keyTag as string,
              keyNode,
              null,
            );
            keyTag = null;
            keyNode = null;
            valueNode = null;
          }

          detected = true;
          atExplicitKey = true;
          allowCompact = true;
        } else if (atExplicitKey) {
          // i.e. 0x3A/* : */ === character after the explicit key.
          atExplicitKey = false;
          allowCompact = true;
        } else {
          throw this.#createError(
            "Cannot read block as explicit mapping pair is incomplete: a key node is missed or followed by a non-tabulated empty line",
          );
        }

        this.position += 1;
        ch = following;

        //
        // Implicit notation case. Flow-style node as the key first, then ":", and the value.
        //
      } else if (this.composeNode(flowIndent, CONTEXT_FLOW_OUT, false, true)) {
        if (this.line === line) {
          ch = this.peek();

          this.skipWhitespaces();
          ch = this.peek();

          if (ch === COLON) {
            ch = this.next();

            if (!isWhiteSpaceOrEOL(ch)) {
              throw this.#createError(
                "Cannot read block: a whitespace character is expected after the key-value separator within a block mapping",
              );
            }

            if (atExplicitKey) {
              this.storeMappingPair(
                result,
                overridableKeys,
                keyTag as string,
                keyNode,
                null,
              );
              keyTag = null;
              keyNode = null;
              valueNode = null;
            }

            detected = true;
            atExplicitKey = false;
            allowCompact = false;
            keyTag = this.tag;
            keyNode = this.result;
          } else if (detected) {
            throw this.#createError(
              "Cannot read an implicit mapping pair: missing colon",
            );
          } else {
            this.tag = tag;
            this.anchor = anchor;
            return true; // Keep the result of `composeNode`.
          }
        } else if (detected) {
          throw this.#createError(
            "Cannot read a block mapping entry: a multiline key may not be an implicit key",
          );
        } else {
          this.tag = tag;
          this.anchor = anchor;
          return true; // Keep the result of `composeNode`.
        }
      } else {
        break; // Reading is done. Go to the epilogue.
      }

      //
      // Common reading code for both explicit and implicit notations.
      //
      if (this.line === line || this.lineIndent > nodeIndent) {
        if (
          this.composeNode(nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)
        ) {
          if (atExplicitKey) {
            keyNode = this.result;
          } else {
            valueNode = this.result;
          }
        }

        if (!atExplicitKey) {
          this.storeMappingPair(
            result,
            overridableKeys,
            keyTag as string,
            keyNode,
            valueNode,
            line,
            pos,
          );
          keyTag = keyNode = valueNode = null;
        }

        this.skipSeparationSpace(true, -1);
        ch = this.peek();
      }

      if (this.lineIndent > nodeIndent && ch !== 0) {
        throw this.#createError(
          "Cannot read block: bad indentation of a mapping entry",
        );
      } else if (this.lineIndent < nodeIndent) {
        break;
      }
    }

    //
    // Epilogue.
    //

    // Special case: last mapping's node contains only the key in explicit notation.
    if (atExplicitKey) {
      this.storeMappingPair(
        result,
        overridableKeys,
        keyTag as string,
        keyNode,
        null,
      );
    }

    // Expose the resulting mapping.
    if (detected) {
      this.tag = tag;
      this.anchor = anchor;
      this.kind = "mapping";
      this.result = result;
    }

    return detected;
  }
  readTagProperty(): boolean {
    let isVerbatim = false;
    let isNamed = false;
    let tagHandle = "";
    let tagName: string;

    let ch = this.peek();

    if (ch !== EXCLAMATION) return false;

    if (this.tag !== null) {
      throw this.#createError(
        "Cannot read tag property: duplication of a tag property",
      );
    }

    ch = this.next();

    if (ch === SMALLER_THAN) {
      isVerbatim = true;
      ch = this.next();
    } else if (ch === EXCLAMATION) {
      isNamed = true;
      tagHandle = "!!";
      ch = this.next();
    } else {
      tagHandle = "!";
    }

    let position = this.position;

    if (isVerbatim) {
      do {
        ch = this.next();
      } while (ch !== 0 && ch !== GREATER_THAN);

      if (this.position < this.length) {
        tagName = this.input.slice(position, this.position);
        ch = this.next();
      } else {
        throw this.#createError(
          "Cannot read tag property: unexpected end of stream",
        );
      }
    } else {
      while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
        if (ch === EXCLAMATION) {
          if (!isNamed) {
            tagHandle = this.input.slice(position - 1, this.position + 1);

            if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
              throw this.#createError(
                "Cannot read tag property: named tag handle contains invalid characters",
              );
            }

            isNamed = true;
            position = this.position + 1;
          } else {
            throw this.#createError(
              "Cannot read tag property: tag suffix cannot contain an exclamation mark",
            );
          }
        }

        ch = this.next();
      }

      tagName = this.input.slice(position, this.position);

      if (PATTERN_FLOW_INDICATORS.test(tagName)) {
        throw this.#createError(
          "Cannot read tag property: tag suffix cannot contain flow indicator characters",
        );
      }
    }

    if (tagName && !PATTERN_TAG_URI.test(tagName)) {
      throw this.#createError(
        `Cannot read tag property: invalid characters in tag name "${tagName}"`,
      );
    }

    if (isVerbatim) {
      this.tag = tagName;
    } else if (this.tagMap.has(tagHandle)) {
      this.tag = this.tagMap.get(tagHandle) + tagName;
    } else if (tagHandle === "!") {
      this.tag = `!${tagName}`;
    } else if (tagHandle === "!!") {
      this.tag = `tag:yaml.org,2002:${tagName}`;
    } else {
      throw this.#createError(
        `Cannot read tag property: undeclared tag handle "${tagHandle}"`,
      );
    }

    return true;
  }
  readAnchorProperty(): boolean {
    let ch = this.peek();
    if (ch !== AMPERSAND) return false;

    if (this.anchor !== null) {
      throw this.#createError(
        "Cannot read anchor property: duplicate anchor property",
      );
    }
    ch = this.next();

    const position = this.position;
    while (ch !== 0 && !isWhiteSpaceOrEOL(ch) && !isFlowIndicator(ch)) {
      ch = this.next();
    }

    if (this.position === position) {
      throw this.#createError(
        "Cannot read anchor property: name of an anchor node must contain at least one character",
      );
    }

    this.anchor = this.input.slice(position, this.position);
    return true;
  }
  readAlias(): boolean {
    if (this.peek() !== ASTERISK) return false;

    let ch = this.next();

    const position = this.position;

    while (ch !== 0 && !isWhiteSpaceOrEOL(ch) && !isFlowIndicator(ch)) {
      ch = this.next();
    }

    if (this.position === position) {
      throw this.#createError(
        "Cannot read alias: alias name must contain at least one character",
      );
    }

    const alias = this.input.slice(position, this.position);
    if (!this.anchorMap.has(alias)) {
      throw this.#createError(
        `Cannot read alias: unidentified alias "${alias}"`,
      );
    }

    this.result = this.anchorMap.get(alias);
    this.skipSeparationSpace(true, -1);
    return true;
  }

  composeNode(
    parentIndent: number,
    nodeContext: number,
    allowToSeek: boolean,
    allowCompact: boolean,
  ): boolean {
    let indentStatus = 1; // 1: this>parent, 0: this=parent, -1: this<parent
    let atNewLine = false;
    let hasContent = false;
    let type: Type<KindType>;

    this.tag = null;
    this.anchor = null;
    this.kind = null;
    this.result = null;

    const allowBlockScalars = CONTEXT_BLOCK_OUT === nodeContext ||
      CONTEXT_BLOCK_IN === nodeContext;

    let allowBlockCollections = allowBlockScalars;
    const allowBlockStyles = allowBlockScalars;

    if (allowToSeek) {
      if (this.skipSeparationSpace(true, -1)) {
        atNewLine = true;

        if (this.lineIndent > parentIndent) {
          indentStatus = 1;
        } else if (this.lineIndent === parentIndent) {
          indentStatus = 0;
        } else if (this.lineIndent < parentIndent) {
          indentStatus = -1;
        }
      }
    }

    if (indentStatus === 1) {
      while (this.readTagProperty() || this.readAnchorProperty()) {
        if (this.skipSeparationSpace(true, -1)) {
          atNewLine = true;
          allowBlockCollections = allowBlockStyles;

          if (this.lineIndent > parentIndent) {
            indentStatus = 1;
          } else if (this.lineIndent === parentIndent) {
            indentStatus = 0;
          } else if (this.lineIndent < parentIndent) {
            indentStatus = -1;
          }
        } else {
          allowBlockCollections = false;
        }
      }
    }

    if (allowBlockCollections) {
      allowBlockCollections = atNewLine || allowCompact;
    }

    if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
      const cond = CONTEXT_FLOW_IN === nodeContext ||
        CONTEXT_FLOW_OUT === nodeContext;
      const flowIndent = cond ? parentIndent : parentIndent + 1;

      const blockIndent = this.position - this.lineStart;

      if (indentStatus === 1) {
        if (
          (allowBlockCollections &&
            (this.readBlockSequence(blockIndent) ||
              this.readBlockMapping(blockIndent, flowIndent))) ||
          this.readFlowCollection(flowIndent)
        ) {
          hasContent = true;
        } else {
          if (
            (allowBlockScalars && this.readBlockScalar(flowIndent)) ||
            this.readSingleQuotedScalar(flowIndent) ||
            this.readDoubleQuotedScalar(flowIndent)
          ) {
            hasContent = true;
          } else if (this.readAlias()) {
            hasContent = true;

            if (this.tag !== null || this.anchor !== null) {
              throw this.#createError(
                "Cannot compose node: alias node should not have any properties",
              );
            }
          } else if (
            this.readPlainScalar(flowIndent, CONTEXT_FLOW_IN === nodeContext)
          ) {
            hasContent = true;

            if (this.tag === null) {
              this.tag = "?";
            }
          }

          if (this.anchor !== null) {
            this.anchorMap.set(this.anchor, this.result);
          }
        }
      } else if (indentStatus === 0) {
        // Special case: block sequences are allowed to have same indentation level as the parent.
        // http://www.yaml.org/spec/1.2/spec.html#id2799784
        hasContent = allowBlockCollections &&
          this.readBlockSequence(blockIndent);
      }
    }

    if (this.tag !== null && this.tag !== "!") {
      if (this.tag === "?") {
        for (
          let typeIndex = 0;
          typeIndex < this.implicitTypes.length;
          typeIndex++
        ) {
          type = this.implicitTypes[typeIndex]!;

          // Implicit resolving is not allowed for non-scalar types, and '?'
          // non-specific tag is only assigned to plain scalars. So, it isn't
          // needed to check for 'kind' conformity.

          if (type.resolve(this.result)) {
            // `state.result` updated in resolver if matched
            this.result = type.construct(this.result);
            this.tag = type.tag;
            if (this.anchor !== null) {
              this.anchorMap.set(this.anchor, this.result);
            }
            break;
          }
        }
      } else if (this.typeMap[this.kind ?? "fallback"].has(this.tag)) {
        const map = this.typeMap[this.kind ?? "fallback"];
        type = map.get(this.tag)!;

        if (this.result !== null && type.kind !== this.kind) {
          throw this.#createError(
            `Unacceptable node kind for !<${this.tag}> tag: it should be "${type.kind}", not "${this.kind}"`,
          );
        }

        if (!type.resolve(this.result)) {
          // `state.result` updated in resolver if matched
          throw this.#createError(
            `Cannot resolve a node with !<${this.tag}> explicit tag`,
          );
        } else {
          this.result = type.construct(this.result);
          if (this.anchor !== null) {
            this.anchorMap.set(this.anchor, this.result);
          }
        }
      } else {
        throw this.#createError(`Cannot resolve unknown tag !<${this.tag}>`);
      }
    }

    return this.tag !== null || this.anchor !== null || hasContent;
  }

  readDocument() {
    const documentStart = this.position;

    let hasDirectives = false;

    this.version = null;
    this.checkLineBreaks = false;
    this.tagMap = new Map();
    this.anchorMap = new Map();

    let ch = this.peek();
    while (ch !== 0) {
      this.skipSeparationSpace(true, -1);

      ch = this.peek();

      if (this.lineIndent > 0 || ch !== PERCENT) {
        break;
      }

      hasDirectives = true;
      ch = this.next();
      let position = this.position;

      while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
        ch = this.next();
      }

      const directiveName = this.input.slice(position, this.position);
      const directiveArgs = [];

      if (directiveName.length < 1) {
        throw this.#createError(
          "Cannot read document: directive name length must be greater than zero",
        );
      }

      while (ch !== 0) {
        this.skipWhitespaces();
        this.skipComment();
        ch = this.peek();

        if (isEOL(ch)) break;

        position = this.position;

        while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
          ch = this.next();
        }

        directiveArgs.push(this.input.slice(position, this.position));
      }

      if (ch !== 0) this.readLineBreak();

      switch (directiveName) {
        case "YAML":
          this.yamlDirectiveHandler(...directiveArgs);
          break;
        case "TAG":
          this.tagDirectiveHandler(...directiveArgs);
          break;
        default:
          this.dispatchWarning(
            `unknown document directive "${directiveName}"`,
          );
          break;
      }

      ch = this.peek();
    }

    this.skipSeparationSpace(true, -1);

    if (
      this.lineIndent === 0 &&
      this.peek() === MINUS &&
      this.peek(1) === MINUS &&
      this.peek(2) === MINUS
    ) {
      this.position += 3;
      this.skipSeparationSpace(true, -1);
    } else if (hasDirectives) {
      throw this.#createError(
        "Cannot read document: directives end mark is expected",
      );
    }

    this.composeNode(this.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
    this.skipSeparationSpace(true, -1);

    if (
      this.checkLineBreaks &&
      PATTERN_NON_ASCII_LINE_BREAKS.test(
        this.input.slice(documentStart, this.position),
      )
    ) {
      this.dispatchWarning("non-ASCII line breaks are interpreted as content");
    }

    if (this.position === this.lineStart && this.testDocumentSeparator()) {
      if (this.peek() === DOT) {
        this.position += 3;
        this.skipSeparationSpace(true, -1);
      }
    } else if (this.position < this.length - 1) {
      throw this.#createError(
        "Cannot read document: end of the stream or a document separator is expected",
      );
    }

    return this.result;
  }

  *readDocuments() {
    while (this.position < this.length - 1) {
      yield this.readDocument();
    }
  }
}