All files / lib/internal url.js

94.52% Statements 1520/1608
97.5% Branches 508/521
97.36% Functions 74/76
94.52% Lines 1520/1608

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 160943x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 7x 7x 7x 7x 43x 7x 7x 7x 7x       7x 7x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 698x 698x 698x 43x 43x 43x 43x 43x 43x 43x 43x 43x 82620x 82620x 82620x 82620x 82620x 82620x 82620x 82620x 82620x 82620x 43x 43x 1292x 1292x 1292x 43x 43x 43x 43x 43x 43x 43x 74554x 74233x 74551x 32x 32x 2x 2x 2x 2x 32x 19x 1x 1x 18x 18x 18x 18x 19x 22x 22x 22x 4x 4x 18x 18x 22x 15x 15x 11x 11x 19x 15x 4x 4x 11x 11x 30x 11x 11x 11x 11x 11x 11x 45x 45x 45x 41x 41x 41x 41x 41x 41x 3x 38x 34x 34x 34x 34x 41x 45x 7x 321x 289x 289x 289x 288x 288x 74537x 74537x 74537x 74554x 43x 43x 8x 8x 7x 8x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 9x 9x 6x 6x 6x 6x 6x 6x 8x 1x 1x 8x 4x 4x 4x 1x 8x 43x 43x 70x 70x 67x 67x 3x 3x 64x 64x 64x 64x 64x 70x 43x 43x 30x 30x 27x 28x 2x 2x 25x 25x 25x 25x 47x 47x 27x 34x 20x 20x 47x 23x 30x 43x 43x 250x 250x 247x 248x 2x 2x 245x 245x 245x 247x 228x 121x 121x 228x 122x 250x 43x 43x 16x 16x 13x 14x 2x 2x 11x 11x 11x 11x 13x 29x 22x 22x 29x 9x 16x 43x 43x 51x 51x 48x 49x 2x 2x 46x 46x 46x 48x 71x 30x 30x 71x 14x 51x 43x 43x 97x 97x 94x 94x 3x 3x 91x 91x 91x 91x 91x 91x 91x 91x 91x 91x 41x 41x 23x 17x 17x 17x 20x 6x 6x 41x 18x 18x 41x 87x 87x 87x 87x 70x 70x 87x 87x 97x 43x 43x 24x 24x 24x 24x 2x 22x 18x 18x 18x 18x 62x 62x 62x 62x 140x 100x 100x 140x 40x 40x 140x 62x 62x 62x 20x 2x 2x 2x 2x 14x 184x 184x 184x 184x 184x 180x 180x 14x 2x 22x 22x 24x 43x 43x 43x 43x 43x 332x 332x 331x 331x 332x 43x 43x 6x 6x 5x 5x 5x 5x 5x 5x 5x 23x 23x 23x 23x 23x 23x 23x 6x 43x 43x 43x 6x 6x 5x 5x 6x 43x 43x 4x 4x 3x 3x 4x 43x 43x 43x 43x 422x 422x 419x 419x 422x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 74205x 74205x 74205x 74205x 74205x 74205x 74205x 74205x 74205x 74205x 74205x 74205x 74205x 74202x 74202x 74202x 74205x 74205x 43x 8419x 8419x 8419x 43x 33x 33x 33x 33x 17x 27x 16x 16x 33x 33x 33x 43x 276x 276x 276x 276x 276x 276x 276x       276x 43x 120x 120x 120x 120x 43x 149x 149x 149x 149x 149x 149x 43x 42398x 42398x 42398x 42398x 42394x 42394x 42398x 4x 4x 4x 42398x 42398x 42398x 42382x 42382x 42382x 42398x 43x 159x 159x 159x 159x 43x 74x 74x 74x 74x 43x 190906x 190906x 190906x 43x 43x 43x 82763x 82763x 82763x 82763x 9091x 9091x 82620x 82620x 82620x 82620x 82763x 43x 43x 1x 1x 43x 43x 132100x 132100x 43x 43x 43x 201x 201x 201x 201x 201x 43x 43x 4x 4x     4x 4x 4x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 4x 43x 43x 69542x 69542x 69538x 69538x 69538x 69538x 69538x 69538x 69538x 69538x 69538x 69538x 69538x 69538x 62564x 62564x 62564x 62564x 421x 421x 421x 421x 421x 421x 62564x 62564x 62564x 62564x 62564x 69542x 6864x 69531x 62674x 30x 30x 62674x 62628x 62628x 62674x 69542x 69542x 69542x 69542x 69538x 69542x 43x 43x 43x 13215x 13215x 13212x 13215x 43x 43x 56295x 56295x 56292x 56295x 43x 43x 9x 9x 7x 7x 7x 7x 7x 9x 43x 43x 43x 9895x 9895x 9892x 9892x 9892x 9894x 25x 25x 25x 25x 2x 2x 25x 2x 9895x 9895x 9895x 9895x 9895x 698x 9895x 9169x 9895x 43x 43x 23263x 23263x 23260x 23263x 43x 43x 89x 89x 87x 87x 87x 87x 83x 83x 83x 89x 43x 43x 1290x 1290x 1287x 1290x 43x 43x 66x 66x 64x 64x 64x 64x 50x 64x 4x 4x 4x 4x 46x 46x 66x 43x 43x 1278x 1278x 1275x 1278x 43x 43x 64x 64x 62x 62x 62x 62x 50x 62x 4x 4x 4x 4x 46x 46x 64x 43x 43x 1407x 1407x 1404x 1407x 1407x 1407x 1404x 1407x 43x 43x 215x 215x 213x 213x 213x 213x 4x 4x 4x 207x 207x 215x 43x 43x 11549x 11549x 11549x 11549x 43x 43x 193x 193x 191x 191x 191x 191x 4x 4x 4x 185x 193x 43x 43x 2691x 2691x 2688x 2691x 2691x 43x 43x 83x 83x 81x 81x 81x 81x 71x 79x 2x 2x 2x 69x 69x 83x 43x 43x 19587x 19587x 19584x 19584x 19584x 19403x 19586x 19383x 19587x 43x 43x 42404x 42404x 42402x 42402x 42402x 42404x 42398x 42398x 42404x 43x 43x 2442x 2442x 2439x 2442x 2442x 323x 2442x 43x 43x 1103x 1103x 1101x 1101x 1101x 937x 937x 1099x 162x 162x 162x 162x 159x 159x 159x 162x 1099x 1103x 43x 43x 43x 522x 522x 519x 522x 43x 43x 2225x 2225x 2222x 2225x 2225x 161x 2225x 43x 43x 1007x 1007x 1005x 1005x 1005x 1005x 929x 929x 929x 929x 78x 74x 74x 74x 74x 1007x 43x 43x 14x 14x 11x 14x 43x 43x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 2x 2x 2x 2x 7x 43x 43x 2x 2x 2x 2x 2x 2x 2x     2x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 192x 192x 192x 116x 116x 116x 134x 111x 111x 192x 5x 5x 5x 192x 43x 75592x 75592x 74105x 74105x 74105x 1487x 75592x 43x 43x 43x 1487x 1487x 1487x 1487x 1487x 1487x 1487x 1487x 1487x 1487x 65095x 65095x 65095x 65095x 813x 91x 91x 91x 91x 722x 722x 813x 722x 813x 722x 722x 722x 722x 813x 722x 722x 722x 722x 722x 722x 722x 722x 64282x 64282x 65095x 1493x 1493x 1493x 1493x 1493x 1493x 1493x 1493x 1493x 1493x 1493x 1493x 1493x 1493x 62789x 62789x 65095x 6547x 6547x 6547x 6547x 65095x 11657x 11657x 11657x 703x 11657x 1354x 1328x 654x 654x 1354x 26x 26x 1354x 11657x 65095x 1487x 1487x 1487x 1487x 1487x 1487x 1420x 1420x 1484x 1420x 1487x 1420x 1420x 1420x 1420x 1487x 1420x 1420x 1487x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 419x 419x 419x 419x 384x 384x 384x 384x 384x 414x 396x 396x 396x 396x 384x 384x 419x 43x 43x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 805x 43x 43x 180x 180x 180x 180x 180x 180x 180x 180x 180x 180x 180x 180x 180x 180x 650x 650x 650x 650x       650x 180x 180x 180x 180x 180x 43x 43x 339x 339x 339x 339x 339x 339x 339x 339x 339x 43x 43x 43x 43x 43x 43x 1095x 1095x 3x 3x 1092x 1092x 1092x 1092x 1092x 1092x 1092x 1092x 1095x 337x 337x 337x 337x 337x 755x 755x 755x 755x 755x 755x 1091x 13x 1095x 12x 742x 730x 730x 755x 755x 755x 755x 755x 43x 43x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 28x 28x 6x 28x 3x 22x 5x 5x 28x 6x 6x 6x 6x 6x 6x 6x 1x 6x 5x 5x 6x 6x 43x 43x 230x 230x 230x 229x 229x 229x 230x 43x 208x 208x 208x 207x 207x 207x 208x 43x 43x 43x 43x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 171x 171x 175x 6x 6x 175x 175x 43x 43x 43x                                                                     43x 8347x 8347x 3x 3x 8344x 8347x 805120x 180x 180x 3x 3x 3x 3x 180x 805120x 8341x 8347x 43x 8360x 8360x 8360x 7685x 7685x 8354x 8360x 8360x 8360x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 42244x 42244x 42244x 42244x 42244x 42244x 42244x 42244x 42244x 42244x 42244x 42244x 42244x 42244x 43x 42248x 42248x 42248x                                         42247x 42247x 42247x 42247x 42247x 42247x 42247x 42247x 42247x 42244x 42244x 42244x 42248x 43x 173903x 173903x 173903x 43x 164900x 164900x 164900x 1271x 164900x 43x                                           43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x  
'use strict';
 
