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 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 | 1x 1x 1x 186x 186x 186x 186x 186x 186x 186x 186x 186x 186x 186x 1x 1x 319x 319x 319x 319x 319x 319x 319x 1x 1x 318x 318x 318x 319x 319x 319x 319x 319x 318x 318x 318x 318x 318x 318x 318x 318x 2x 318x 2x 2x 316x 318x 113x 318x 37x 318x 318x 318x 10x 10x 10x 10x 10x 10x 318x 6x 6x 318x 318x 17x 17x 17x 17x 318x 7x 318x 3x 3x 3x 3x 3x 3x 318x 318x 120x 120x 120x 118x 2x 2x 120x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 118x 120x 100x 100x 100x 93x 45x 10x 100x 10x 10x 12x 12x 12x 10x 10x 100x 100x 100x 100x 100x 100x 120x 16x 16x 4x 4x 4x 4x 4x 4x 4x 12x 12x 16x 8x 8x 8x 8x 8x 8x 8x 16x 2x 2x 2x 2x 2x 2x 2x 2x 2x 16x 2x 2x 2x 2x 2x 2x 120x 318x 2x 2x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 318x 1x 1x 1x 1x 1x 1x 318x 150x 150x 150x 150x 150x 150x 150x 150x 285x 271x 7x 7x 7x 7x 271x 271x 271x 269x 271x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 285x 14x 14x 285x 149x 149x 19x 19x 19x 19x 19x 18x 18x 19x 42x 47x 44x 47x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 47x 42x 2x 2x 42x 18x 18x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 8x 9x 9x 9x 8x 7x 7x 8x 9x 1x 1x 9x 1x 1x 1x 1x 1x 1x 9x 7x 36x 36x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 2x 2x 7x 5x 5x 7x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 7x 7x 16x 16x 16x 16x 16x 16x 4x 4x 12x 12x 12x 12x 16x 1x 1x 16x 11x 11x 11x 16x 12x 12x 12x 12x 12x 12x 12x 10x 10x 8x 8x 8x 8x 8x 8x 1x 1x 8x 2x 4x 2x 2x 5x 5x 1x 5x 4x 4x 4x 4x 4x 5x 100x 100x 100x 100x 100x 100x 100x 33x 100x 36x 100x 10x 100x 3x 3x 100x 18x 18x 13x 13x 5x 5x 4x 5x 5x 1x 5x 5x 1x 5x 5x 2x 5x 5x 1x 1x 1x 1x 1x 5x 5x 18x 100x 10x 10x 10x 10x 10x 10x 4x 4x 6x 6x 6x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 12x 16x 16x 12x 6x 6x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 3x 3x 5x 3x 3x 3x 8x 2x 2x 3x 2x 2x 2x 8x 1x 8x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 8x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 3x 1x 8x 260x 260x 260x 260x 260x 260x 260x 260x 260x 2x 2x 258x 258x 260x 260x 260x 260x 260x 260x 260x 280x 280x 280x 280x 280x 280x 280x 280x 269x 37x 269x 232x 232x 3x 3x 229x 37x 192x 232x 174x 231x 58x 58x 3x 4x 4x 3x 3x 3x 4x 58x 232x 280x 11x 11x 11x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 280x 349x 349x 349x 328x 21x 16x 5x 2x 3x 349x 339x 349x 10x 10x 349x 26x 26x 10x 26x 16x 16x 26x 58x 58x 3x 3x 3x 5x 3x 3x 58x 1x 1x 1x 1x 1x 1x 1x 1x 1x 80x 80x 54x 54x 80x 1x 1x 80x 80x 26x 26x 138x 2x 2x 138x 138x 26x 48x 48x 48x 26x 26x 26x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 39x 39x 31x 31x 39x 8x 8x 8x 8x 39x 36x 36x 39x 40x 37x 37x 40x 3x 3x 3x 3x 3x 3x 40x 31x 31x 31x 75x 75x 31x 31x 28x 6x 5x 2x 2x 1x 31x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x 6x 6x 5x 5x 6x 1x 1x 6x 6x 3x 3x 3x 4x 4x 1x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 4x 3x 3x 6x 6x 6x 5x 5x 5x 5x 5x 8x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x 1x 1x 6x 6x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 4x 6x 6x 2x 2x 4x 4x 4x 4x 9x 9x 1x 1x 48x 48x 48x 48x 48x 48x 1x 42x 42x 42x 42x 42x 42x 5x 5x 37x 42x 42x 42x 42x 42x 42x 42x 37x 37x 37x 37x 37x 37x 37x 33x 33x 33x 33x 33x 33x 33x 33x 37x 4x 4x 4x 4x 4x 4x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 149x 149x 17x 17x 132x 132x 132x 4x 128x 149x 149x 149x 149x 149x 149x 149x 149x 149x 11x 11x 11x 11x 11x 11x 3x 3x 8x 11x 1x 1x 1x 1x 11x 7x 7x 8x 8x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 1x 176x 176x 176x 176x 176x 176x 176x 176x 3x 173x 176x 364x 6x 3x 3x 3x 3x 1x 1x 1x 1x 364x 358x 358x 364x 176x 173x 358x 50x 44x 44x 50x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 1x 1x 6x 6x 6x 358x 1x 1x 1x 1x 1x 1x 1x 308x 5x 4x 4x 4x 4x 4x 4x 4x 5x 1x 1x 5x 358x 173x 176x 157x 157x 157x 157x 176x 8x 8x 176x 458x 458x 458x 458x 458x 458x 458x 458x 458x 458x 73x 73x 73x 5x 2x 2x 2x 2x 2x 5x 1x 1x 1x 1x 5x 5x 1x 1x 1x 1x 73x 68x 68x 70x 70x 458x 1x 1x 458x 135x 135x 458x 1x 1x 458x 56x 7x 7x 7x 7x 7x 7x 7x 7x 56x 56x 458x 458x 3x 3x 3x 3x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 117x 117x 254x 254x 117x 117x 254x 254x 220x 220x 254x 35x 35x 35x 35x 35x 34x 1x 745x 745x 745x 745x 745x 745x 745x 745x 87x 745x 67x 745x 25x 745x 3x 745x 2x 745x 745x 24x 24x 24x 24x 24x 20x 20x 10x 20x 3x 20x 10x 10x 10x 10x 10x 10x 10x 10x 9x 9x 17x 7x 7x 20x 4x 3x 4x 1x 4x 3x 3x 24x 23x 18x 5x 24x 745x 264x 264x 264x 264x 264x 264x 264x 745x 745x 19x 745x 745x 5x 745x 38x 38x 25x 38x 38x 38x 13x 38x 38x 745x 79x 79x 44x 44x 34x 34x 9x 9x 9x 9x 9x 9x 9x 1x 9x 9x 9x 9x 5x 5x 5x 5x 5x 5x 5x 5x 9x 9x 2x 2x 2x 2x 2x 2x 2x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 9x 34x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 9x 25x 25x 25x 25x 25x 25x 25x 1x 25x 25x 25x 25x 1x 25x 25x 25x 2x 25x 1x 25x 1x 25x 1x 1x 1x 1x 1x 1x 1x 25x 1x 1x 1x 1x 1x 1x 1x 25x 25x 1x 1x 1x 1x 1x 1x 1x 25x 25x 34x 7x 7x 745x 7x 745x 35x 745x 5x 5x 5x 5x 745x 5x 745x 3x 745x 13x 13x 13x 745x 1x 745x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 745x 5x 5x 5x 5x 5x 5x 5x 745x 23x 23x 23x 23x 23x 23x 23x 745x 5x 1x 1x 4x 4x 745x 745x 2x 42x 42x 52x 52x 52x 52x 52x 52x 52x 9x 9x 43x 43x 43x 43x 43x 43x 43x 43x 5x 5x 5x 8x 6x 6x 3x 3x 6x 3x 3x 6x 6x 8x 5x 5x 3x 3x 3x 3x 3x 3x 5x 5x 5x 5x 5x 5x 5x 3x 3x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 3x 3x 3x 1x 1x 1x 2x 3x 3x 3x 6x 5x 6x 5x 3x 3x 3x 3x 3x 3x 5x 2x 2x 5x 1x 1x 1x 9x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 6x 8x 8x 8x 4x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 1x 39x 39x 39x 39x 39x 2x 2x 2x 39x 39x 11x 39x 28x 28x 39x 39x | import type { Expression, Identifier, Node, Statement, TSCallSignatureDeclaration, TSEnumDeclaration, TSExpressionWithTypeArguments, TSFunctionType, TSImportType, TSIndexedAccessType, TSInterfaceDeclaration, TSMappedType, TSMethodSignature, TSModuleBlock, TSModuleDeclaration, TSPropertySignature, TSQualifiedName, TSType, TSTypeAnnotation, TSTypeElement, TSTypeLiteral, TSTypeQuery, TSTypeReference, TemplateLiteral, } from '@babel/types' import { UNKNOWN_TYPE, createGetCanonicalFileName, getId, getImportedName, joinPaths, normalizePath, } from './utils' import { type ScriptCompileContext, resolveParserPlugins } from './context' import type { ImportBinding, SFCScriptCompileOptions } from '../compileScript' import { capitalize, hasOwn } from '@vue/shared' import { parse as babelParse } from '@babel/parser' import { parse } from '../parse' import { createCache } from '../cache' import type TS from 'typescript' import { dirname, extname, join } from 'path' import { minimatch as isMatch } from 'minimatch' import * as process from 'process' export type SimpleTypeResolveOptions = Partial< Pick< SFCScriptCompileOptions, 'globalTypeFiles' | 'fs' | 'babelParserPlugins' | 'isProd' > > /** * TypeResolveContext is compatible with ScriptCompileContext * but also allows a simpler version of it with minimal required properties * when resolveType needs to be used in a non-SFC context, e.g. in a babel * plugin. The simplest context can be just: * ```ts * const ctx: SimpleTypeResolveContext = { * filename: '...', * source: '...', * options: {}, * error() {}, * ast: [] * } * ``` */ export type SimpleTypeResolveContext = Pick< ScriptCompileContext, // file | 'source' | 'filename' // utils | 'error' | 'helper' | 'getString' // props | 'propsTypeDecl' | 'propsRuntimeDefaults' | 'propsDestructuredBindings' // emits | 'emitsTypeDecl' // customElement | 'isCE' > & Partial< Pick<ScriptCompileContext, 'scope' | 'globalScopes' | 'deps' | 'fs'> > & { ast: Statement[] options: SimpleTypeResolveOptions } export type TypeResolveContext = ScriptCompileContext | SimpleTypeResolveContext type Import = Pick<ImportBinding, 'source' | 'imported'> interface WithScope { _ownerScope: TypeScope } // scope types always has ownerScope attached type ScopeTypeNode = Node & WithScope & { _ns?: TSModuleDeclaration & WithScope } export class TypeScope { constructor( public filename: string, public source: string, public offset: number = 0, public imports: Record<string, Import> = Object.create(null), public types: Record<string, ScopeTypeNode> = Object.create(null), public declares: Record<string, ScopeTypeNode> = Object.create(null), ) {} isGenericScope = false resolvedImportSources: Record<string, string> = Object.create(null) exportedTypes: Record<string, ScopeTypeNode> = Object.create(null) exportedDeclares: Record<string, ScopeTypeNode> = Object.create(null) } export interface MaybeWithScope { _ownerScope?: TypeScope } interface ResolvedElements { props: Record< string, (TSPropertySignature | TSMethodSignature) & { // resolved props always has ownerScope attached _ownerScope: TypeScope } > calls?: (TSCallSignatureDeclaration | TSFunctionType)[] } /** * Resolve arbitrary type node to a list of type elements that can be then * mapped to runtime props or emits. */ export function resolveTypeElements( ctx: TypeResolveContext, node: Node & MaybeWithScope & { _resolvedElements?: ResolvedElements }, scope?: TypeScope, typeParameters?: Record<string, Node>, ): ResolvedElements { const canCache = !typeParameters if (canCache && node._resolvedElements) { return node._resolvedElements } const resolved = innerResolveTypeElements( ctx, node, node._ownerScope || scope || ctxToScope(ctx), typeParameters, ) return canCache ? (node._resolvedElements = resolved) : resolved } function innerResolveTypeElements( ctx: TypeResolveContext, node: Node, scope: TypeScope, typeParameters?: Record<string, Node>, ): ResolvedElements { if ( node.leadingComments && node.leadingComments.some(c => c.value.includes('@vue-ignore')) ) { return { props: {} } } switch (node.type) { case 'TSTypeLiteral': return typeElementsToMap(ctx, node.members, scope, typeParameters) case 'TSInterfaceDeclaration': return resolveInterfaceMembers(ctx, node, scope, typeParameters) case 'TSTypeAliasDeclaration': case 'TSTypeAnnotation': case 'TSParenthesizedType': return resolveTypeElements( ctx, node.typeAnnotation, scope, typeParameters, ) case 'TSFunctionType': { return { props: {}, calls: [node] } } case 'TSUnionType': case 'TSIntersectionType': return mergeElements( node.types.map(t => resolveTypeElements(ctx, t, scope, typeParameters)), node.type, ) case 'TSMappedType': return resolveMappedType(ctx, node, scope, typeParameters) case 'TSIndexedAccessType': { const types = resolveIndexType(ctx, node, scope) return mergeElements( types.map(t => resolveTypeElements(ctx, t, t._ownerScope)), 'TSUnionType', ) } case 'TSExpressionWithTypeArguments': // referenced by interface extends case 'TSTypeReference': { const typeName = getReferenceName(node) if ( (typeName === 'ExtractPropTypes' || typeName === 'ExtractPublicPropTypes') && node.typeParameters && scope.imports[typeName]?.source === 'vue' ) { return resolveExtractPropTypes( resolveTypeElements( ctx, node.typeParameters.params[0], scope, typeParameters, ), scope, ) } const resolved = resolveTypeReference(ctx, node, scope) if (resolved) { let typeParams: Record<string, Node> | undefined if ( (resolved.type === 'TSTypeAliasDeclaration' || resolved.type === 'TSInterfaceDeclaration') && resolved.typeParameters && node.typeParameters ) { typeParams = Object.create(null) resolved.typeParameters.params.forEach((p, i) => { let param = typeParameters && typeParameters[p.name] if (!param) param = node.typeParameters!.params[i] typeParams![p.name] = param }) } return resolveTypeElements( ctx, resolved, resolved._ownerScope, typeParams, ) } else { if (typeof typeName === 'string') { if (typeParameters && typeParameters[typeName]) { return resolveTypeElements( ctx, typeParameters[typeName], scope, typeParameters, ) } if ( // @ts-expect-error SupportedBuiltinsSet.has(typeName) ) { return resolveBuiltin( ctx, node, typeName as any, scope, typeParameters, ) } else if (typeName === 'ReturnType' && node.typeParameters) { // limited support, only reference types const ret = resolveReturnType( ctx, node.typeParameters.params[0], scope, ) if (ret) { return resolveTypeElements(ctx, ret, scope) } } } return ctx.error( `Unresolvable type reference or unsupported built-in utility type`, node, scope, ) } } case 'TSImportType': { if ( getId(node.argument) === 'vue' && node.qualifier?.type === 'Identifier' && node.qualifier.name === 'ExtractPropTypes' && node.typeParameters ) { return resolveExtractPropTypes( resolveTypeElements(ctx, node.typeParameters.params[0], scope), scope, ) } const sourceScope = importSourceToScope( ctx, node.argument, scope, node.argument.value, ) const resolved = resolveTypeReference(ctx, node, sourceScope) if (resolved) { return resolveTypeElements(ctx, resolved, resolved._ownerScope) } break } case 'TSTypeQuery': { const resolved = resolveTypeReference(ctx, node, scope) if (resolved) { return resolveTypeElements(ctx, resolved, resolved._ownerScope) } } break } return ctx.error(`Unresolvable type: ${node.type}`, node, scope) } function typeElementsToMap( ctx: TypeResolveContext, elements: TSTypeElement[], scope = ctxToScope(ctx), typeParameters?: Record<string, Node>, ): ResolvedElements { const res: ResolvedElements = { props: {} } for (const e of elements) { if (e.type === 'TSPropertySignature' || e.type === 'TSMethodSignature') { // capture generic parameters on node's scope if (typeParameters) { scope = createChildScope(scope) scope.isGenericScope = true Object.assign(scope.types, typeParameters) } ;(e as MaybeWithScope)._ownerScope = scope const name = getId(e.key) if (name && !e.computed) { res.props[name] = e as ResolvedElements['props'][string] } else if (e.key.type === 'TemplateLiteral') { for (const key of resolveTemplateKeys(ctx, e.key, scope)) { res.props[key] = e as ResolvedElements['props'][string] } } else { ctx.error( `Unsupported computed key in type referenced by a macro`, e.key, scope, ) } } else if (e.type === 'TSCallSignatureDeclaration') { ;(res.calls || (res.calls = [])).push(e) } } return res } function mergeElements( maps: ResolvedElements[], type: 'TSUnionType' | 'TSIntersectionType', ): ResolvedElements { if (maps.length === 1) return maps[0] const res: ResolvedElements = { props: {} } const { props: baseProps } = res for (const { props, calls } of maps) { for (const key in props) { if (!hasOwn(baseProps, key)) { baseProps[key] = props[key] } else { baseProps[key] = createProperty( baseProps[key].key, { type, // @ts-expect-error types: [baseProps[key], props[key]], }, baseProps[key]._ownerScope, baseProps[key].optional || props[key].optional, ) } } if (calls) { ;(res.calls || (res.calls = [])).push(...calls) } } return res } function createProperty( key: Expression, typeAnnotation: TSType, scope: TypeScope, optional: boolean, ): TSPropertySignature & WithScope { return { type: 'TSPropertySignature', key, kind: 'get', optional, typeAnnotation: { type: 'TSTypeAnnotation', typeAnnotation, }, _ownerScope: scope, } } function resolveInterfaceMembers( ctx: TypeResolveContext, node: TSInterfaceDeclaration & MaybeWithScope, scope: TypeScope, typeParameters?: Record<string, Node>, ): ResolvedElements { const base = typeElementsToMap( ctx, node.body.body, node._ownerScope, typeParameters, ) if (node.extends) { for (const ext of node.extends) { try { const { props, calls } = resolveTypeElements(ctx, ext, scope) for (const key in props) { if (!hasOwn(base.props, key)) { base.props[key] = props[key] } } if (calls) { ;(base.calls || (base.calls = [])).push(...calls) } } catch (e) { ctx.error( `Failed to resolve extends base type.\nIf this previously worked in 3.2, ` + `you can instruct the compiler to ignore this extend by adding ` + `/* @vue-ignore */ before it, for example:\n\n` + `interface Props extends /* @vue-ignore */ Base {}\n\n` + `Note: both in 3.2 or with the ignore, the properties in the base ` + `type are treated as fallthrough attrs at runtime.`, ext, scope, ) } } } return base } function resolveMappedType( ctx: TypeResolveContext, node: TSMappedType, scope: TypeScope, typeParameters?: Record<string, Node>, ): ResolvedElements { const res: ResolvedElements = { props: {} } let keys: string[] if (node.nameType) { const { name, constraint } = node.typeParameter scope = createChildScope(scope) Object.assign(scope.types, { ...typeParameters, [name]: constraint }) keys = resolveStringType(ctx, node.nameType, scope) } else { keys = resolveStringType(ctx, node.typeParameter.constraint!, scope) } for (const key of keys) { res.props[key] = createProperty( { type: 'Identifier', name: key, }, node.typeAnnotation!, scope, !!node.optional, ) } return res } function resolveIndexType( ctx: TypeResolveContext, node: TSIndexedAccessType, scope: TypeScope, ): (TSType & MaybeWithScope)[] { if (node.indexType.type === 'TSNumberKeyword') { return resolveArrayElementType(ctx, node.objectType, scope) } const { indexType, objectType } = node const types: TSType[] = [] let keys: string[] let resolved: ResolvedElements if (indexType.type === 'TSStringKeyword') { resolved = resolveTypeElements(ctx, objectType, scope) keys = Object.keys(resolved.props) } else { keys = resolveStringType(ctx, indexType, scope) resolved = resolveTypeElements(ctx, objectType, scope) } for (const key of keys) { const targetType = resolved.props[key]?.typeAnnotation?.typeAnnotation if (targetType) { ;(targetType as TSType & MaybeWithScope)._ownerScope = resolved.props[key]._ownerScope types.push(targetType) } } return types } function resolveArrayElementType( ctx: TypeResolveContext, node: Node, scope: TypeScope, ): TSType[] { // type[] if (node.type === 'TSArrayType') { return [node.elementType] } // tuple if (node.type === 'TSTupleType') { return node.elementTypes.map(t => t.type === 'TSNamedTupleMember' ? t.elementType : t, ) } if (node.type === 'TSTypeReference') { // Array<type> if (getReferenceName(node) === 'Array' && node.typeParameters) { return node.typeParameters.params } else { const resolved = resolveTypeReference(ctx, node, scope) if (resolved) { return resolveArrayElementType(ctx, resolved, scope) } } } return ctx.error( 'Failed to resolve element type from target type', node, scope, ) } function resolveStringType( ctx: TypeResolveContext, node: Node, scope: TypeScope, ): string[] { switch (node.type) { case 'StringLiteral': return [node.value] case 'TSLiteralType': return resolveStringType(ctx, node.literal, scope) case 'TSUnionType': return node.types.map(t => resolveStringType(ctx, t, scope)).flat() case 'TemplateLiteral': { return resolveTemplateKeys(ctx, node, scope) } case 'TSTypeReference': { const resolved = resolveTypeReference(ctx, node, scope) if (resolved) { return resolveStringType(ctx, resolved, scope) } if (node.typeName.type === 'Identifier') { const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters!.params[index], scope) switch (node.typeName.name) { case 'Extract': return getParam(1) case 'Exclude': { const excluded = getParam(1) return getParam().filter(s => !excluded.includes(s)) } case 'Uppercase': return getParam().map(s => s.toUpperCase()) case 'Lowercase': return getParam().map(s => s.toLowerCase()) case 'Capitalize': return getParam().map(capitalize) case 'Uncapitalize': return getParam().map(s => s[0].toLowerCase() + s.slice(1)) default: ctx.error( 'Unsupported type when resolving index type', node.typeName, scope, ) } } } } return ctx.error('Failed to resolve index type into finite keys', node, scope) } function resolveTemplateKeys( ctx: TypeResolveContext, node: TemplateLiteral, scope: TypeScope, ): string[] { if (!node.expressions.length) { return [node.quasis[0].value.raw] } const res: string[] = [] const e = node.expressions[0] const q = node.quasis[0] const leading = q ? q.value.raw : `` const resolved = resolveStringType(ctx, e, scope) const restResolved = resolveTemplateKeys( ctx, { ...node, expressions: node.expressions.slice(1), quasis: q ? node.quasis.slice(1) : node.quasis, }, scope, ) for (const r of resolved) { for (const rr of restResolved) { res.push(leading + r + rr) } } return res } const SupportedBuiltinsSet = new Set([ 'Partial', 'Required', 'Readonly', 'Pick', 'Omit', ] as const) type GetSetType<T> = T extends Set<infer V> ? V : never function resolveBuiltin( ctx: TypeResolveContext, node: TSTypeReference | TSExpressionWithTypeArguments, name: GetSetType<typeof SupportedBuiltinsSet>, scope: TypeScope, typeParameters?: Record<string, Node>, ): ResolvedElements { const t = resolveTypeElements( ctx, node.typeParameters!.params[0], scope, typeParameters, ) switch (name) { case 'Partial': { const res: ResolvedElements = { props: {}, calls: t.calls } Object.keys(t.props).forEach(key => { res.props[key] = { ...t.props[key], optional: true } }) return res } case 'Required': { const res: ResolvedElements = { props: {}, calls: t.calls } Object.keys(t.props).forEach(key => { res.props[key] = { ...t.props[key], optional: false } }) return res } case 'Readonly': return t case 'Pick': { const picked = resolveStringType( ctx, node.typeParameters!.params[1], scope, ) const res: ResolvedElements = { props: {}, calls: t.calls } for (const key of picked) { res.props[key] = t.props[key] } return res } case 'Omit': const omitted = resolveStringType( ctx, node.typeParameters!.params[1], scope, ) const res: ResolvedElements = { props: {}, calls: t.calls } for (const key in t.props) { if (!omitted.includes(key)) { res.props[key] = t.props[key] } } return res } } type ReferenceTypes = | TSTypeReference | TSExpressionWithTypeArguments | TSImportType | TSTypeQuery function resolveTypeReference( ctx: TypeResolveContext, node: ReferenceTypes & { _resolvedReference?: ScopeTypeNode }, scope?: TypeScope, name?: string, onlyExported = false, ): ScopeTypeNode | undefined { const canCache = !scope?.isGenericScope if (canCache && node._resolvedReference) { return node._resolvedReference } const resolved = innerResolveTypeReference( ctx, scope || ctxToScope(ctx), name || getReferenceName(node), node, onlyExported, ) return canCache ? (node._resolvedReference = resolved) : resolved } function innerResolveTypeReference( ctx: TypeResolveContext, scope: TypeScope, name: string | string[], node: ReferenceTypes, onlyExported: boolean, ): ScopeTypeNode | undefined { if (typeof name === 'string') { if (scope.imports[name]) { return resolveTypeFromImport(ctx, node, name, scope) } else { const lookupSource = node.type === 'TSTypeQuery' ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types if (lookupSource[name]) { return lookupSource[name] } else { // fallback to global const globalScopes = resolveGlobalScope(ctx) if (globalScopes) { for (const s of globalScopes) { const src = node.type === 'TSTypeQuery' ? s.declares : s.types if (src[name]) { ;(ctx.deps || (ctx.deps = new Set())).add(s.filename) return src[name] } } } } } } else { let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported) if (ns) { if (ns.type !== 'TSModuleDeclaration') { // namespace merged with other types, attached as _ns ns = ns._ns } if (ns) { const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope) return innerResolveTypeReference( ctx, childScope, name.length > 2 ? name.slice(1) : name[name.length - 1], node, !ns.declare, ) } } } } function getReferenceName(node: ReferenceTypes): string | string[] { const ref = node.type === 'TSTypeReference' ? node.typeName : node.type === 'TSExpressionWithTypeArguments' ? node.expression : node.type === 'TSImportType' ? node.qualifier : node.exprName if (ref?.type === 'Identifier') { return ref.name } else if (ref?.type === 'TSQualifiedName') { return qualifiedNameToPath(ref) } else { return 'default' } } function qualifiedNameToPath(node: Identifier | TSQualifiedName): string[] { if (node.type === 'Identifier') { return [node.name] } else { return [...qualifiedNameToPath(node.left), node.right.name] } } function resolveGlobalScope(ctx: TypeResolveContext): TypeScope[] | undefined { if (ctx.options.globalTypeFiles) { const fs = resolveFS(ctx) if (!fs) { throw new Error('[vue/compiler-sfc] globalTypeFiles requires fs access.') } return ctx.options.globalTypeFiles.map(file => fileToScope(ctx, normalizePath(file), true), ) } } let ts: typeof TS | undefined let loadTS: (() => typeof TS) | undefined /** * @private */ export function registerTS(_loadTS: () => typeof TS): void { loadTS = () => { try { return _loadTS() } catch (err: any) { if ( typeof err.message === 'string' && err.message.includes('Cannot find module') ) { throw new Error( 'Failed to load TypeScript, which is required for resolving imported types. ' + 'Please make sure "typescript" is installed as a project dependency.', ) } else { throw new Error( 'Failed to load TypeScript for resolving imported types.', ) } } } } type FS = NonNullable<SFCScriptCompileOptions['fs']> function resolveFS(ctx: TypeResolveContext): FS | undefined { if (ctx.fs) { return ctx.fs } if (!ts && loadTS) { ts = loadTS() } const fs = ctx.options.fs || ts?.sys if (!fs) { return } return (ctx.fs = { fileExists(file) { if (file.endsWith('.vue.ts')) { file = file.replace(/\.ts$/, '') } return fs.fileExists(file) }, readFile(file) { if (file.endsWith('.vue.ts')) { file = file.replace(/\.ts$/, '') } return fs.readFile(file) }, realpath: fs.realpath, }) } function resolveTypeFromImport( ctx: TypeResolveContext, node: ReferenceTypes, name: string, scope: TypeScope, ): ScopeTypeNode | undefined { const { source, imported } = scope.imports[name] const sourceScope = importSourceToScope(ctx, node, scope, source) return resolveTypeReference(ctx, node, sourceScope, imported, true) } function importSourceToScope( ctx: TypeResolveContext, node: Node, scope: TypeScope, source: string, ): TypeScope { let fs: FS | undefined try { fs = resolveFS(ctx) } catch (err: any) { return ctx.error(err.message, node, scope) } if (!fs) { return ctx.error( `No fs option provided to \`compileScript\` in non-Node environment. ` + `File system access is required for resolving imported types.`, node, scope, ) } let resolved: string | undefined = scope.resolvedImportSources[source] if (!resolved) { if (source.startsWith('..')) { const osSpecificJoinFn = process.platform === 'win32' ? join : joinPaths const filename = osSpecificJoinFn(dirname(scope.filename), source) resolved = resolveExt(filename, fs) } else if (source[0] === '.') { // relative import - fast path const filename = joinPaths(dirname(scope.filename), source) resolved = resolveExt(filename, fs) } else { // module or aliased import - use full TS resolution, only supported in Node if (!__CJS__) { return ctx.error( `Type import from non-relative sources is not supported in the browser build.`, node, scope, ) } if (!ts) { if (loadTS) ts = loadTS() if (!ts) { return ctx.error( `Failed to resolve import source ${JSON.stringify(source)}. ` + `typescript is required as a peer dep for vue in order ` + `to support resolving types from module imports.`, node, scope, ) } } resolved = resolveWithTS(scope.filename, source, ts, fs) } if (resolved) { resolved = scope.resolvedImportSources[source] = normalizePath(resolved) } } if (resolved) { // (hmr) register dependency file on ctx ;(ctx.deps || (ctx.deps = new Set())).add(resolved) return fileToScope(ctx, resolved) } else { return ctx.error( `Failed to resolve import source ${JSON.stringify(source)}.`, node, scope, ) } } function resolveExt(filename: string, fs: FS) { // #8339 ts may import .js but we should resolve to corresponding ts or d.ts filename = filename.replace(/\.js$/, '') const tryResolve = (filename: string) => { if (fs.fileExists(filename)) return filename } return ( tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`)) ) } interface CachedConfig { config: TS.ParsedCommandLine cache?: TS.ModuleResolutionCache } const tsConfigCache = createCache<CachedConfig[]>() const tsConfigRefMap = new Map<string, string>() function resolveWithTS( containingFile: string, source: string, ts: typeof TS, fs: FS, ): string | undefined { if (!__CJS__) return // 1. resolve tsconfig.json const configPath = ts.findConfigFile(containingFile, fs.fileExists) // 2. load tsconfig.json let tsCompilerOptions: TS.CompilerOptions let tsResolveCache: TS.ModuleResolutionCache | undefined if (configPath) { let configs: CachedConfig[] const normalizedConfigPath = normalizePath(configPath) const cached = tsConfigCache.get(normalizedConfigPath) if (!cached) { configs = loadTSConfig(configPath, ts, fs).map(config => ({ config })) tsConfigCache.set(normalizedConfigPath, configs) } else { configs = cached } let matchedConfig: CachedConfig | undefined if (configs.length === 1) { matchedConfig = configs[0] } else { // resolve which config matches the current file for (const c of configs) { const base = normalizePath( (c.config.options.pathsBasePath as string) || dirname(c.config.options.configFilePath as string), ) const included: string[] | undefined = c.config.raw?.include const excluded: string[] | undefined = c.config.raw?.exclude if ( (!included && (!base || containingFile.startsWith(base))) || included?.some(p => isMatch(containingFile, joinPaths(base, p))) ) { if ( excluded && excluded.some(p => isMatch(containingFile, joinPaths(base, p))) ) { continue } matchedConfig = c break } } if (!matchedConfig) { matchedConfig = configs[configs.length - 1] } } tsCompilerOptions = matchedConfig.config.options tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts.createModuleResolutionCache( process.cwd(), createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames), tsCompilerOptions, )) } else { tsCompilerOptions = {} } // 3. resolve const res = ts.resolveModuleName( source, containingFile, tsCompilerOptions, fs, tsResolveCache, ) if (res.resolvedModule) { let filename = res.resolvedModule.resolvedFileName if (filename.endsWith('.vue.ts')) { filename = filename.replace(/\.ts$/, '') } return fs.realpath ? fs.realpath(filename) : filename } } function loadTSConfig( configPath: string, ts: typeof TS, fs: FS, visited = new Set<string>(), ): TS.ParsedCommandLine[] { // The only case where `fs` is NOT `ts.sys` is during tests. // parse config host requires an extra `readDirectory` method // during tests, which is stubbed. const parseConfigHost = __TEST__ ? { ...fs, useCaseSensitiveFileNames: true, readDirectory: () => [], } : ts.sys const config = ts.parseJsonConfigFileContent( ts.readConfigFile(configPath, fs.readFile).config, parseConfigHost, dirname(configPath), undefined, configPath, ) const res = [config] visited.add(configPath) if (config.projectReferences) { for (const ref of config.projectReferences) { const refPath = ts.resolveProjectReferencePath(ref) if (visited.has(refPath) || !fs.fileExists(refPath)) { continue } tsConfigRefMap.set(refPath, configPath) res.unshift(...loadTSConfig(refPath, ts, fs, visited)) } } return res } const fileToScopeCache = createCache<TypeScope>() /** * @private */ export function invalidateTypeCache(filename: string): void { filename = normalizePath(filename) fileToScopeCache.delete(filename) tsConfigCache.delete(filename) const affectedConfig = tsConfigRefMap.get(filename) if (affectedConfig) tsConfigCache.delete(affectedConfig) } export function fileToScope( ctx: TypeResolveContext, filename: string, asGlobal = false, ): TypeScope { const cached = fileToScopeCache.get(filename) if (cached) { return cached } // fs should be guaranteed to exist here const fs = resolveFS(ctx)! const source = fs.readFile(filename) || '' const body = parseFile(filename, source, ctx.options.babelParserPlugins) const scope = new TypeScope(filename, source, 0, recordImports(body)) recordTypes(ctx, body, scope, asGlobal) fileToScopeCache.set(filename, scope) return scope } function parseFile( filename: string, content: string, parserPlugins?: SFCScriptCompileOptions['babelParserPlugins'], ): Statement[] { const ext = extname(filename) if (ext === '.ts' || ext === '.mts' || ext === '.tsx' || ext === '.mtsx') { return babelParse(content, { plugins: resolveParserPlugins( ext.slice(1), parserPlugins, /\.d\.m?ts$/.test(filename), ), sourceType: 'module', }).program.body } else if (ext === '.vue') { const { descriptor: { script, scriptSetup }, } = parse(content) if (!script && !scriptSetup) { return [] } // ensure the correct offset with original source const scriptOffset = script ? script.loc.start.offset : Infinity const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script let scriptContent = ' '.repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock!.content if (secondBlock) { scriptContent += ' '.repeat(secondBlock.loc.start.offset - script!.loc.end.offset) + secondBlock.content } const lang = script?.lang || scriptSetup?.lang return babelParse(scriptContent, { plugins: resolveParserPlugins(lang!, parserPlugins), sourceType: 'module', }).program.body } return [] } function ctxToScope(ctx: TypeResolveContext): TypeScope { if (ctx.scope) { return ctx.scope } const body = 'ast' in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst!.body] : ctx.scriptSetupAst!.body const scope = new TypeScope( ctx.filename, ctx.source, 'startOffset' in ctx ? ctx.startOffset! : 0, 'userImports' in ctx ? Object.create(ctx.userImports) : recordImports(body), ) recordTypes(ctx, body, scope) return (ctx.scope = scope) } function moduleDeclToScope( ctx: TypeResolveContext, node: TSModuleDeclaration & { _resolvedChildScope?: TypeScope }, parentScope: TypeScope, ): TypeScope { if (node._resolvedChildScope) { return node._resolvedChildScope } const scope = createChildScope(parentScope) if (node.body.type === 'TSModuleDeclaration') { const decl = node.body as TSModuleDeclaration & WithScope decl._ownerScope = scope const id = getId(decl.id) scope.types[id] = scope.exportedTypes[id] = decl } else { recordTypes(ctx, node.body.body, scope) } return (node._resolvedChildScope = scope) } function createChildScope(parentScope: TypeScope) { return new TypeScope( parentScope.filename, parentScope.source, parentScope.offset, Object.create(parentScope.imports), Object.create(parentScope.types), Object.create(parentScope.declares), ) } const importExportRE = /^Import|^Export/ function recordTypes( ctx: TypeResolveContext, body: Statement[], scope: TypeScope, asGlobal = false, ) { const { types, declares, exportedTypes, exportedDeclares, imports } = scope const isAmbient = asGlobal ? !body.some(s => importExportRE.test(s.type)) : false for (const stmt of body) { if (asGlobal) { if (isAmbient) { if ((stmt as any).declare) { recordType(stmt, types, declares) } } else if (stmt.type === 'TSModuleDeclaration' && stmt.global) { for (const s of (stmt.body as TSModuleBlock).body) { recordType(s, types, declares) } } } else { recordType(stmt, types, declares) } } if (!asGlobal) { for (const stmt of body) { if (stmt.type === 'ExportNamedDeclaration') { if (stmt.declaration) { recordType(stmt.declaration, types, declares) recordType(stmt.declaration, exportedTypes, exportedDeclares) } else { for (const spec of stmt.specifiers) { if (spec.type === 'ExportSpecifier') { const local = spec.local.name const exported = getId(spec.exported) if (stmt.source) { // re-export, register an import + export as a type reference imports[exported] = { source: stmt.source.value, imported: local, } exportedTypes[exported] = { type: 'TSTypeReference', typeName: { type: 'Identifier', name: local, }, _ownerScope: scope, } } else if (types[local]) { // exporting local defined type exportedTypes[exported] = types[local] } } } } } else if (stmt.type === 'ExportAllDeclaration') { const sourceScope = importSourceToScope( ctx, stmt.source, scope, stmt.source.value, ) Object.assign(scope.exportedTypes, sourceScope.exportedTypes) } else if (stmt.type === 'ExportDefaultDeclaration' && stmt.declaration) { if (stmt.declaration.type !== 'Identifier') { recordType(stmt.declaration, types, declares, 'default') recordType( stmt.declaration, exportedTypes, exportedDeclares, 'default', ) } else if (types[stmt.declaration.name]) { exportedTypes['default'] = types[stmt.declaration.name] } } } } for (const key of Object.keys(types)) { const node = types[key] node._ownerScope = scope if (node._ns) node._ns._ownerScope = scope } for (const key of Object.keys(declares)) { declares[key]._ownerScope = scope } } function recordType( node: Node, types: Record<string, Node>, declares: Record<string, Node>, overwriteId?: string, ) { switch (node.type) { case 'TSInterfaceDeclaration': case 'TSEnumDeclaration': case 'TSModuleDeclaration': { const id = overwriteId || getId(node.id) let existing = types[id] if (existing) { if (node.type === 'TSModuleDeclaration') { if (existing.type === 'TSModuleDeclaration') { mergeNamespaces(existing as typeof node, node) } else { attachNamespace(existing, node) } break } if (existing.type === 'TSModuleDeclaration') { // replace and attach namespace types[id] = node attachNamespace(node, existing) break } if (existing.type !== node.type) { // type-level error break } if (node.type === 'TSInterfaceDeclaration') { ;(existing as typeof node).body.body.push(...node.body.body) } else { ;(existing as typeof node).members.push(...node.members) } } else { types[id] = node } break } case 'ClassDeclaration': if (overwriteId || node.id) types[overwriteId || getId(node.id!)] = node break case 'TSTypeAliasDeclaration': types[node.id.name] = node.typeParameters ? node : node.typeAnnotation break case 'TSDeclareFunction': if (node.id) declares[node.id.name] = node break case 'VariableDeclaration': { if (node.declare) { for (const decl of node.declarations) { if (decl.id.type === 'Identifier' && decl.id.typeAnnotation) { declares[decl.id.name] = ( decl.id.typeAnnotation as TSTypeAnnotation ).typeAnnotation } } } break } } } function mergeNamespaces(to: TSModuleDeclaration, from: TSModuleDeclaration) { const toBody = to.body const fromBody = from.body if (toBody.type === 'TSModuleDeclaration') { if (fromBody.type === 'TSModuleDeclaration') { // both decl mergeNamespaces(toBody, fromBody) } else { // to: decl -> from: block fromBody.body.push({ type: 'ExportNamedDeclaration', declaration: toBody, exportKind: 'type', specifiers: [], }) } } else if (fromBody.type === 'TSModuleDeclaration') { // to: block <- from: decl toBody.body.push({ type: 'ExportNamedDeclaration', declaration: fromBody, exportKind: 'type', specifiers: [], }) } else { // both block toBody.body.push(...fromBody.body) } } function attachNamespace( to: Node & { _ns?: TSModuleDeclaration }, ns: TSModuleDeclaration, ) { if (!to._ns) { to._ns = ns } else { mergeNamespaces(to._ns, ns) } } export function recordImports(body: Statement[]): Record<string, Import> { const imports: TypeScope['imports'] = Object.create(null) for (const s of body) { recordImport(s, imports) } return imports } function recordImport(node: Node, imports: TypeScope['imports']) { if (node.type !== 'ImportDeclaration') { return } for (const s of node.specifiers) { imports[s.local.name] = { imported: getImportedName(s), source: node.source.value, } } } export function inferRuntimeType( ctx: TypeResolveContext, node: Node & MaybeWithScope, scope: TypeScope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, ): string[] { try { switch (node.type) { case 'TSStringKeyword': return ['String'] case 'TSNumberKeyword': return ['Number'] case 'TSBooleanKeyword': return ['Boolean'] case 'TSObjectKeyword': return ['Object'] case 'TSNullKeyword': return ['null'] case 'TSTypeLiteral': case 'TSInterfaceDeclaration': { // TODO (nice to have) generate runtime property validation const types = new Set<string>() const members = node.type === 'TSTypeLiteral' ? node.members : node.body.body for (const m of members) { if (isKeyOf) { if ( m.type === 'TSPropertySignature' && m.key.type === 'NumericLiteral' ) { types.add('Number') } else if (m.type === 'TSIndexSignature') { const annotation = m.parameters[0].typeAnnotation if (annotation && annotation.type !== 'Noop') { const type = inferRuntimeType( ctx, annotation.typeAnnotation, scope, )[0] if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE] types.add(type) } } else { types.add('String') } } else if ( m.type === 'TSCallSignatureDeclaration' || m.type === 'TSConstructSignatureDeclaration' ) { types.add('Function') } else { types.add('Object') } } return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : 'Object'] } case 'TSPropertySignature': if (node.typeAnnotation) { return inferRuntimeType( ctx, node.typeAnnotation.typeAnnotation, scope, ) } break case 'TSMethodSignature': case 'TSFunctionType': return ['Function'] case 'TSArrayType': case 'TSTupleType': // TODO (nice to have) generate runtime element type/length checks return ['Array'] case 'TSLiteralType': switch (node.literal.type) { case 'StringLiteral': return ['String'] case 'BooleanLiteral': return ['Boolean'] case 'NumericLiteral': case 'BigIntLiteral': return ['Number'] default: return [UNKNOWN_TYPE] } case 'TSTypeReference': { const resolved = resolveTypeReference(ctx, node, scope) if (resolved) { return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf) } if (node.typeName.type === 'Identifier') { if (isKeyOf) { switch (node.typeName.name) { case 'String': case 'Array': case 'ArrayLike': case 'Parameters': case 'ConstructorParameters': case 'ReadonlyArray': return ['String', 'Number'] // TS built-in utility types case 'Record': case 'Partial': case 'Required': case 'Readonly': if (node.typeParameters && node.typeParameters.params[0]) { return inferRuntimeType( ctx, node.typeParameters.params[0], scope, true, ) } break case 'Pick': case 'Extract': if (node.typeParameters && node.typeParameters.params[1]) { return inferRuntimeType( ctx, node.typeParameters.params[1], scope, ) } break case 'Function': case 'Object': case 'Set': case 'Map': case 'WeakSet': case 'WeakMap': case 'Date': case 'Promise': case 'Error': case 'Uppercase': case 'Lowercase': case 'Capitalize': case 'Uncapitalize': case 'ReadonlyMap': case 'ReadonlySet': return ['String'] } } else { switch (node.typeName.name) { case 'Array': case 'Function': case 'Object': case 'Set': case 'Map': case 'WeakSet': case 'WeakMap': case 'Date': case 'Promise': case 'Error': return [node.typeName.name] // TS built-in utility types // https://www.typescriptlang.org/docs/handbook/utility-types.html case 'Partial': case 'Required': case 'Readonly': case 'Record': case 'Pick': case 'Omit': case 'InstanceType': return ['Object'] case 'Uppercase': case 'Lowercase': case 'Capitalize': case 'Uncapitalize': return ['String'] case 'Parameters': case 'ConstructorParameters': case 'ReadonlyArray': return ['Array'] case 'ReadonlyMap': return ['Map'] case 'ReadonlySet': return ['Set'] case 'NonNullable': if (node.typeParameters && node.typeParameters.params[0]) { return inferRuntimeType( ctx, node.typeParameters.params[0], scope, ).filter(t => t !== 'null') } break case 'Extract': if (node.typeParameters && node.typeParameters.params[1]) { return inferRuntimeType( ctx, node.typeParameters.params[1], scope, ) } break case 'Exclude': case 'OmitThisParameter': if (node.typeParameters && node.typeParameters.params[0]) { return inferRuntimeType( ctx, node.typeParameters.params[0], scope, ) } break } } } // cannot infer, fallback to UNKNOWN: ThisParameterType break } case 'TSParenthesizedType': return inferRuntimeType(ctx, node.typeAnnotation, scope) case 'TSUnionType': return flattenTypes(ctx, node.types, scope, isKeyOf) case 'TSIntersectionType': { return flattenTypes(ctx, node.types, scope, isKeyOf).filter( t => t !== UNKNOWN_TYPE, ) } case 'TSEnumDeclaration': return inferEnumType(node) case 'TSSymbolKeyword': return ['Symbol'] case 'TSIndexedAccessType': { const types = resolveIndexType(ctx, node, scope) return flattenTypes(ctx, types, scope, isKeyOf) } case 'ClassDeclaration': return ['Object'] case 'TSImportType': { const sourceScope = importSourceToScope( ctx, node.argument, scope, node.argument.value, ) const resolved = resolveTypeReference(ctx, node, sourceScope) if (resolved) { return inferRuntimeType(ctx, resolved, resolved._ownerScope) } break } case 'TSTypeQuery': { const id = node.exprName if (id.type === 'Identifier') { // typeof only support identifier in local scope const matched = scope.declares[id.name] if (matched) { return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf) } } break } // e.g. readonly case 'TSTypeOperator': { return inferRuntimeType( ctx, node.typeAnnotation, scope, node.operator === 'keyof', ) } case 'TSAnyKeyword': { if (isKeyOf) { return ['String', 'Number', 'Symbol'] } break } } } catch (e) { // always soft fail on failed runtime type inference } return [UNKNOWN_TYPE] // no runtime check } function flattenTypes( ctx: TypeResolveContext, types: TSType[], scope: TypeScope, isKeyOf: boolean = false, ): string[] { if (types.length === 1) { return inferRuntimeType(ctx, types[0], scope, isKeyOf) } return [ ...new Set( ([] as string[]).concat( ...types.map(t => inferRuntimeType(ctx, t, scope, isKeyOf)), ), ), ] } function inferEnumType(node: TSEnumDeclaration): string[] { const types = new Set<string>() for (const m of node.members) { if (m.initializer) { switch (m.initializer.type) { case 'StringLiteral': types.add('String') break case 'NumericLiteral': types.add('Number') break } } } return types.size ? [...types] : ['Number'] } /** * support for the `ExtractPropTypes` helper - it's non-exhaustive, mostly * tailored towards popular component libs like element-plus and antd-vue. */ function resolveExtractPropTypes( { props }: ResolvedElements, scope: TypeScope, ): ResolvedElements { const res: ResolvedElements = { props: {} } for (const key in props) { const raw = props[key] res.props[key] = reverseInferType( raw.key, raw.typeAnnotation!.typeAnnotation, scope, ) } return res } function reverseInferType( key: Expression, node: TSType, scope: TypeScope, optional = true, checkObjectSyntax = true, ): TSPropertySignature & WithScope { if (checkObjectSyntax && node.type === 'TSTypeLiteral') { // check { type: xxx } const typeType = findStaticPropertyType(node, 'type') if (typeType) { const requiredType = findStaticPropertyType(node, 'required') const optional = requiredType && requiredType.type === 'TSLiteralType' && requiredType.literal.type === 'BooleanLiteral' ? !requiredType.literal.value : true return reverseInferType(key, typeType, scope, optional, false) } } else if ( node.type === 'TSTypeReference' && node.typeName.type === 'Identifier' ) { if (node.typeName.name.endsWith('Constructor')) { return createProperty( key, ctorToType(node.typeName.name), scope, optional, ) } else if (node.typeName.name === 'PropType' && node.typeParameters) { // PropType<{}> return createProperty(key, node.typeParameters.params[0], scope, optional) } } if ( (node.type === 'TSTypeReference' || node.type === 'TSImportType') && node.typeParameters ) { // try if we can catch Foo.Bar<XXXConstructor> for (const t of node.typeParameters.params) { const inferred = reverseInferType(key, t, scope, optional) if (inferred) return inferred } } return createProperty(key, { type: `TSNullKeyword` }, scope, optional) } function ctorToType(ctorType: string): TSType { const ctor = ctorType.slice(0, -11) switch (ctor) { case 'String': case 'Number': case 'Boolean': return { type: `TS${ctor}Keyword` } case 'Array': case 'Function': case 'Object': case 'Set': case 'Map': case 'WeakSet': case 'WeakMap': case 'Date': case 'Promise': return { type: 'TSTypeReference', typeName: { type: 'Identifier', name: ctor }, } } // fallback to null return { type: `TSNullKeyword` } } function findStaticPropertyType(node: TSTypeLiteral, key: string) { const prop = node.members.find( m => m.type === 'TSPropertySignature' && !m.computed && getId(m.key) === key && m.typeAnnotation, ) return prop && prop.typeAnnotation!.typeAnnotation } function resolveReturnType( ctx: TypeResolveContext, arg: Node, scope: TypeScope, ) { let resolved: Node | undefined = arg if ( arg.type === 'TSTypeReference' || arg.type === 'TSTypeQuery' || arg.type === 'TSImportType' ) { resolved = resolveTypeReference(ctx, arg, scope) } if (!resolved) return if (resolved.type === 'TSFunctionType') { return resolved.typeAnnotation?.typeAnnotation } if (resolved.type === 'TSDeclareFunction') { return resolved.returnType } } export function resolveUnionType( ctx: TypeResolveContext, node: Node & MaybeWithScope & { _resolvedElements?: ResolvedElements }, scope?: TypeScope, ): Node[] { if (node.type === 'TSTypeReference') { const resolved = resolveTypeReference(ctx, node, scope) if (resolved) node = resolved } let types: Node[] if (node.type === 'TSUnionType') { types = node.types.flatMap(node => resolveUnionType(ctx, node, scope)) } else { types = [node] } return types } |