const {
  Array,
  ArrayPrototypeJoin,
  ArrayPrototypeMap,
  ArrayPrototypePush,
  ArrayPrototypeReduce,
  ArrayPrototypeSlice,
  FunctionPrototypeBind,
  Int8Array,
  Number,
  ObjectCreate,
  ObjectDefineProperties,
  ObjectDefineProperty,
  ObjectGetOwnPropertySymbols,
  ObjectGetPrototypeOf,
  ObjectKeys,
  ReflectApply,
  ReflectGetOwnPropertyDescriptor,
  ReflectOwnKeys,
  String,
  StringPrototypeCharCodeAt,
  StringPrototypeIncludes,
  StringPrototypeReplace,
  StringPrototypeSlice,
  StringPrototypeSplit,
  StringPrototypeStartsWith,
  Symbol,
  SymbolIterator,
  SymbolToStringTag,
  decodeURIComponent,
} = primordials;
 
const { inspect } = require('internal/util/inspect');
const {
  encodeStr,
  hexTable,
  isHexTable
} = require('internal/querystring');
 
const {
  getConstructorOf,
  removeColors,
  toUSVString,
  kEnumerableProperty,
} = require('internal/util');
 
const {
  codes: {
    ERR_ARG_NOT_ITERABLE,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
    ERR_INVALID_FILE_URL_HOST,
    ERR_INVALID_FILE_URL_PATH,
    ERR_INVALID_THIS,
    ERR_INVALID_TUPLE,
    ERR_INVALID_URL,
    ERR_INVALID_URL_SCHEME,
    ERR_MISSING_ARGS,
    ERR_NO_CRYPTO,
  },
} = require('internal/errors');
const {
  CHAR_AMPERSAND,
  CHAR_BACKWARD_SLASH,
  CHAR_EQUAL,
  CHAR_FORWARD_SLASH,
  CHAR_LOWERCASE_A,
  CHAR_LOWERCASE_Z,
  CHAR_PERCENT,
  CHAR_PLUS
} = require('internal/constants');
const path = require('path');
 
const {
  validateFunction,
  validateObject,
} = require('internal/validators');
 
const querystring = require('querystring');
 
const { platform } = process;
const isWindows = platform === 'win32';
 
const {
  domainToASCII: _domainToASCII,
  domainToUnicode: _domainToUnicode,
  encodeAuth,
  parse,
  setURLConstructor,
  URL_FLAGS_CANNOT_BE_BASE,
  URL_FLAGS_HAS_FRAGMENT,
  URL_FLAGS_HAS_HOST,
  URL_FLAGS_HAS_PASSWORD,
  URL_FLAGS_HAS_PATH,
  URL_FLAGS_HAS_QUERY,
  URL_FLAGS_HAS_USERNAME,
  URL_FLAGS_IS_DEFAULT_SCHEME_PORT,
  URL_FLAGS_SPECIAL,
  kFragment,
  kHost,
  kHostname,
  kPathStart,
  kPort,
  kQuery,
  kSchemeStart
} = internalBinding('url');
 
const {
  storeDataObject,
  revokeDataObject,
} = internalBinding('blob');
 
const context = Symbol('context');
const cannotBeBase = Symbol('cannot-be-base');
const cannotHaveUsernamePasswordPort =
    Symbol('cannot-have-username-password-port');
const special = Symbol('special');
const searchParams = Symbol('query');
const kFormat = Symbol('format');
 
let blob;
let cryptoRandom;
 
function lazyBlob() {
  blob ??= require('internal/blob');
  return blob;
}
 
function lazyCryptoRandom() {
  try {
    cryptoRandom ??= require('internal/crypto/random');
  } catch {
    // If Node.js built without crypto support, we'll fall
    // through here and handle it later.
  }
  return cryptoRandom;
}
 
// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
const IteratorPrototype = ObjectGetPrototypeOf(
  ObjectGetPrototypeOf([][SymbolIterator]())
);
 
// Refs: https://html.spec.whatwg.org/multipage/browsers.html#concept-origin-opaque
const kOpaqueOrigin = 'null';
 
// Refs: https://html.spec.whatwg.org/multipage/browsers.html#ascii-serialisation-of-an-origin
function serializeTupleOrigin(scheme, host, port) {
  return `${scheme}//${host}${port === null ? '' : `:${port}`}`;
}
 
// This class provides the internal state of a URL object. An instance of this
// class is stored in every URL object and is accessed internally by setters
// and getters. It roughly corresponds to the concept of a URL record in the
// URL Standard, with a few differences. It is also the object transported to
// the C++ binding.
// Refs: https://url.spec.whatwg.org/#concept-url
class URLContext {
  constructor() {
    this.flags = 0;
    this.scheme = ':';
    this.username = '';
    this.password = '';
    this.host = null;
    this.port = null;
    this.path = [];
    this.query = null;
    this.fragment = null;
  }
}
 
function isURLSearchParams(self) {
  return self && self[searchParams] && !self[searchParams][searchParams];
}
 
class URLSearchParams {
  // URL Standard says the default value is '', but as undefined and '' have
  // the same result, undefined is used to prevent unnecessary parsing.
  // Default parameter is necessary to keep URLSearchParams.length === 0 in
  // accordance with Web IDL spec.
  constructor(init = undefined) {
    if (init === null || init === undefined) {
      this[searchParams] = [];
    } else if (typeof init === 'object' || typeof init === 'function') {
      const method = init[SymbolIterator];
      if (method === this[SymbolIterator]) {
        // While the spec does not have this branch, we can use it as a
        // shortcut to avoid having to go through the costly generic iterator.
        const childParams = init[searchParams];
        this[searchParams] = childParams.slice();
      } else if (method !== null && method !== undefined) {
        if (typeof method !== 'function') {
          throw new ERR_ARG_NOT_ITERABLE('Query pairs');
        }
 
        // Sequence<sequence<USVString>>
        // Note: per spec we have to first exhaust the lists then process them
        const pairs = [];
        for (const pair of init) {
          if ((typeof pair !== 'object' && typeof pair !== 'function') ||
              pair === null ||
              typeof pair[SymbolIterator] !== 'function') {
            throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]');
          }
          const convertedPair = [];
          for (const element of pair)
            ArrayPrototypePush(convertedPair, toUSVString(element));
          ArrayPrototypePush(pairs, convertedPair);
        }
 
        this[searchParams] = [];
        for (const pair of pairs) {
          if (pair.length !== 2) {
            throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]');
          }
          ArrayPrototypePush(this[searchParams], pair[0], pair[1]);
        }
      } else {
        // Record<USVString, USVString>
        // Need to use reflection APIs for full spec compliance.
        const visited = {};
        this[searchParams] = [];
        const keys = ReflectOwnKeys(init);
        for (let i = 0; i < keys.length; i++) {
          const key = keys[i];
          const desc = ReflectGetOwnPropertyDescriptor(init, key);
          if (desc !== undefined && desc.enumerable) {
            const typedKey = toUSVString(key);
            const typedValue = toUSVString(init[key]);
 
            // Two different key may result same after `toUSVString()`, we only
            // leave the later one. Refers to WPT.
            if (visited[typedKey] !== undefined) {
              this[searchParams][visited[typedKey]] = typedValue;
            } else {
              visited[typedKey] = ArrayPrototypePush(this[searchParams],
                                                     typedKey,
                                                     typedValue) - 1;
            }
          }
        }
      }
    } else {
      // USVString
      init = toUSVString(init);
      if (init[0] === '?') init = init.slice(1);
      initSearchParams(this, init);
    }
 
    // "associated url object"
    this[context] = null;
  }
 
  [inspect.custom](recurseTimes, ctx) {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    if (typeof recurseTimes === 'number' && recurseTimes < 0)
      return ctx.stylize('[Object]', 'special');
 
    const separator = ', ';
    const innerOpts = { ...ctx };
    if (recurseTimes !== null) {
      innerOpts.depth = recurseTimes - 1;
    }
    const innerInspect = (v) => inspect(v, innerOpts);
 
    const list = this[searchParams];
    const output = [];
    for (let i = 0; i < list.length; i += 2)
      ArrayPrototypePush(
        output,
        `${innerInspect(list[i])} => ${innerInspect(list[i + 1])}`);
 
    const length = ArrayPrototypeReduce(
      output,
      (prev, cur) => prev + removeColors(cur).length + separator.length,
      -separator.length
    );
    if (length > ctx.breakLength) {
      return `${this.constructor.name} {\n` +
      `  ${ArrayPrototypeJoin(output, ',\n  ')} }`;
    } else if (output.length) {
      return `${this.constructor.name} { ` +
      `${ArrayPrototypeJoin(output, separator)} }`;
    }
    return `${this.constructor.name} {}`;
  }
 
  append(name, value) {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    if (arguments.length < 2) {
      throw new ERR_MISSING_ARGS('name', 'value');
    }
 
    name = toUSVString(name);
    value = toUSVString(value);
    ArrayPrototypePush(this[searchParams], name, value);
    update(this[context], this);
  }
 
  delete(name) {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    if (arguments.length < 1) {
      throw new ERR_MISSING_ARGS('name');
    }
 
    const list = this[searchParams];
    name = toUSVString(name);
    for (let i = 0; i < list.length;) {
      const cur = list[i];
      if (cur === name) {
        list.splice(i, 2);
      } else {
        i += 2;
      }
    }
    update(this[context], this);
  }
 
  get(name) {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    if (arguments.length < 1) {
      throw new ERR_MISSING_ARGS('name');
    }
 
    const list = this[searchParams];
    name = toUSVString(name);
    for (let i = 0; i < list.length; i += 2) {
      if (list[i] === name) {
        return list[i + 1];
      }
    }
    return null;
  }
 
  getAll(name) {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    if (arguments.length < 1) {
      throw new ERR_MISSING_ARGS('name');
    }
 
    const list = this[searchParams];
    const values = [];
    name = toUSVString(name);
    for (let i = 0; i < list.length; i += 2) {
      if (list[i] === name) {
        values.push(list[i + 1]);
      }
    }
    return values;
  }
 
  has(name) {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    if (arguments.length < 1) {
      throw new ERR_MISSING_ARGS('name');
    }
 
    const list = this[searchParams];
    name = toUSVString(name);
    for (let i = 0; i < list.length; i += 2) {
      if (list[i] === name) {
        return true;
      }
    }
    return false;
  }
 
  set(name, value) {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    if (arguments.length < 2) {
      throw new ERR_MISSING_ARGS('name', 'value');
    }
 
    const list = this[searchParams];
    name = toUSVString(name);
    value = toUSVString(value);
 
    // If there are any name-value pairs whose name is `name`, in `list`, set
    // the value of the first such name-value pair to `value` and remove the
    // others.
    let found = false;
    for (let i = 0; i < list.length;) {
      const cur = list[i];
      if (cur === name) {
        if (!found) {
          list[i + 1] = value;
          found = true;
          i += 2;
        } else {
          list.splice(i, 2);
        }
      } else {
        i += 2;
      }
    }
 
    // Otherwise, append a new name-value pair whose name is `name` and value
    // is `value`, to `list`.
    if (!found) {
      ArrayPrototypePush(list, name, value);
    }
 
    update(this[context], this);
  }
 
  sort() {
    const a = this[searchParams];
    const len = a.length;
 
    if (len <= 2) {
      // Nothing needs to be done.
    } else if (len < 100) {
      // 100 is found through testing.
      // Simple stable in-place insertion sort
      // Derived from v8/src/js/array.js
      for (let i = 2; i < len; i += 2) {
        const curKey = a[i];
        const curVal = a[i + 1];
        let j;
        for (j = i - 2; j >= 0; j -= 2) {
          if (a[j] > curKey) {
            a[j + 2] = a[j];
            a[j + 3] = a[j + 1];
          } else {
            break;
          }
        }
        a[j + 2] = curKey;
        a[j + 3] = curVal;
      }
    } else {
      // Bottom-up iterative stable merge sort
      const lBuffer = new Array(len);
      const rBuffer = new Array(len);
      for (let step = 2; step < len; step *= 2) {
        for (let start = 0; start < len - 2; start += 2 * step) {
          const mid = start + step;
          let end = mid + step;
          end = end < len ? end : len;
          if (mid > end)
            continue;
          merge(a, start, mid, end, lBuffer, rBuffer);
        }
      }
    }
 
    update(this[context], this);
  }
 
  // https://heycam.github.io/webidl/#es-iterators
  // Define entries here rather than [Symbol.iterator] as the function name
  // must be set to `entries`.
  entries() {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    return createSearchParamsIterator(this, 'key+value');
  }
 
  forEach(callback, thisArg = undefined) {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    validateFunction(callback, 'callback');
 
    let list = this[searchParams];
 
    let i = 0;
    while (i < list.length) {
      const key = list[i];
      const value = list[i + 1];
      callback.call(thisArg, value, key, this);
      // In case the URL object's `search` is updated
      list = this[searchParams];
      i += 2;
    }
  }
 
  // https://heycam.github.io/webidl/#es-iterable
  keys() {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    return createSearchParamsIterator(this, 'key');
  }
 
  values() {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    return createSearchParamsIterator(this, 'value');
  }
 
  // https://heycam.github.io/webidl/#es-stringifier
  // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
  toString() {
    if (!isURLSearchParams(this))
      throw new ERR_INVALID_THIS('URLSearchParams');
 
    return serializeParams(this[searchParams]);
  }
}
 
ObjectDefineProperties(URLSearchParams.prototype, {
  append: kEnumerableProperty,
  delete: kEnumerableProperty,
  get: kEnumerableProperty,
  getAll: kEnumerableProperty,
  has: kEnumerableProperty,
  set: kEnumerableProperty,
  sort: kEnumerableProperty,
  entries: kEnumerableProperty,
  forEach: kEnumerableProperty,
  keys: kEnumerableProperty,
  values: kEnumerableProperty,
  toString: kEnumerableProperty,
  [SymbolToStringTag]: { __proto__: null, configurable: true, value: 'URLSearchParams' },
 
  // https://heycam.github.io/webidl/#es-iterable-entries
  [SymbolIterator]: {
    __proto__: null,
    configurable: true,
    writable: true,
    value: URLSearchParams.prototype.entries,
  },
});
 
function onParseComplete(flags, protocol, username, password,
                         host, port, path, query, fragment) {
  const ctx = this[context];
  ctx.flags = flags;
  ctx.scheme = protocol;
  ctx.username = (flags & URL_FLAGS_HAS_USERNAME) !== 0 ? username : '';
  ctx.password = (flags & URL_FLAGS_HAS_PASSWORD) !== 0 ? password : '';
  ctx.port = port;
  ctx.path = (flags & URL_FLAGS_HAS_PATH) !== 0 ? path : [];
  ctx.query = query;
  ctx.fragment = fragment;
  ctx.host = host;
  if (!this[searchParams]) { // Invoked from URL constructor
    this[searchParams] = new URLSearchParams();
    this[searchParams][context] = this;
  }
  initSearchParams(this[searchParams], query);
}
 
function onParseError(input, flags) {
  throw new ERR_INVALID_URL(input);
}
 
function onParseProtocolComplete(flags, protocol, username, password,
                                 host, port, path, query, fragment) {
  const ctx = this[context];
  if ((flags & URL_FLAGS_SPECIAL) !== 0) {
    ctx.flags |= URL_FLAGS_SPECIAL;
  } else {
    ctx.flags &= ~URL_FLAGS_SPECIAL;
  }
  ctx.scheme = protocol;
  ctx.port = port;
}
 
function onParseHostnameComplete(flags, protocol, username, password,
                                 host, port, path, query, fragment) {
  const ctx = this[context];
  if ((flags & URL_FLAGS_HAS_HOST) !== 0) {
    ctx.host = host;
    ctx.flags |= URL_FLAGS_HAS_HOST;
  } else {
    ctx.host = null;
    ctx.flags &= ~URL_FLAGS_HAS_HOST;
  }
}
 
function onParsePortComplete(flags, protocol, username, password,
                             host, port, path, query, fragment) {
  this[context].port = port;
}
 
function onParseHostComplete(flags, protocol, username, password,
                             host, port, path, query, fragment) {
  ReflectApply(onParseHostnameComplete, this, arguments);
  if (port !== null || ((flags & URL_FLAGS_IS_DEFAULT_SCHEME_PORT) !== 0))
    ReflectApply(onParsePortComplete, this, arguments);
}
 
function onParsePathComplete(flags, protocol, username, password,
                             host, port, path, query, fragment) {
  const ctx = this[context];
  if ((flags & URL_FLAGS_HAS_PATH) !== 0) {
    ctx.path = path;
    ctx.flags |= URL_FLAGS_HAS_PATH;
  } else {
    ctx.path = [];
    ctx.flags &= ~URL_FLAGS_HAS_PATH;
  }
 
  // The C++ binding may set host to empty string.
  if ((flags & URL_FLAGS_HAS_HOST) !== 0) {
    ctx.host = host;
    ctx.flags |= URL_FLAGS_HAS_HOST;
  }
}
 
function onParseSearchComplete(flags, protocol, username, password,
                               host, port, path, query, fragment) {
  this[context].query = query;
}
 
function onParseHashComplete(flags, protocol, username, password,
                             host, port, path, query, fragment) {
  this[context].fragment = fragment;
}
 
function isURLThis(self) {
  return (self !== undefined && self !== null && self[context] !== undefined);
}
 
class URL {
  constructor(input, base = undefined) {
    // toUSVString is not needed.
    input = `${input}`;
    let base_context;
    if (base !== undefined) {
      base_context = new URL(base)[context];
    }
    this[context] = new URLContext();
    parse(input, -1, base_context, undefined,
          FunctionPrototypeBind(onParseComplete, this),
          FunctionPrototypeBind(onParseError, this, input));
  }
 
  get [special]() {
    return (this[context].flags & URL_FLAGS_SPECIAL) !== 0;
  }
 
  get [cannotBeBase]() {
    return (this[context].flags & URL_FLAGS_CANNOT_BE_BASE) !== 0;
  }
 
  // https://url.spec.whatwg.org/#cannot-have-a-username-password-port
  get [cannotHaveUsernamePasswordPort]() {
    const { host, scheme } = this[context];
    return ((host == null || host === '') ||
            this[cannotBeBase] ||
            scheme === 'file:');
  }
 
  [inspect.custom](depth, opts) {
    if (this == null ||
        ObjectGetPrototypeOf(this[context]) !== URLContext.prototype) {
      throw new ERR_INVALID_THIS('URL');
    }
 
    if (typeof depth === 'number' && depth < 0)
      return this;
 
    const constructor = getConstructorOf(this) || URL;
    const obj = ObjectCreate({ constructor });
 
    obj.href = this.href;
    obj.origin = this.origin;
    obj.protocol = this.protocol;
    obj.username = this.username;
    obj.password = this.password;
    obj.host = this.host;
    obj.hostname = this.hostname;
    obj.port = this.port;
    obj.pathname = this.pathname;
    obj.search = this.search;
    obj.searchParams = this.searchParams;
    obj.hash = this.hash;
 
    if (opts.showHidden) {
      obj.cannotBeBase = this[cannotBeBase];
      obj.special = this[special];
      obj[context] = this[context];
    }
 
    return `${constructor.name} ${inspect(obj, opts)}`;
  }
 
  [kFormat](options) {
    if (options)
      validateObject(options, 'options');
 
    options = {
      fragment: true,
      unicode: false,
      search: true,
      auth: true,
      ...options
    };
    const ctx = this[context];
    // https://url.spec.whatwg.org/#url-serializing
    let ret = ctx.scheme;
    if (ctx.host !== null) {
      ret += '//';
      const has_username = ctx.username !== '';
      const has_password = ctx.password !== '';
      if (options.auth && (has_username || has_password)) {
        if (has_username)
          ret += ctx.username;
        if (has_password)
          ret += `:${ctx.password}`;
        ret += '@';
      }
      ret += options.unicode ?
        domainToUnicode(ctx.host) : ctx.host;
      if (ctx.port !== null)
        ret += `:${ctx.port}`;
    }
    if (this[cannotBeBase]) {
      ret += ctx.path[0];
    } else {
      if (ctx.host === null && ctx.path.length > 1 && ctx.path[0] === '') {
        ret += '/.';
      }
      if (ctx.path.length) {
        ret += '/' + ArrayPrototypeJoin(ctx.path, '/');
      }
    }
    if (options.search && ctx.query !== null)
      ret += `?${ctx.query}`;
    if (options.fragment && ctx.fragment !== null)
      ret += `#${ctx.fragment}`;
    return ret;
  }
 
  // https://heycam.github.io/webidl/#es-stringifier
  toString() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    return this[kFormat]({});
  }
 
  get href() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    return this[kFormat]({});
  }
 
  set href(input) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    // toUSVString is not needed.
    input = `${input}`;
    parse(input, -1, undefined, undefined,
          FunctionPrototypeBind(onParseComplete, this),
          FunctionPrototypeBind(onParseError, this, input));
  }
 
  // readonly
  get origin() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    // Refs: https://url.spec.whatwg.org/#concept-url-origin
    const ctx = this[context];
    switch (ctx.scheme) {
      case 'blob:':
        if (ctx.path.length > 0) {
          try {
            return (new URL(ctx.path[0])).origin;
          } catch {
            // Fall through... do nothing
          }
        }
        return kOpaqueOrigin;
      case 'ftp:':
      case 'http:':
      case 'https:':
      case 'ws:':
      case 'wss:':
        return serializeTupleOrigin(ctx.scheme, ctx.host, ctx.port);
    }
    return kOpaqueOrigin;
  }
 
  get protocol() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    return this[context].scheme;
  }
 
  set protocol(scheme) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    // toUSVString is not needed.
    scheme = `${scheme}`;
    if (scheme.length === 0)
      return;
    const ctx = this[context];
    parse(scheme, kSchemeStart, null, ctx,
          FunctionPrototypeBind(onParseProtocolComplete, this));
  }
 
  get username() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    return this[context].username;
  }
 
  set username(username) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    // toUSVString is not needed.
    username = `${username}`;
    if (this[cannotHaveUsernamePasswordPort])
      return;
    const ctx = this[context];
    if (username === '') {
      ctx.username = '';
      ctx.flags &= ~URL_FLAGS_HAS_USERNAME;
      return;
    }
    ctx.username = encodeAuth(username);
    ctx.flags |= URL_FLAGS_HAS_USERNAME;
  }
 
  get password() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    return this[context].password;
  }
 
  set password(password) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    // toUSVString is not needed.
    password = `${password}`;
    if (this[cannotHaveUsernamePasswordPort])
      return;
    const ctx = this[context];
    if (password === '') {
      ctx.password = '';
      ctx.flags &= ~URL_FLAGS_HAS_PASSWORD;
      return;
    }
    ctx.password = encodeAuth(password);
    ctx.flags |= URL_FLAGS_HAS_PASSWORD;
  }
 
  get host() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const ctx = this[context];
    let ret = ctx.host || '';
    if (ctx.port !== null)
      ret += `:${ctx.port}`;
    return ret;
  }
 
  set host(host) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const ctx = this[context];
    // toUSVString is not needed.
    host = `${host}`;
    if (this[cannotBeBase]) {
      // Cannot set the host if cannot-be-base is set
      return;
    }
    parse(host, kHost, null, ctx,
          FunctionPrototypeBind(onParseHostComplete, this));
  }
 
  get hostname() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    return this[context].host || '';
  }
 
  set hostname(host) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const ctx = this[context];
    // toUSVString is not needed.
    host = `${host}`;
    if (this[cannotBeBase]) {
      // Cannot set the host if cannot-be-base is set
      return;
    }
    parse(host, kHostname, null, ctx, onParseHostnameComplete.bind(this));
  }
 
  get port() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const port = this[context].port;
    return port === null ? '' : String(port);
  }
 
  set port(port) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    // toUSVString is not needed.
    port = `${port}`;
    if (this[cannotHaveUsernamePasswordPort])
      return;
    const ctx = this[context];
    if (port === '') {
      ctx.port = null;
      return;
    }
    parse(port, kPort, null, ctx,
          FunctionPrototypeBind(onParsePortComplete, this));
  }
 
  get pathname() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const ctx = this[context];
    if (this[cannotBeBase])
      return ctx.path[0];
    if (ctx.path.length === 0)
      return '';
    return `/${ArrayPrototypeJoin(ctx.path, '/')}`;
  }
 
  set pathname(path) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    // toUSVString is not needed.
    path = `${path}`;
    if (this[cannotBeBase])
      return;
    parse(path, kPathStart, null, this[context],
          onParsePathComplete.bind(this));
  }
 
  get search() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const { query } = this[context];
    if (query === null || query === '')
      return '';
    return `?${query}`;
  }
 
  set search(search) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const ctx = this[context];
    search = toUSVString(search);
    if (search === '') {
      ctx.query = null;
      ctx.flags &= ~URL_FLAGS_HAS_QUERY;
    } else {
      if (search[0] === '?') search = StringPrototypeSlice(search, 1);
      ctx.query = '';
      ctx.flags |= URL_FLAGS_HAS_QUERY;
      if (search) {
        parse(search, kQuery, null, ctx,
              FunctionPrototypeBind(onParseSearchComplete, this));
      }
    }
    initSearchParams(this[searchParams], search);
  }
 
  // readonly
  get searchParams() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    return this[searchParams];
  }
 
  get hash() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const { fragment } = this[context];
    if (fragment === null || fragment === '')
      return '';
    return `#${fragment}`;
  }
 
  set hash(hash) {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    const ctx = this[context];
    // toUSVString is not needed.
    hash = `${hash}`;
    if (!hash) {
      ctx.fragment = null;
      ctx.flags &= ~URL_FLAGS_HAS_FRAGMENT;
      return;
    }
    if (hash[0] === '#') hash = StringPrototypeSlice(hash, 1);
    ctx.fragment = '';
    ctx.flags |= URL_FLAGS_HAS_FRAGMENT;
    parse(hash, kFragment, null, ctx,
          FunctionPrototypeBind(onParseHashComplete, this));
  }
 
  toJSON() {
    if (!isURLThis(this))
      throw new ERR_INVALID_THIS('URL');
    return this[kFormat]({});
  }
 
  static createObjectURL(obj) {
    const cryptoRandom = lazyCryptoRandom();
    if (cryptoRandom === undefined)
      throw new ERR_NO_CRYPTO();
 
    // Yes, lazy loading is annoying but because of circular
    // references between the url, internal/blob, and buffer
    // modules, lazy loading here makes sure that things work.
    const blob = lazyBlob();
    if (!blob.isBlob(obj))
      throw new ERR_INVALID_ARG_TYPE('obj', 'Blob', obj);
 
    const id = cryptoRandom.randomUUID();
 
    storeDataObject(id, obj[blob.kHandle], obj.size, obj.type);
 
    return `blob:nodedata:${id}`;
  }
 
  static revokeObjectURL(url) {
    url = `${url}`;
    try {
      const parsed = new URL(url);
      const split = StringPrototypeSplit(parsed.pathname, ':');
      if (split.length === 2)
        revokeDataObject(split[1]);
    } catch {
      // If there's an error, it's ignored.
    }
  }
}
 
ObjectDefineProperties(URL.prototype, {
  [kFormat]: { __proto__: null, configurable: false, writable: false },
  [SymbolToStringTag]: { __proto__: null, configurable: true, value: 'URL' },
  toString: kEnumerableProperty,
  href: kEnumerableProperty,
  origin: kEnumerableProperty,
  protocol: kEnumerableProperty,
  username: kEnumerableProperty,
  password: kEnumerableProperty,
  host: kEnumerableProperty,
  hostname: kEnumerableProperty,
  port: kEnumerableProperty,
  pathname: kEnumerableProperty,
  search: kEnumerableProperty,
  searchParams: kEnumerableProperty,
  hash: kEnumerableProperty,
  toJSON: kEnumerableProperty,
});
 
function update(url, params) {
  if (!url)
    return;
 
  const ctx = url[context];
  const serializedParams = params.toString();
  if (serializedParams) {
    ctx.query = serializedParams;
    ctx.flags |= URL_FLAGS_HAS_QUERY;
  } else {
    ctx.query = null;
    ctx.flags &= ~URL_FLAGS_HAS_QUERY;
  }
}
 
function initSearchParams(url, init) {
  if (!init) {
    url[searchParams] = [];
    return;
  }
  url[searchParams] = parseParams(init);
}
 
// application/x-www-form-urlencoded parser
// Ref: https://url.spec.whatwg.org/#concept-urlencoded-parser
function parseParams(qs) {
  const out = [];
  let pairStart = 0;
  let lastPos = 0;
  let seenSep = false;
  let buf = '';
  let encoded = false;
  let encodeCheck = 0;
  let i;
  for (i = 0; i < qs.length; ++i) {
    const code = StringPrototypeCharCodeAt(qs, i);
 
    // Try matching key/value pair separator
    if (code === CHAR_AMPERSAND) {
      if (pairStart === i) {
        // We saw an empty substring between pair separators
        lastPos = pairStart = i + 1;
        continue;
      }
 
      if (lastPos < i)
        buf += qs.slice(lastPos, i);
      if (encoded)
        buf = querystring.unescape(buf);
      out.push(buf);
 
      // If `buf` is the key, add an empty value.
      if (!seenSep)
        out.push('');
 
      seenSep = false;
      buf = '';
      encoded = false;
      encodeCheck = 0;
      lastPos = pairStart = i + 1;
      continue;
    }
 
    // Try matching key/value separator (e.g. '=') if we haven't already
    if (!seenSep && code === CHAR_EQUAL) {
      // Key/value separator match!
      if (lastPos < i)
        buf += qs.slice(lastPos, i);
      if (encoded)
        buf = querystring.unescape(buf);
      out.push(buf);
 
      seenSep = true;
      buf = '';
      encoded = false;
      encodeCheck = 0;
      lastPos = i + 1;
      continue;
    }
 
    // Handle + and percent decoding.
    if (code === CHAR_PLUS) {
      if (lastPos < i)
        buf += StringPrototypeSlice(qs, lastPos, i);
      buf += ' ';
      lastPos = i + 1;
    } else if (!encoded) {
      // Try to match an (valid) encoded byte (once) to minimize unnecessary
      // calls to string decoding functions
      if (code === CHAR_PERCENT) {
        encodeCheck = 1;
      } else if (encodeCheck > 0) {
        if (isHexTable[code] === 1) {
          if (++encodeCheck === 3) {
            encoded = true;
          }
        } else {
          encodeCheck = 0;
        }
      }
    }
  }
 
  // Deal with any leftover key or value data
 
  // There is a trailing &. No more processing is needed.
  if (pairStart === i)
    return out;
 
  if (lastPos < i)
    buf += StringPrototypeSlice(qs, lastPos, i);
  if (encoded)
    buf = querystring.unescape(buf);
  ArrayPrototypePush(out, buf);
 
  // If `buf` is the key, add an empty value.
  if (!seenSep)
    ArrayPrototypePush(out, '');
 
  return out;
}
 
// Adapted from querystring's implementation.
// Ref: https://url.spec.whatwg.org/#concept-urlencoded-byte-serializer
const noEscape = new Int8Array([
/*
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
*/
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x00 - 0x0F
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10 - 0x1F
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, // 0x20 - 0x2F
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 0x30 - 0x3F
  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40 - 0x4F
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 0x50 - 0x5F
  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60 - 0x6F
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  // 0x70 - 0x7F
]);
 
// Special version of hexTable that uses `+` for U+0020 SPACE.
const paramHexTable = hexTable.slice();
paramHexTable[0x20] = '+';
 
// application/x-www-form-urlencoded serializer
// Ref: https://url.spec.whatwg.org/#concept-urlencoded-serializer
function serializeParams(array) {
  const len = array.length;
  if (len === 0)
    return '';
 
  const firstEncodedParam = encodeStr(array[0], noEscape, paramHexTable);
  const firstEncodedValue = encodeStr(array[1], noEscape, paramHexTable);
  let output = `${firstEncodedParam}=${firstEncodedValue}`;
 
  for (let i = 2; i < len; i += 2) {
    const encodedParam = encodeStr(array[i], noEscape, paramHexTable);
    const encodedValue = encodeStr(array[i + 1], noEscape, paramHexTable);
    output += `&${encodedParam}=${encodedValue}`;
  }
 
  return output;
}
 
// Mainly to mitigate func-name-matching ESLint rule
function defineIDLClass(proto, classStr, obj) {
  // https://heycam.github.io/webidl/#dfn-class-string
  ObjectDefineProperty(proto, SymbolToStringTag, {
    __proto__: null,
    writable: false,
    enumerable: false,
    configurable: true,
    value: classStr
  });
 
  // https://heycam.github.io/webidl/#es-operations
  for (const key of ObjectKeys(obj)) {
    ObjectDefineProperty(proto, key, {
      __proto__: null,
      writable: true,
      enumerable: true,
      configurable: true,
      value: obj[key]
    });
  }
  for (const key of ObjectGetOwnPropertySymbols(obj)) {
    ObjectDefineProperty(proto, key, {
      __proto__: null,
      writable: true,
      enumerable: false,
      configurable: true,
      value: obj[key]
    });
  }
}
 
// for merge sort
function merge(out, start, mid, end, lBuffer, rBuffer) {
  const sizeLeft = mid - start;
  const sizeRight = end - mid;
  let l, r, o;
 
  for (l = 0; l < sizeLeft; l++)
    lBuffer[l] = out[start + l];
  for (r = 0; r < sizeRight; r++)
    rBuffer[r] = out[mid + r];
 
  l = 0;
  r = 0;
  o = start;
  while (l < sizeLeft && r < sizeRight) {
    if (lBuffer[l] <= rBuffer[r]) {
      out[o++] = lBuffer[l++];
      out[o++] = lBuffer[l++];
    } else {
      out[o++] = rBuffer[r++];
      out[o++] = rBuffer[r++];
    }
  }
  while (l < sizeLeft)
    out[o++] = lBuffer[l++];
  while (r < sizeRight)
    out[o++] = rBuffer[r++];
}
 
// https://heycam.github.io/webidl/#dfn-default-iterator-object
function createSearchParamsIterator(target, kind) {
  const iterator = ObjectCreate(URLSearchParamsIteratorPrototype);
  iterator[context] = {
    target,
    kind,
    index: 0
  };
  return iterator;
}
 
// https://heycam.github.io/webidl/#dfn-iterator-prototype-object
const URLSearchParamsIteratorPrototype = ObjectCreate(IteratorPrototype);
 
defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', {
  next() {
    if (!this ||
        ObjectGetPrototypeOf(this) !== URLSearchParamsIteratorPrototype) {
      throw new ERR_INVALID_THIS('URLSearchParamsIterator');
    }
 
    const {
      target,
      kind,
      index
    } = this[context];
    const values = target[searchParams];
    const len = values.length;
    if (index >= len) {
      return {
        value: undefined,
        done: true
      };
    }
 
    const name = values[index];
    const value = values[index + 1];
    this[context].index = index + 2;
 
    let result;
    if (kind === 'key') {
      result = name;
    } else if (kind === 'value') {
      result = value;
    } else {
      result = [name, value];
    }
 
    return {
      value: result,
      done: false
    };
  },
  [inspect.custom](recurseTimes, ctx) {
    if (this == null || this[context] == null || this[context].target == null)
      throw new ERR_INVALID_THIS('URLSearchParamsIterator');
 
    if (typeof recurseTimes === 'number' && recurseTimes < 0)
      return ctx.stylize('[Object]', 'special');
 
    const innerOpts = { ...ctx };
    if (recurseTimes !== null) {
      innerOpts.depth = recurseTimes - 1;
    }
    const {
      target,
      kind,
      index
    } = this[context];
    const output = ArrayPrototypeReduce(
      ArrayPrototypeSlice(target[searchParams], index),
      (prev, cur, i) => {
        const key = i % 2 === 0;
        if (kind === 'key' && key) {
          ArrayPrototypePush(prev, cur);
        } else if (kind === 'value' && !key) {
          ArrayPrototypePush(prev, cur);
        } else if (kind === 'key+value' && !key) {
          ArrayPrototypePush(prev, [target[searchParams][index + i - 1], cur]);
        }
        return prev;
      },
      []
    );
    const breakLn = inspect(output, innerOpts).includes('\n');
    const outputStrs = ArrayPrototypeMap(output, (p) => inspect(p, innerOpts));
    let outputStr;
    if (breakLn) {
      outputStr = `\n  ${ArrayPrototypeJoin(outputStrs, ',\n  ')}`;
    } else {
      outputStr = ` ${ArrayPrototypeJoin(outputStrs, ', ')}`;
    }
    return `${this[SymbolToStringTag]} {${outputStr} }`;
  }
});
 
function domainToASCII(domain) {
  if (arguments.length < 1)
    throw new ERR_MISSING_ARGS('domain');
 
  // toUSVString is not needed.
  return _domainToASCII(`${domain}`);
}
 
function domainToUnicode(domain) {
  if (arguments.length < 1)
    throw new ERR_MISSING_ARGS('domain');
 
  // toUSVString is not needed.
  return _domainToUnicode(`${domain}`);
}
 
// Utility function that converts a URL object into an ordinary
// options object as expected by the http.request and https.request
// APIs.
function urlToHttpOptions(url) {
  const options = {
    protocol: url.protocol,
    hostname: typeof url.hostname === 'string' &&
              StringPrototypeStartsWith(url.hostname, '[') ?
      StringPrototypeSlice(url.hostname, 1, -1) :
      url.hostname,
    hash: url.hash,
    search: url.search,
    pathname: url.pathname,
    path: `${url.pathname || ''}${url.search || ''}`,
    href: url.href
  };
  if (url.port !== '') {
    options.port = Number(url.port);
  }
  if (url.username || url.password) {
    options.auth = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
  }
  return options;
}
 
const forwardSlashRegEx = /\//g;
 
function getPathFromURLWin32(url) {
  const hostname = url.hostname;
  let pathname = url.pathname;
  for (let n = 0; n < pathname.length; n++) {
    if (pathname[n] === '%') {
      const third = pathname.codePointAt(n + 2) | 0x20;
      if ((pathname[n + 1] === '2' && third === 102) || // 2f 2F /
          (pathname[n + 1] === '5' && third === 99)) {  // 5c 5C \
        throw new ERR_INVALID_FILE_URL_PATH(
          'must not include encoded \\ or / characters'
        );
      }
    }
  }
  pathname = pathname.replace(forwardSlashRegEx, '\\');
  pathname = decodeURIComponent(pathname);
  if (hostname !== '') {
    // If hostname is set, then we have a UNC path
    // Pass the hostname through domainToUnicode just in case
    // it is an IDN using punycode encoding. We do not need to worry
    // about percent encoding because the URL parser will have
    // already taken care of that for us. Note that this only
    // causes IDNs with an appropriate `xn--` prefix to be decoded.
    return `\\\\${domainToUnicode(hostname)}${pathname}`;
  }
  // Otherwise, it's a local path that requires a drive letter
  const letter = pathname.codePointAt(1) | 0x20;
  const sep = pathname[2];
  if (letter < CHAR_LOWERCASE_A || letter > CHAR_LOWERCASE_Z ||   // a..z A..Z
      (sep !== ':')) {
    throw new ERR_INVALID_FILE_URL_PATH('must be absolute');
  }
  return pathname.slice(1);
}
 
function getPathFromURLPosix(url) {
  if (url.hostname !== '') {
    throw new ERR_INVALID_FILE_URL_HOST(platform);
  }
  const pathname = url.pathname;
  for (let n = 0; n < pathname.length; n++) {
    if (pathname[n] === '%') {
      const third = pathname.codePointAt(n + 2) | 0x20;
      if (pathname[n + 1] === '2' && third === 102) {
        throw new ERR_INVALID_FILE_URL_PATH(
          'must not include encoded / characters'
        );
      }
    }
  }
  return decodeURIComponent(pathname);
}
 
function fileURLToPath(path) {
  if (typeof path === 'string')
    path = new URL(path);
  else if (!isURLInstance(path))
    throw new ERR_INVALID_ARG_TYPE('path', ['string', 'URL'], path);
  if (path.protocol !== 'file:')
    throw new ERR_INVALID_URL_SCHEME('file');
  return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path);
}
 
// The following characters are percent-encoded when converting from file path
// to URL:
// - %: The percent character is the only character not encoded by the
//        `pathname` setter.
// - \: Backslash is encoded on non-windows platforms since it's a valid
//      character but the `pathname` setters replaces it by a forward slash.
// - LF: The newline character is stripped out by the `pathname` setter.
//       (See whatwg/url#419)
// - CR: The carriage return character is also stripped out by the `pathname`
//       setter.
// - TAB: The tab character is also stripped out by the `pathname` setter.
const percentRegEx = /%/g;
const backslashRegEx = /\\/g;
const newlineRegEx = /\n/g;
const carriageReturnRegEx = /\r/g;
const tabRegEx = /\t/g;
 
function encodePathChars(filepath) {
  if (StringPrototypeIncludes(filepath, '%'))
    filepath = StringPrototypeReplace(filepath, percentRegEx, '%25');
  // In posix, backslash is a valid character in paths:
  if (!isWindows && StringPrototypeIncludes(filepath, '\\'))
    filepath = StringPrototypeReplace(filepath, backslashRegEx, '%5C');
  if (StringPrototypeIncludes(filepath, '\n'))
    filepath = StringPrototypeReplace(filepath, newlineRegEx, '%0A');
  if (StringPrototypeIncludes(filepath, '\r'))
    filepath = StringPrototypeReplace(filepath, carriageReturnRegEx, '%0D');
  if (StringPrototypeIncludes(filepath, '\t'))
    filepath = StringPrototypeReplace(filepath, tabRegEx, '%09');
  return filepath;
}
 
function pathToFileURL(filepath) {
  const outURL = new URL('file://');
  if (isWindows && StringPrototypeStartsWith(filepath, '\\\\')) {
    // UNC path format: \\server\share\resource
    const paths = StringPrototypeSplit(filepath, '\\');
    if (paths.length <= 3) {
      throw new ERR_INVALID_ARG_VALUE(
        'filepath',
        filepath,
        'Missing UNC resource path'
      );
    }
    const hostname = paths[2];
    if (hostname.length === 0) {
      throw new ERR_INVALID_ARG_VALUE(
        'filepath',
        filepath,
        'Empty UNC servername'
      );
    }
    outURL.hostname = domainToASCII(hostname);
    outURL.pathname = encodePathChars(
      ArrayPrototypeJoin(ArrayPrototypeSlice(paths, 3), '/'));
  } else {
    let resolved = path.resolve(filepath);
    // path.resolve strips trailing slashes so we must add them back
    const filePathLast = StringPrototypeCharCodeAt(filepath,
                                                   filepath.length - 1);
    if ((filePathLast === CHAR_FORWARD_SLASH ||
         (isWindows && filePathLast === CHAR_BACKWARD_SLASH)) &&
        resolved[resolved.length - 1] !== path.sep)
      resolved += '/';
    outURL.pathname = encodePathChars(resolved);
  }
  return outURL;
}
 
function isURLInstance(fileURLOrPath) {
  return fileURLOrPath != null && fileURLOrPath.href && fileURLOrPath.origin;
}
 
function toPathIfFileURL(fileURLOrPath) {
  if (!isURLInstance(fileURLOrPath))
    return fileURLOrPath;
  return fileURLToPath(fileURLOrPath);
}
 
function constructUrl(flags, protocol, username, password,
                      host, port, path, query, fragment) {
  const ctx = new URLContext();
  ctx.flags = flags;
  ctx.scheme = protocol;
  ctx.username = (flags & URL_FLAGS_HAS_USERNAME) !== 0 ? username : '';
  ctx.password = (flags & URL_FLAGS_HAS_PASSWORD) !== 0 ? password : '';
  ctx.port = port;
  ctx.path = (flags & URL_FLAGS_HAS_PATH) !== 0 ? path : [];
  ctx.query = query;
  ctx.fragment = fragment;
  ctx.host = host;

  const url = ObjectCreate(URL.prototype);
  url[context] = ctx;
  const params = new URLSearchParams();
  url[searchParams] = params;
  params[context] = url;
  initSearchParams(params, query);
  return url;
}
setURLConstructor(constructUrl);
 
module.exports = {
  toUSVString,
  fileURLToPath,
  pathToFileURL,
  toPathIfFileURL,
  isURLInstance,
  URL,
  URLSearchParams,
  domainToASCII,
  domainToUnicode,
  urlToHttpOptions,
  formatSymbol: kFormat,
  searchParamsSymbol: searchParams,
  encodeStr
};