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 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 | 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 84x 2x 2x 2x 2x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 84x 82x 82x 82x 82x 82x 281x 47x 281x 234x 234x 281x 82x 82x 82x 82x 82x 82x 3x 2x 2x 2x 3x 1x 1x 3x 82x 82x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 82x 82x 6x 6x 4x 4x 4x 4x 4x 4x 4x 6x 2x 2x 2x 2x 2x 6x 82x 82x 8x 2x 2x 6x 6x 6x 6x 6x 8x 5x 5x 5x 5x 5x 5x 5x 5x 3x 3x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 8x 1x 1x 1x 1x 6x 6x 6x 9x 9x 2x 2x 7x 7x 9x 2x 2x 5x 5x 9x 1x 1x 6x 6x 6x 7x 4x 4x 4x 4x 6x 6x 8x 82x 82x 4x 4x 4x 4x 4x 4x 4x 11x 1x 1x 10x 10x 4x 4x 4x 3x 3x 4x 4x 4x 4x 4x 4x 13x 13x 10x 10x 3x 3x 3x 13x 13x 13x 2x 2x 13x 1x 1x 1x 1x 13x 2x 2x 4x 82x 82x 5x 5x 5x 5x 5x 5x 5x 5x 82x 82x 82x 82x 82x 82x 82x 5x 5x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x 4x 4x 4x 1x 1x 3x 3x 3x 3x 4x 4x 4x 4x 1x 1x 1x 1x 4x 3x 3x 3x 3x 3x 6x 1x 1x 1x 6x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 4x 82x 82x 82x 82x 82x 82x 82x 82x 82x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 82x 82x 82x 82x 82x 82x 82x 82x 82x 11x 11x 11x 11x 10x 10x 10x 10x 10x 11x 11x 11x 2x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 409x 409x 409x 409x 401x 401x 401x 401x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 409x 406x 409x 4x 4x 405x 405x 405x 405x 409x 2x 2x 409x 8x 11x 2x 2x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 11x 1x 1x 1x 1x 1x 1x 1x 1x 11x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 25x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 25x 25x 25x 2x 25x 17x 3x 3x 3x 3x 3x 3x 3x 3x 3x 14x 17x 1x 1x 1x 1x 1x 1x 1x 1x 13x 16x 5x 5x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 17x 17x 17x 17x 17x 11x 5x 5x 5x 5x 11x 11x 11x 11x 11x 11x 11x 10x 4x 4x 11x 11x 11x 13x 10x 4x 4x 4x 4x 10x 10x 10x 10x 10x 10x 10x 10x 4x 4x 10x 11x 17x 2x 1x 1x 1x 1x 2x 17x 9x 9x 1x 1x 1x 1x 1x 9x 8x 2x 2x 8x 8x 8x 8x 8x 8x 8x 9x 9x 8x 2x 2x 2x 2x 9x 1x 1x 9x 11x 17x 17x 2x 2x 2x 2x 1x 1x 2x 2x 2x 21x 2x 2x 1x 1x 2x 2x 15x 15x 10x 10x 10x 10x 10x 10x 10x 10x 10x 21x 25x 25x 25x 25x 25x 25x 25x 5x 5x 4x 4x 4x 4x 5x 5x 25x 10x 10x 10x 9x 9x 9x 9x 9x 9x 19x 19x 1x 1x 18x 18x 19x 1x 1x 17x 17x 19x 11x 19x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 15x 15x 15x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 10x 3x 7x 7x 7x 6x 6x 6x 6x 7x 1x 1x 3x 3x 9x 9x 10x 1x 1x 1x 10x 82x 82x 17x 17x 17x 17x 17x 17x 1x 1x 17x 17x 17x 17x 2x 2x 2x 2x 2x 15x 15x 16x 3x 3x 3x 3x 15x 15x 17x 82x 82x 12x 12x 12x 12x 12x 12x 1x 1x 12x 12x 12x 12x 1x 1x 1x 1x 1x 11x 11x 12x 1x 1x 1x 1x 11x 11x 12x 82x 82x 82x 82x 82x 82x 82x 82x 1x 1x 3x 3x 1x 1x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 2x 2x 2x 2x 2x 3x 5x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 8x 8x 6x 6x 6x 2x 2x 2x 2x 2x 7x 7x 7x 2x 2x 2x 2x 3x 1x 1x 3x 2x 2x 7x 2x 2x 2x 2x 3x 1x 1x 3x 2x 2x 5x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 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 2x 2x 2x 2x 4x 82x 82x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 82x 82x 82x 82x 82x 82x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 82x 82x 3x 3x 3x 3x 3x 3x 3x 82x 82x 82x | const axios = require("axios");
const {
buildAzureDevOpsClientConfig,
splitIntoIdentityBatches,
buildIdentitiesLookupUrl,
mapIdentityResultsToUserMap,
buildWorkItemStatesUrl,
resolveStateColorHex,
} = require("./azureDevOpsIdentityHelpers");
const {
buildGitItemsUrl,
buildCommitChangesUrl,
buildCommitDetailsUrl,
normalizeAzureItemContent,
isAddChangeType,
buildDeletedFileDiff,
buildNoChangesDetectedDiff,
buildBranchFallbackRequest,
buildFallbackDiffResult,
buildUnavailableFallbackResult,
buildShortCommitId,
buildInitialFileChange,
extractChangeFilePath,
isDirectoryChange,
resolveChangeProcessingMode,
buildFileChangePatch,
buildEditedDiffLookupRequest,
resolveEditedDiffBuildContext,
buildLineByLineDiff,
buildUnifiedDiffText,
buildAddedFileDiffCapped,
} = require("./azureDevOpsDiffHelpers");
/**
* Servicio para interactuar con Azure DevOps API
* Migración de: src/azure_devops_connector.py
*/
class AzureDevOpsService {
/**
* @param {string} organization - Organización de Azure DevOps
* @param {string} pat - Personal Access Token
* @param {Function} logCallback - Función para logging
* @throws {Error} Si organization o pat están vacíos
*/
constructor(organization, pat, logCallback = null) {
if (!organization || !pat) {
throw new Error(
"Organization y PAT son requeridos para AzureDevOpsService",
);
}
this.organization = organization;
this.pat = pat;
this.logCallback = logCallback;
this.baseUrl = `https://dev.azure.com/${organization}/_apis`;
// Cachear módulo VS Code para optimizar _isDebugEnabled()
this._vscode = null;
try {
this._vscode = require("vscode");
} catch (error) {
// VS Code no disponible (tests, ambiente no-VS Code)
}
this._configuredIgnoreRegex = null;
// Configurar axios con autenticación
this.client = axios.create({
auth: {
username: "",
password: pat,
},
headers: {
"Content-Type": "application/json",
},
timeout: 30000,
});
}
/**
* Log interno
*/
log(message) {
if (this.logCallback) {
this.logCallback(message);
} else {
console.log(message);
}
}
/**
* Verifica si el modo debug está habilitado
* Usa caché del módulo vscode para optimizar performance
*/
_isDebugEnabled() {
if (!this._vscode) return false;
try {
const config = this._vscode.workspace.getConfiguration("gbot");
return config.get("debug", false);
} catch (error) {
return false;
}
}
_getDiffSafetyLimits() {
return {
// Presupuesto por bloque para evitar crecimiento explosivo del heap.
maxBlockDiffChars: 350000,
// Si el contenido combinado supera este umbral, evitar diff detallado.
maxDiffInputChars: 160000,
// Límite de salida por archivo para evitar strings gigantes.
maxDiffOutputChars: 120000,
// Myers crece rápido en memoria con muchos renglones; usar fallback antes.
maxMyersLines: 6000,
};
}
_shouldSkipFileForDiff(filePath) {
const normalizedPath = (filePath || "").replace(/\\/g, "/");
if (!normalizedPath) return false;
const patterns = [
/(^|\/)\.vs\//i,
/(^|\/)(node_modules|bin|obj|dist|build)\//i,
/\.(dacpac|bacpac|dbmdl|dll|exe|pdb|zip|jar|war|sqlite|slnx\.sqlite)$/i,
];
if (patterns.some((pattern) => pattern.test(normalizedPath))) {
return true;
}
const configuredPatterns = this._getConfiguredIgnoreRegex();
return configuredPatterns.some((pattern) => pattern.test(normalizedPath));
}
_getConfiguredIgnoreRegex() {
if (Array.isArray(this._configuredIgnoreRegex)) {
return this._configuredIgnoreRegex;
}
let configuredPatterns = [];
let sourceLabel = null;
try {
if (this._vscode?.workspace?.getConfiguration) {
const config = this._vscode.workspace.getConfiguration("gbot");
const inspected =
typeof config.inspect === "function"
? config.inspect("prReview.ignoredFilePatterns")
: null;
const hasExplicitSettingsValue = Boolean(
inspected &&
(inspected.globalValue !== undefined ||
inspected.workspaceValue !== undefined ||
inspected.workspaceFolderValue !== undefined),
);
if (hasExplicitSettingsValue) {
const patternsFromSettings = config.get(
"prReview.ignoredFilePatterns",
);
if (Array.isArray(patternsFromSettings)) {
configuredPatterns = patternsFromSettings;
sourceLabel = "settings de VS Code";
}
} else {
const patternsFromConfigJson =
this._readIgnoredPatternsFromConfigJson(this._vscode);
if (Array.isArray(patternsFromConfigJson)) {
configuredPatterns = patternsFromConfigJson;
sourceLabel = "config.json";
}
}
}
} catch (error) {
this.log(
`⚠️ Error leyendo patrones ignorados configurados: ${error.message}`,
);
}
this._configuredIgnoreRegex = configuredPatterns
.map((pattern) => {
try {
if (typeof pattern !== "string") {
return null;
}
const normalizedPattern = pattern.trim();
if (!normalizedPattern || normalizedPattern.length > 200) {
return null;
}
return new RegExp(normalizedPattern, "i");
} catch {
return null;
}
})
.filter((p) => p !== null);
if (this._configuredIgnoreRegex.length > 0) {
this.log(
`⚙️ Azure diff: cargados ${this._configuredIgnoreRegex.length} patrón(es) ignorados desde ${sourceLabel}`,
);
}
return this._configuredIgnoreRegex;
}
_readIgnoredPatternsFromConfigJson(vscodeApi) {
const fs = require("fs");
const path = require("path");
const candidates = [];
const workspaceFolders = vscodeApi?.workspace?.workspaceFolders || [];
const pushCandidates = (rootPath) => {
if (!rootPath) {
return;
}
candidates.push(path.join(rootPath, "config.json"));
candidates.push(path.join(rootPath, "config.json.example"));
};
workspaceFolders.forEach((folder) => {
const rootPath = folder?.uri?.fsPath;
pushCandidates(rootPath);
});
pushCandidates(path.join(__dirname, "..", "..", ".."));
pushCandidates(path.join(__dirname, "..", "..", "..", ".."));
for (const configPath of candidates) {
try {
if (!fs.existsSync(configPath)) {
continue;
}
const configContent = fs.readFileSync(configPath, "utf-8");
const configData = JSON.parse(configContent);
const patterns = configData?.prReview?.ignoredFilePatterns;
if (Array.isArray(patterns)) {
return patterns;
}
} catch (error) {
this.log(
`⚠️ Azure diff: error leyendo ${configPath}: ${error.message}. Se intentará otra fuente.`,
);
}
}
return [];
}
_buildMemoryGuardDiffMessage(filePath, changeType, reason) {
return [
"⚠️ Diff detallado omitido para proteger memoria del Extension Host.",
`Archivo: ${filePath}`,
`Tipo de cambio: ${changeType}`,
`Motivo: ${reason}`,
"Acción: se analizará por metadata/ruta sin contenido completo.",
].join("\n");
}
/**
* Prueba conexión a Azure DevOps
* @returns {Promise<boolean>}
* @throws {Error} Si la conexión falla con detalles del error
*/
async testConnection() {
try {
this.log("Probando conexión a Azure DevOps...");
const url = `${this.baseUrl}/projects?api-version=7.0`;
const response = await this.client.get(url);
if (response.data && response.data.value) {
this.log(
`✅ Conexión exitosa. ${response.data.value.length} proyecto(s) encontrado(s)`,
);
return true;
}
this.log("Respuesta inesperada de Azure DevOps");
return false;
} catch (error) {
const errorMsg =
error.response?.status === 401
? "Autenticación fallida. Verifica tu PAT token"
: error.response?.status === 404
? "Organización no encontrada. Verifica el nombre"
: `Error de conexión: ${error.message}`;
this.log(`❌ ${errorMsg}`);
throw new Error(errorMsg);
}
}
/**
* Busca Pull Requests en toda la organización por número de pase
* @param {string} paseNumber - Número de pase a buscar
* @returns {Promise<Array>} Lista de PRs encontrados
*/
async searchPullRequestsByPase(paseNumber) {
try {
this.log(`Buscando PRs para pase: ${paseNumber}`);
// Primero obtener todos los proyectos
const projectsUrl = `${this.baseUrl}/projects?api-version=7.0`;
const projectsResponse = await this.client.get(projectsUrl);
const projects = projectsResponse.data.value;
this.log(`Buscando en ${projects.length} proyecto(s)...`);
const allPRs = [];
// Buscar PRs en cada proyecto
for (const project of projects) {
try {
const prsUrl = `https://dev.azure.com/${this.organization}/${project.name}/_apis/git/pullrequests?searchCriteria.status=completed&api-version=7.0`;
const prsResponse = await this.client.get(prsUrl);
// Filtrar PRs que contengan el número de pase
const matchingPRs = prsResponse.data.value.filter((pr) => {
// Solo PRs hacia branch main
const isMainBranch =
pr.targetRefName === "refs/heads/main" ||
pr.targetRefName === "refs/heads/master";
if (!isMainBranch) return false;
const title = (pr.title || "").toLowerCase().trim();
const description = (pr.description || "").toLowerCase().trim();
const pasePattern = paseNumber.toLowerCase();
return (
title.includes(pasePattern) || description.includes(pasePattern)
);
});
if (matchingPRs.length > 0) {
this.log(` ✓ ${project.name}: ${matchingPRs.length} PR(s)`);
allPRs.push(
...matchingPRs.map((pr) => ({
...pr,
projectName: project.name,
organization: this.organization, // ✅ Guardar organización del PR
})),
);
}
} catch (error) {
this.log(` ⚠ Error en ${project.name}: ${error.message}`);
}
}
this.log(`Total: ${allPRs.length} PR(s) encontrado(s)`);
return allPRs;
} catch (error) {
this.log(`❌ Error buscando PRs: ${error.message}`);
throw error;
}
}
/**
* Obtiene commits de un Pull Request
* @param {string} project - Nombre del proyecto
* @param {string} repository - ID del repositorio
* @param {number} pullRequestId - ID del PR
* @returns {Promise<Array>} Lista de commits
*/
async getPullRequestCommits(project, repository, pullRequestId) {
const url = `https://dev.azure.com/${this.organization}/${project}/_apis/git/repositories/${repository}/pullRequests/${pullRequestId}/commits?api-version=7.0`;
try {
this.log(` 🔍 Obteniendo commits: PR #${pullRequestId} (${project})`);
const response = await this.client.get(url);
const commits = response.data.value || [];
this.log(` ✓ PR #${pullRequestId}: ${commits.length} commit(s)`);
return commits;
} catch (error) {
const statusCode = error.response?.status || "desconocido";
this.log(
` ❌ Error ${statusCode} obteniendo commits del PR #${pullRequestId}`,
);
this.log(` 📍 URL: ${url}`);
this.log(` ℹ️ Organización: ${this.organization}`);
this.log(` ℹ️ Proyecto: ${project}`);
this.log(` ℹ️ Repository ID: ${repository}`);
// Si es 404, probablemente el PR no existe o los permisos son insuficientes
if (statusCode === 404) {
this.log(
` ⚠️ El PR no existe, fue eliminado, o el PAT no tiene permisos de 'Code: Read'`,
);
}
return [];
}
}
/**
* Obtiene todos los commits de múltiples PRs
* @param {Array} pullRequests - Lista de PRs
* @returns {Promise<Object>} Diccionario de PR ID -> commits
*/
async getCommitsForPullRequests(pullRequests) {
this.log("Obteniendo commits de PRs...");
this.log(`Total de PRs a procesar: ${pullRequests.length}`);
const commitsByPR = {};
let processedCount = 0;
let errorCount = 0;
for (const pr of pullRequests) {
try {
// Validar datos del PR
if (!pr.repository?.id || !pr.pullRequestId || !pr.projectName) {
this.log(
` ⚠️ PR con datos incompletos: ${JSON.stringify({
prId: pr.pullRequestId,
repoId: pr.repository?.id,
project: pr.projectName,
})}`,
);
errorCount++;
continue;
}
const commits = await this.getPullRequestCommits(
pr.projectName,
pr.repository.id,
pr.pullRequestId,
);
if (commits.length > 0) {
commitsByPR[pr.pullRequestId] = commits.map((c) => ({
id: c.commitId,
message: c.comment || "",
author: c.author?.name || "Unknown",
}));
processedCount++;
} else {
this.log(` ⚠️ PR #${pr.pullRequestId}: sin commits`);
}
} catch (error) {
this.log(
` ❌ Error procesando PR #${pr.pullRequestId}: ${error.message}`,
);
errorCount++;
// Continuar con el siguiente PR
}
}
this.log(
`\n✅ Resumen: ${processedCount}/${pullRequests.length} PR(s) procesados exitosamente`,
);
if (errorCount > 0) {
this.log(`⚠️ ${errorCount} PR(s) con errores (se omitieron)`);
}
return commitsByPR;
}
/**
* Ejecuta query WIQL en Azure Boards
* @param {string} wiql - Query WIQL
* @param {string} organization - Organización de Azure Boards
* @param {string} pat - PAT de Azure Boards
* @returns {Promise<Array>} Work items encontrados
*/
async queryWorkItems(wiql, organization, pat) {
try {
this.log("Ejecutando query WIQL en Azure Boards...");
const queryUrl = `https://dev.azure.com/${organization}/_apis/wit/wiql?api-version=7.0`;
const boardsClient = axios.create({
auth: {
username: "",
password: pat,
},
headers: {
"Content-Type": "application/json",
},
timeout: 30000,
});
const response = await boardsClient.post(queryUrl, { query: wiql });
const workItemRefs = response.data.workItems || [];
if (workItemRefs.length === 0) {
this.log(" ℹ No se encontraron work items");
return [];
}
this.log(` Encontrados ${workItemRefs.length} work item(s)`);
// Obtener detalles de work items
const ids = workItemRefs.map((wi) => wi.id).join(",");
const detailsUrl = `https://dev.azure.com/${organization}/_apis/wit/workitems?ids=${ids}&api-version=7.0`;
const detailsResponse = await boardsClient.get(detailsUrl);
const workItems = detailsResponse.data.value || [];
this.log(`${workItems.length} work item(s) obtenidos`);
return workItems;
} catch (error) {
this.log(`❌ Error en query WIQL: ${error.message}`);
throw error;
}
}
/**
* Obtener comentarios de un work item
* @param {number} workItemId - ID del work item
* @param {string} organization - Organización de Azure Boards
* @param {string} pat - PAT de Azure Boards
* @returns {Promise<Array>} Lista de comentarios
*/
async getWorkItemComments(workItemId, organization, pat) {
try {
const boardsClient = axios.create({
auth: {
username: "",
password: pat,
},
headers: {
"Content-Type": "application/json",
},
timeout: 30000,
});
// Intentar primero con Comments API (v7.0)
try {
const commentsUrl = `https://dev.azure.com/${organization}/_apis/wit/workitems/${workItemId}/comments?api-version=7.0`;
const response = await boardsClient.get(commentsUrl);
const comments = response.data.comments || [];
return comments.map((comment) => ({
id: comment.id,
text: comment.text || "",
createdBy: comment.createdBy?.displayName || "Unknown",
createdDate: comment.createdDate || "",
modifiedBy: comment.modifiedBy?.displayName || "",
modifiedDate: comment.modifiedDate || "",
}));
} catch (commentsError) {
// Intentar con Discussions API (v7.1-preview)
try {
const discussionsUrl = `https://dev.azure.com/${organization}/_apis/wit/workitems/${workItemId}/discussions?api-version=7.1-preview.1`;
const response = await boardsClient.get(discussionsUrl);
const discussions = response.data.value || [];
// Convertir discussions al formato de comments
const comments = [];
for (const discussion of discussions) {
// Cada discussion puede tener múltiples comments
if (discussion.comments) {
for (const comment of discussion.comments) {
comments.push({
id: comment.id,
text: comment.content || comment.text || "",
createdBy: comment.createdBy?.displayName || "Unknown",
createdDate: comment.createdDate || "",
modifiedBy: comment.modifiedBy?.displayName || "",
modifiedDate: comment.modifiedDate || "",
});
}
}
}
return comments;
} catch (discussionsError) {
// Ninguna API disponible, retornar array vacío
return [];
}
}
} catch (error) {
this.log(
`Error obteniendo comentarios del work item ${workItemId}: ${error.message}`,
);
// No fallar si no hay comentarios, retornar array vacío
return [];
}
}
/**
* Obtener historial de actualizaciones de un work item (incluye comentarios en cambios)
* @param {number} workItemId - ID del work item
* @param {string} organization - Organización de Azure Boards
* @param {string} pat - PAT de Azure Boards
* @returns {Promise<Array>} Lista de actualizaciones con comentarios
*/
async getWorkItemUpdates(workItemId, organization, pat) {
try {
const updatesUrl = `https://dev.azure.com/${organization}/_apis/wit/workitems/${workItemId}/updates?api-version=7.0`;
const boardsClient = axios.create({
auth: {
username: "",
password: pat,
},
headers: {
"Content-Type": "application/json",
},
timeout: 30000,
});
const response = await boardsClient.get(updatesUrl);
const updates = response.data.value || [];
// Filtrar solo las actualizaciones que tienen comentarios (System.History)
const commentsFromHistory = updates
.filter((update) => {
const historyField = update.fields?.["System.History"];
return historyField && historyField.newValue;
})
.map((update) => {
// Validar fecha antes de usarla - filtrar placeholders
const revisedDate = update.revisedDate || "";
let validDate = revisedDate;
// Si la fecha es placeholder (año 9999), intentar usar otras fechas disponibles
if (revisedDate) {
try {
const dateObj = new Date(revisedDate);
// Azure DevOps usa 9999-01-01 como placeholder "never modified"
// Algunos clientes pueden tener 9998 debido a timezone offset
// Si el año es >= 9000, es placeholder - usar fecha del update en su lugar
if (dateObj.getFullYear() >= 9000) {
// Intentar usar changedDate si está disponible
validDate =
update.fields?.["System.ChangedDate"]?.newValue ||
revisedDate;
this.log(
` ⚠️ Fecha placeholder detectada en historial (${dateObj.getFullYear()}), usando fecha alternativa`,
);
}
} catch (error) {
this.log(
` ⚠️ Error validando fecha del historial: ${error.message}`,
);
}
}
return {
id: update.id,
text: update.fields["System.History"].newValue || "",
createdBy: update.revisedBy?.displayName || "Unknown",
createdDate: validDate,
modifiedBy: update.revisedBy?.displayName || "",
modifiedDate: validDate, // Para comentarios del historial, ambas fechas son iguales
};
});
this.log(
`✅ ${commentsFromHistory.length} comentario(s) encontrados en historial`,
);
return commentsFromHistory;
} catch (error) {
const status = error.response?.status || "unknown";
const statusText = error.response?.statusText || "";
const errorDetail = error.response?.data?.message || error.message;
this.log(
`⚠ Error obteniendo historial (${status} ${statusText}): ${errorDetail}`,
);
return [];
}
}
/**
* Publicar un comentario en un work item
* @param {number} workItemId - ID del work item
* @param {string} commentText - Texto del comentario
* @param {string} [organization] - Organizacion de Azure Boards
* @param {string} [pat] - PAT de Azure Boards
* @returns {Promise<Object>} Respuesta de Azure DevOps
*/
async addWorkItemComment(workItemId, commentText, organization, pat) {
const normalizedId = Number(workItemId);
if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
throw new Error("Work item ID debe ser un entero positivo");
}
const trimmedComment = String(commentText || "").trim();
if (!trimmedComment) {
throw new Error("Comentario vacio");
}
const MAX_COMMENT_LENGTH = 150000;
if (trimmedComment.length > MAX_COMMENT_LENGTH) {
throw new Error(
`Comentario demasiado largo (max ${MAX_COMMENT_LENGTH} caracteres)`,
);
}
const org = organization || this.organization;
const token = pat || this.pat;
if (!org || !token) {
throw new Error("Organizacion y PAT son requeridos para comentar");
}
const boardsClient = axios.create({
auth: {
username: "",
password: token,
},
headers: {
"Content-Type": "application/json",
},
timeout: 30000,
});
let project = "";
try {
project = await this._getWorkItemProjectName(normalizedId, org, token);
} catch (error) {
const status = error?.response?.status;
this.log(
`⚠️ No se pudo resolver project del work item ${normalizedId}: ${error.message}`,
);
if (status === 401 || status === 403) {
throw error;
}
}
const commentHtml = this._markdownToHtml(trimmedComment);
const commentsUrl = project
? `https://dev.azure.com/${org}/${project}/_apis/wit/workitems/${normalizedId}/comments?api-version=7.1-preview.3`
: `https://dev.azure.com/${org}/_apis/wit/workitems/${normalizedId}/comments?api-version=7.1-preview.3`;
try {
const response = await boardsClient.post(commentsUrl, {
text: commentHtml,
});
return response.data;
} catch (error) {
const status = error.response?.status;
const statusText = error.response?.statusText || "";
if (status !== 404) {
throw error;
}
const isCommentsApiError = error.config?.url?.includes("/comments");
if (!isCommentsApiError) {
throw error;
}
this.log(
`⚠️ Comments API no disponible (${status} ${statusText}). Usando System.History.`,
);
const patchUrl = project
? `https://dev.azure.com/${org}/${project}/_apis/wit/workitems/${normalizedId}?api-version=7.0`
: `https://dev.azure.com/${org}/_apis/wit/workitems/${normalizedId}?api-version=7.0`;
const historyHtml = commentHtml;
const patchResponse = await boardsClient.patch(
patchUrl,
[
{
op: "add",
path: "/fields/System.History",
value: historyHtml,
},
],
{ headers: { "Content-Type": "application/json-patch+json" } },
);
return patchResponse.data;
}
}
async _getWorkItemProjectName(workItemId, organization, pat) {
const org = organization || this.organization;
const token = pat || this.pat;
if (!org || !token) {
return "";
}
const boardsClient = axios.create({
auth: {
username: "",
password: token,
},
headers: {
"Content-Type": "application/json",
},
timeout: 30000,
});
const url = `https://dev.azure.com/${org}/_apis/wit/workitems/${workItemId}?api-version=7.0&fields=System.TeamProject`;
const response = await boardsClient.get(url);
return response.data?.fields?.["System.TeamProject"] || "";
}
_markdownToHtml(markdown) {
const escaped = this._escapeHtml(String(markdown || ""));
const lines = escaped.split(/\r?\n/);
const output = [];
for (const rawLine of lines) {
const line = rawLine.trimRight();
const headingMatch = line.match(/^(#{1,3})\s+(.*)$/);
if (headingMatch) {
const content = this._applyInlineMarkdown(headingMatch[2].trim());
output.push(`<div><b>${content}</b></div>`);
continue;
}
const listMatch = line.match(/^[-*]\s+(.*)$/);
if (listMatch) {
const content = this._applyInlineMarkdown(listMatch[1].trim());
output.push(`<div>• ${content}</div>`);
continue;
}
if (!line.trim()) {
output.push("<br/>");
continue;
}
output.push(`<div>${this._applyInlineMarkdown(line.trim())}</div>`);
}
return output.join("\n");
}
_applyInlineMarkdown(text) {
return String(text || "").replace(/\*\*(.+?)\*\*/g, "<b>$1</b>");
}
_escapeHtml(text) {
return String(text || "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\"/g, """)
.replace(/'/g, "'");
}
/**
* Crear un work item via JSON Patch
* @param {Object} params
* @param {string} params.organization
* @param {string} params.project
* @param {string} params.pat
* @param {string} params.workItemType
* @param {Object} params.fields
* @param {Array<Object>} [params.relations]
* @returns {Promise<Object>} Work item creado
*/
async createWorkItem({
organization,
project,
pat,
workItemType,
fields = {},
relations = [],
}) {
const org = organization || this.organization;
const token = pat || this.pat;
if (!org || !project || !token) {
throw new Error("Faltan datos para crear work item");
}
if (!workItemType) {
throw new Error("Tipo de work item requerido");
}
const patch = [];
Object.entries(fields || {}).forEach(([fieldName, value]) => {
if (value === undefined || value === null || value === "") {
return;
}
let normalizedValue = value;
if (normalizedValue instanceof Date) {
normalizedValue = normalizedValue.toISOString();
} else if (
typeof normalizedValue === "number" &&
!Number.isFinite(normalizedValue)
) {
throw new Error(`Campo ${fieldName} tiene tipo invalido: number`);
} else if (!/^(string|number|boolean)$/.test(typeof normalizedValue)) {
throw new Error(
`Campo ${fieldName} tiene tipo invalido: ${typeof normalizedValue}`,
);
}
patch.push({
op: "add",
path: `/fields/${fieldName}`,
value: normalizedValue,
});
});
(relations || []).forEach((relation) => {
if (!relation) {
return;
}
patch.push({
op: "add",
path: "/relations/-",
value: relation,
});
});
if (patch.length === 0) {
throw new Error("No hay campos para crear el work item");
}
const boardsClient = axios.create({
auth: {
username: "",
password: token,
},
headers: {
"Content-Type": "application/json-patch+json",
},
timeout: 30000,
});
const encodedType = encodeURIComponent(workItemType);
const createUrl = `https://dev.azure.com/${org}/${project}/_apis/wit/workitems/$${encodedType}?api-version=7.0`;
const response = await boardsClient.post(createUrl, patch);
return response.data;
}
/**
* Obtener información de usuarios por sus IDs (GUIDs)
* @param {string[]} userIds - Array de GUIDs de usuarios
* @param {string} organization - Organización de Azure DevOps
* @param {string} pat - Personal Access Token
* @returns {Promise<Object>} Mapa de userId -> displayName
*/
async getUsersByIds(userIds, organization, pat) {
try {
if (!userIds || userIds.length === 0) {
return {};
}
const identitiesClient = axios.create(buildAzureDevOpsClientConfig(pat));
// API de identidades de Azure DevOps (vssps.dev.azure.com)
// Podemos hacer batch requests con hasta 100 IDs a la vez
const userMap = {};
const batches = splitIntoIdentityBatches(userIds, 100);
for (const batch of batches) {
if (batch.length === 0) {
continue;
}
try {
const identitiesUrl = buildIdentitiesLookupUrl(organization, batch);
const response = await identitiesClient.get(identitiesUrl);
const identities = response.data.value || [];
Object.assign(userMap, mapIdentityResultsToUserMap(identities));
} catch (batchError) {
this.log(
` ⚠️ Error obteniendo batch de identidades: ${batchError.message}`,
);
}
}
this.log(
`✅ Obtenidos ${Object.keys(userMap).length} nombres de usuario de ${userIds.length} solicitados`,
);
return userMap;
} catch (error) {
this.log(`⚠ Error obteniendo información de usuarios: ${error.message}`);
return {};
}
}
/**
* Obtener el color del estado de un work item desde Azure DevOps
* @param {string} project - Nombre del proyecto
* @param {string} workItemType - Tipo de work item (Bug, Task, User Story, etc.)
* @param {string} state - Estado del work item (Active, Closed, etc.)
* @param {string} organization - Organización de Azure DevOps
* @param {string} pat - Personal Access Token
* @returns {Promise<string|null>} Color en formato hex (#RRGGBB) o null si no se encuentra
*/
async getWorkItemStateColor(project, workItemType, state, organization, pat) {
try {
const statesUrl = buildWorkItemStatesUrl({
organization,
project,
workItemType,
});
const statesClient = axios.create(buildAzureDevOpsClientConfig(pat));
const response = await statesClient.get(statesUrl);
const states = response.data.value || [];
return resolveStateColorHex(states, state);
} catch (error) {
// Si falla (permisos, API no disponible, etc), retornar null para usar color por defecto
return null;
}
}
/**
* Obtener detalles de un Pull Request específico
* @param {string} project - Nombre del proyecto
* @param {string} repository - Nombre del repositorio
* @param {number} pullRequestId - ID del Pull Request
* @returns {Promise<Object>} - Detalles del PR
*/
async getPullRequestDetails(project, repository, pullRequestId) {
try {
const url = `https://dev.azure.com/${this.organization}/${project}/_apis/git/repositories/${repository}/pullrequests/${pullRequestId}?api-version=7.0`;
const response = await this.client.get(url);
return response.data;
} catch (error) {
this.log(`❌ Error obteniendo detalles del PR: ${error.message}`);
throw error;
}
}
/**
* Obtener threads de revisión de un Pull Request
* @param {string} project - Nombre del proyecto
* @param {string} repository - Nombre del repositorio
* @param {number} pullRequestId - ID del Pull Request
* @returns {Promise<Array>} - Array de threads
*/
async getPullRequestChanges(project, repository, pullRequestId) {
try {
// Obtener detalles del PR (contiene lastMergeSourceCommit para archivos nuevos)
const prUrl = `https://dev.azure.com/${this.organization}/${project}/_apis/git/repositories/${repository}/pullrequests/${pullRequestId}?api-version=7.0`;
const prResponse = await this.client.get(prUrl);
const prDetails = prResponse.data;
// Obtener iteraciones del PR (para conseguir los commits)
const iterationsUrl = `https://dev.azure.com/${this.organization}/${project}/_apis/git/repositories/${repository}/pullrequests/${pullRequestId}/iterations?api-version=7.0`;
const iterationsResponse = await this.client.get(iterationsUrl);
const iterations = iterationsResponse.data.value || [];
if (iterations.length === 0) {
this.log(`⚠️ No se encontraron iteraciones en el PR`);
return [];
}
// Usar la última iteración
const lastIteration = iterations[iterations.length - 1];
// Obtener cambios de la iteración paginando por continuation token.
const baseChangesUrl =
`https://dev.azure.com/${this.organization}/${project}/_apis/git/repositories/${repository}/pullrequests/${pullRequestId}/iterations/${lastIteration.id}/changes`;
const changeEntries = [];
let continuationToken = null;
const seenTokens = new Set();
let pageCount = 0;
const maxPages = this._getMaxChangesPages();
while (pageCount < maxPages) {
pageCount += 1;
const query = [`api-version=7.0`];
if (continuationToken) {
query.push(
`continuationToken=${encodeURIComponent(continuationToken)}`,
);
}
const changesUrl = `${baseChangesUrl}?${query.join("&")}`;
const changesResponse = await this.client.get(changesUrl);
const pageEntries = Array.isArray(changesResponse?.data?.changeEntries)
? changesResponse.data.changeEntries
: [];
changeEntries.push(...pageEntries);
const responseHeaders = changesResponse?.headers || {};
const headerToken =
responseHeaders["x-ms-continuationtoken"] ||
responseHeaders["x-ms-continuation-token"] ||
changesResponse?.data?.continuationToken ||
null;
const nextToken = headerToken ? String(headerToken).trim() : "";
if (
!nextToken ||
nextToken === continuationToken ||
seenTokens.has(nextToken)
) {
break;
}
seenTokens.add(nextToken);
continuationToken = nextToken;
if (pageEntries.length === 0) {
break;
}
}
if (pageCount >= maxPages) {
this.log(
`⚠️ Se alcanzó el máximo de páginas (${maxPages}) al obtener archivos del PR #${pullRequestId}`,
);
}
this.log(
`✅ ${changeEntries.length} archivo(s) modificado(s) encontrados (páginas: ${pageCount})`,
);
// Retornar metadata completa para procesamiento por bloques
return {
prDetails: prDetails, // Detalles completos del PR con lastMergeSourceCommit
iteration: lastIteration,
allFiles: changeEntries,
totalFiles: changeEntries.length,
};
} catch (error) {
this.log(`❌ Error obteniendo cambios del PR: ${error.message}`);
return {
prDetails: null,
iteration: null,
allFiles: [],
totalFiles: 0,
};
}
}
/**
* Obtiene un bloque específico de archivos con sus diffs
* @param {string} project - Nombre del proyecto
* @param {string} repository - Nombre del repositorio
* @param {Object} prDetails - Detalles completos del PR (con lastMergeSourceCommit)
* @param {Object} iteration - Iteración del PR
* @param {Array} files - Lista de archivos a procesar
* @param {number} blockNumber - Número del bloque
* @returns {Promise<Array>} - Archivos con diffs
*/
async getFilesBlock(
project,
repository,
prDetails,
iteration,
files,
blockNumber,
) {
try {
this.log(
`\n📦 Procesando bloque ${blockNumber} (${files.length} archivos)...`,
);
const safetyLimits = this._getDiffSafetyLimits();
const debugEnabled = this._isDebugEnabled();
const diffFetchConcurrency = this._getDiffFetchConcurrency();
let currentBlockDiffChars = 0;
const filesWithDiffs = new Array(files.length);
let skippedByPattern = 0;
let skippedByBudget = 0;
let unsupportedChangeTypeCount = 0;
let fileProcessingErrorCount = 0;
const processChange = async (change) => {
if (!(change.item && change.item.path)) {
return null;
}
const diff = {
path: change.item.path,
changeType: change.changeType,
};
// Si el archivo fue modificado o agregado, obtener contenido
if (
change.changeType === "edit" ||
change.changeType === "add" ||
change.changeType === "delete" ||
change.changeType === "add, edit"
) {
if (this._shouldSkipFileForDiff(change.item.path)) {
skippedByPattern += 1;
diff.diff = this._buildMemoryGuardDiffMessage(
change.item.path,
change.changeType,
"tipo de archivo/ruta excluida para optimización temprana",
);
currentBlockDiffChars += diff.diff.length;
return diff;
}
if (currentBlockDiffChars >= safetyLimits.maxBlockDiffChars) {
skippedByBudget += 1;
diff.diff = this._buildMemoryGuardDiffMessage(
change.item.path,
change.changeType,
`límite de bloque alcanzado (${safetyLimits.maxBlockDiffChars.toLocaleString()} chars)`,
);
return diff;
}
if (debugEnabled) {
this.log(` 🔍 Procesando ${change.changeType}: ${change.item.path}`);
}
// Obtener contenido de ambas versiones directamente
try {
let sourceContent = "";
let targetContent = "";
// Determinar qué commits usar según el tipo de cambio
// Para archivos ADD: source no existe (no está en target branch), target viene del source branch
// Para archivos EDIT: source = versión en target branch, target = versión en source branch
// Para archivos DELETE: source existe en target branch, target no existe (eliminado en source branch)
const sourceCommit = iteration.targetRefCommit.commitId; // Target branch (ej: main/release) - versión ORIGINAL
const targetCommit =
prDetails?.lastMergeSourceCommit?.commitId ||
iteration.sourceRefCommit.commitId; // Source branch (ej: feature) - versión MODIFICADA
// Para archivos nuevos (ADD), source no existe (archivo no está en target branch)
if (change.changeType !== "add") {
if (debugEnabled) {
this.log(
` 📥 Obteniendo versión source (target branch - original)...`,
);
}
sourceContent = await this._getFileContent(
project,
repository,
change.item.path,
sourceCommit,
debugEnabled,
);
if (debugEnabled) {
this.log(` ✓ Source: ${sourceContent.length} caracteres`);
}
}
// Para archivos eliminados (DELETE), target no existe (eliminado en source branch)
if (change.changeType !== "delete") {
if (debugEnabled) {
this.log(
` 📥 Obteniendo versión target (source branch - modificada)...`,
);
}
targetContent = await this._getFileContent(
project,
repository,
change.item.path,
targetCommit,
debugEnabled,
);
if (debugEnabled) {
this.log(` ✓ Target: ${targetContent.length} caracteres`);
}
}
if (!sourceContent && !targetContent) {
if (debugEnabled) {
this.log(
` ❌ No se pudo obtener ningún contenido para ambas versiones`,
);
}
diff.diff = `⚠️ No se pudo obtener el contenido del archivo.\nArchivo: ${change.item.path}\nTipo de cambio: ${change.changeType}`;
} else {
const combinedLength = sourceContent.length + targetContent.length;
if (combinedLength > safetyLimits.maxDiffInputChars) {
diff.diff = this._buildMemoryGuardDiffMessage(
change.item.path,
change.changeType,
`contenido combinado ${combinedLength.toLocaleString()} > ${safetyLimits.maxDiffInputChars.toLocaleString()} chars`,
);
} else {
if (debugEnabled) {
this.log(` 🔨 Generando diff...`);
}
diff.diff = this._generateSimpleDiff(
change.item.path,
sourceContent,
targetContent,
change.changeType,
);
}
if (!diff.diff || diff.diff.length < 100) {
if (debugEnabled) {
this.log(
` ⚠️ Diff muy corto o vacío (${diff.diff?.length || 0} chars)`,
);
}
} else if (debugEnabled) {
this.log(` ✅ Diff generado: ${diff.diff.length} caracteres`);
}
}
currentBlockDiffChars += diff.diff?.length || 0;
} catch (error) {
fileProcessingErrorCount += 1;
if (debugEnabled || fileProcessingErrorCount <= 2) {
this.log(` ❌ Error obteniendo contenido: ${error.message}`);
if (debugEnabled) {
this.log(` Stack: ${error.stack?.substring(0, 200)}`);
}
}
diff.diff = `⚠️ Error obteniendo contenido: ${error.message}\nArchivo: ${change.item.path}`;
}
} else {
unsupportedChangeTypeCount += 1;
if (debugEnabled) {
this.log(` ⚠️ Tipo de cambio no soportado: ${change.changeType}`);
}
diff.diff = `Tipo de cambio: ${change.changeType}\nArchivo: ${change.item.path}`;
}
return diff;
};
const workerCount = Math.max(
1,
Math.min(diffFetchConcurrency, Math.max(1, files.length)),
);
let nextIndex = 0;
const workers = Array.from({ length: workerCount }, async () => {
while (nextIndex < files.length) {
const index = nextIndex;
nextIndex += 1;
const change = files[index];
try {
filesWithDiffs[index] = await processChange(change);
} catch (fileError) {
fileProcessingErrorCount += 1;
if (debugEnabled || fileProcessingErrorCount <= 2) {
this.log(
` ⚠️ Error procesando ${change?.item?.path || "archivo"}: ${fileError.message}`,
);
}
filesWithDiffs[index] = null;
}
}
});
await Promise.all(workers);
const compactFilesWithDiffs = filesWithDiffs.filter(Boolean);
let budgetUsedChars = 0;
const budgetReason = `límite de bloque alcanzado (${safetyLimits.maxBlockDiffChars.toLocaleString()} chars)`;
const normalizedFilesWithDiffs = compactFilesWithDiffs.map((file) => {
const diffText = file?.diff;
if (!diffText || typeof diffText !== "string") {
return file;
}
const isBudgetGuard = diffText.includes("límite de bloque alcanzado");
if (isBudgetGuard) {
return file;
}
if (
budgetUsedChars > 0 &&
budgetUsedChars + diffText.length > safetyLimits.maxBlockDiffChars
) {
skippedByBudget += 1;
return {
...file,
diff: this._buildMemoryGuardDiffMessage(
file.path,
file.changeType,
budgetReason,
),
};
}
budgetUsedChars += diffText.length;
return file;
});
this.log(
`✅ Bloque ${blockNumber} procesado: ${normalizedFilesWithDiffs.length} archivos ` +
`(concurrencia ${workerCount}, omitidos patrón: ${skippedByPattern}, ` +
`omitidos presupuesto: ${skippedByBudget}, tipo no soportado: ${unsupportedChangeTypeCount}, ` +
`errores: ${fileProcessingErrorCount})`,
);
// Log detallado de los diffs generados (solo en modo debug)
if (debugEnabled) {
normalizedFilesWithDiffs.forEach((file, idx) => {
this.log(`\n 📄 Archivo ${idx + 1}: ${file.path}`);
this.log(` Tipo: ${file.changeType}`);
if (file.diff) {
const diffLength = file.diff.length;
const diffPreview = file.diff.substring(0, 300);
this.log(` Diff: ${diffLength} caracteres`);
this.log(` Preview: ${diffPreview}...`);
} else {
this.log(` ⚠️ Sin diff`);
}
});
}
return normalizedFilesWithDiffs;
} catch (error) {
this.log(`❌ Error procesando bloque ${blockNumber}: ${error.message}`);
return [];
}
}
_getDiffFetchConcurrency() {
let configuredValue;
try {
const config = this._vscode?.workspace?.getConfiguration?.("gbot");
configuredValue = config?.get("prReview.diffFetchConcurrency", 4);
} catch (_error) {
configuredValue = 4;
}
configuredValue = configuredValue ?? 4;
const parsed = Number(configuredValue);
if (!Number.isFinite(parsed)) {
this.log(
`⚠️ Valor no numérico para diffFetchConcurrency (${configuredValue}), usando default: 4`,
);
return 4;
}
const clamped = Math.max(1, Math.min(12, Math.floor(parsed)));
if (clamped !== parsed) {
this.log(
`⚠️ Valor de diffFetchConcurrency ajustado: ${parsed} -> ${clamped} (rango válido: 1-12)`,
);
}
return clamped;
}
_getMaxChangesPages() {
let configuredValue;
try {
const config = this._vscode?.workspace?.getConfiguration?.("gbot");
configuredValue = config?.get("prReview.maxChangePages", 200);
} catch (_error) {
configuredValue = 200;
}
configuredValue = configuredValue ?? 200;
const parsed = Number(configuredValue);
if (!Number.isFinite(parsed)) {
this.log(
`⚠️ Valor no numérico para maxChangePages (${configuredValue}), usando default: 200`,
);
return 200;
}
const clamped = Math.max(10, Math.min(1000, Math.floor(parsed)));
if (clamped !== parsed) {
this.log(
`⚠️ Valor de maxChangePages ajustado: ${parsed} -> ${clamped} (rango válido: 10-1000)`,
);
}
return clamped;
}
/**
* Divide archivos en bloques para procesamiento
* @param {Array} files - Lista completa de archivos
* @param {number} blockSize - Tamaño de cada bloque
* @returns {Array} - Array de bloques
*/
splitIntoBlocks(files, blockSize = 20) {
const blocks = [];
for (let i = 0; i < files.length; i += blockSize) {
blocks.push(files.slice(i, i + blockSize));
}
return blocks;
}
/**
* Obtiene el contenido de un archivo en un commit específico
* @param {string} project - Nombre del proyecto
* @param {string} repository - Nombre del repositorio
* @param {string} filePath - Ruta del archivo
* @param {string} commitId - ID del commit
* @returns {Promise<string>} - Contenido del archivo
*/
async _getFileContent(
project,
repository,
filePath,
commitId,
debugEnabled = false,
) {
try {
const url = buildGitItemsUrl({
organization: this.organization,
project,
repository,
filePath,
version: commitId,
versionType: "commit",
includeContent: true,
});
if (debugEnabled) {
this.log(` 🌐 URL: ${url}`);
}
const response = await this.client.get(url);
const content = normalizeAzureItemContent(response.data);
if (debugEnabled) {
const hasContentProp =
response.data && response.data.content
? "con content prop"
: "directo";
this.log(
` ✓ Contenido: ${
content.length
} caracteres (tipo: ${typeof response.data}, ${hasContentProp})`,
);
}
return content;
} catch (error) {
const statusCode = error.response?.status;
const statusText = error.response?.statusText;
if (statusCode === 404) {
// Archivo no existe en esta versión (esperado para archivos nuevos/eliminados)
this.log(
` ℹ️ Archivo no existe en commit ${commitId.substring(
0,
8,
)} (404 - esperado para archivos nuevos/eliminados)`,
);
return "";
} else {
// Error inesperado
this.log(
` ❌ Error ${statusCode || "desconocido"}: ${
statusText || error.message
}`,
);
throw error;
}
}
}
/**
* Genera un diff simple comparando dos contenidos
* @param {string} filePath - Ruta del archivo
* @param {string} sourceContent - Contenido fuente
* @param {string} targetContent - Contenido destino
* @param {string} changeType - Tipo de cambio
* @returns {string} - Diff formateado
*/
_generateSimpleDiff(filePath, sourceContent, targetContent, changeType) {
const safetyLimits = this._getDiffSafetyLimits();
const maxDiffOutputChars = safetyLimits.maxDiffOutputChars;
const combinedLength = sourceContent.length + targetContent.length;
let diff = `File: ${filePath}\nChange Type: ${changeType}\n\n`;
if (combinedLength > safetyLimits.maxDiffInputChars) {
return this._buildMemoryGuardDiffMessage(
filePath,
changeType,
`contenido demasiado grande (${combinedLength.toLocaleString()} chars)`,
);
}
this.log(
` 🔨 Generando diff: source=${sourceContent.length} chars, target=${targetContent.length} chars`,
);
const appendLine = (prefix, line) => {
const nextLine = `${prefix}${line}\n`;
if (diff.length + nextLine.length <= maxDiffOutputChars) {
diff += nextLine;
return true;
}
if (!diff.includes("⚠️ Diff truncado")) {
diff += `\n⚠️ Diff truncado por seguridad de memoria (>${maxDiffOutputChars.toLocaleString()} chars).\n`;
}
return false;
};
if (changeType === "add") {
// Archivo nuevo con límite de salida para proteger memoria.
const lines = targetContent.split("\n");
for (let i = 0; i < lines.length; i++) {
if (!appendLine("+ ", lines[i])) {
break;
}
}
this.log(` ✓ Archivo nuevo: ${lines.length} líneas (acotado)`);
} else if (changeType === "delete") {
// Archivo eliminado con límite de salida para proteger memoria.
const lines = sourceContent.split("\n");
for (let i = 0; i < lines.length; i++) {
if (!appendLine("- ", lines[i])) {
break;
}
}
this.log(` ✓ Archivo eliminado: ${lines.length} líneas (acotado)`);
} else {
// Archivo modificado - usar diff Myers para evitar falsos positivos por desplazamientos
const sourceLines = sourceContent.split("\n");
const targetLines = targetContent.split("\n");
const totalLines = sourceLines.length + targetLines.length;
if (totalLines > safetyLimits.maxMyersLines) {
this.log(
` ⚠️ Archivo grande para Myers (${totalLines} líneas). Se usará resumen protegido.`,
);
const previewSource = sourceContent.substring(0, 1200);
const previewTarget = targetContent.substring(0, 1200);
diff += `⚠️ Diff detallado omitido por volumen de líneas (${totalLines}).\n`;
diff += `Source preview (${previewSource.length} chars):\n${previewSource}\n`;
diff += `Target preview (${previewTarget.length} chars):\n${previewTarget}\n`;
return diff;
}
this.log(
` 📊 Comparando: ${sourceLines.length} vs ${targetLines.length} líneas`,
);
const ops = this._buildLineDiffOps(sourceLines, targetLines);
let linesAdded = 0;
let linesDeleted = 0;
ops.forEach((op) => {
if (op.type === "insert") {
if (appendLine("+ ", op.line)) {
linesAdded++;
}
} else if (op.type === "delete") {
if (appendLine("- ", op.line)) {
linesDeleted++;
}
}
});
if (linesAdded === 0 && linesDeleted === 0) {
diff += "\n⚠️ No se detectaron diferencias entre las versiones.\n";
this.log(` ⚠️ Sin cambios detectados`);
} else {
this.log(
` ✓ Diff generado: +${linesAdded} -${linesDeleted} (myers)`,
);
}
}
return diff;
}
/**
* Construye operaciones de diff por lineas usando algoritmo Myers.
* @param {string[]} a - Lineas fuente
* @param {string[]} b - Lineas destino
* @returns {Array<{type: string, line: string}>} - Operaciones insert/delete/equal
*/
_buildLineDiffOps(a, b) {
const n = a.length;
const m = b.length;
const maxMyersLines = this._getDiffSafetyLimits().maxMyersLines;
if (n + m > maxMyersLines) {
this.log(
` ⚠️ Myers omitido por seguridad (${n + m} líneas > ${maxMyersLines})`,
);
return [];
}
const max = n + m;
const offset = max;
const v = new Array(2 * max + 1).fill(0);
const trace = [];
for (let d = 0; d <= max; d++) {
trace.push(v.slice());
for (let k = -d; k <= d; k += 2) {
const idx = k + offset;
let x;
if (k === -d || (k !== d && v[idx - 1] < v[idx + 1])) {
x = v[idx + 1];
} else {
x = v[idx - 1] + 1;
}
let y = x - k;
while (x < n && y < m && a[x] === b[y]) {
x++;
y++;
}
v[idx] = x;
if (x >= n && y >= m) {
return this._backtrackDiff(trace, a, b);
}
}
}
return [];
}
/**
* Reconstruye las operaciones de diff desde el trace.
* @param {Array<number[]>} trace - Estados del algoritmo Myers
* @param {string[]} a - Lineas fuente
* @param {string[]} b - Lineas destino
* @returns {Array<{type: string, line: string}>}
*/
_backtrackDiff(trace, a, b) {
const n = a.length;
const m = b.length;
const max = n + m;
const offset = max;
let x = n;
let y = m;
const ops = [];
for (let d = trace.length - 1; d >= 0; d--) {
const v = trace[d];
const k = x - y;
const idx = k + offset;
let prevK;
if (k === -d || (k !== d && v[idx - 1] < v[idx + 1])) {
prevK = k + 1;
} else {
prevK = k - 1;
}
const prevX = v[prevK + offset];
const prevY = prevX - prevK;
while (x > prevX && y > prevY) {
ops.push({ type: "equal", line: a[x - 1] });
x--;
y--;
}
if (d === 0) break;
if (x === prevX) {
ops.push({ type: "insert", line: b[prevY] });
y--;
} else {
ops.push({ type: "delete", line: a[prevX] });
x--;
}
}
return ops.reverse();
}
/**
* Formatea el diff de un archivo para mostrar en el prompt
* Solo muestra las líneas modificadas (+ agregadas, - eliminadas) con contexto
*/
_formatDiff(fileDiff) {
let formatted = "";
if (fileDiff.item && fileDiff.item.path) {
formatted += `File: ${fileDiff.item.path}\n`;
}
// Verificar si hay bloques
if (!fileDiff.blocks || fileDiff.blocks.length === 0) {
this.log(
` ⚠️ Sin bloques de diff para ${fileDiff.item?.path || "archivo"}`,
);
return (
formatted +
"\n⚠️ No se encontraron bloques de diferencias en este archivo.\n"
);
}
// Agregar solo las líneas modificadas (agregadas o eliminadas) con contexto
let totalLines = 0;
let changedLines = 0;
fileDiff.blocks.forEach((block, blockIdx) => {
if (block.changeType) {
formatted += `\n--- Block ${blockIdx + 1}: ${block.changeType} ---\n`;
}
if (!block.lines || block.lines.length === 0) {
this.log(` ⚠️ Bloque ${blockIdx + 1} sin líneas`);
return;
}
totalLines += block.lines.length;
let hasChanges = block.lines.some(
(line) => line.lineType === "added" || line.lineType === "deleted",
);
if (hasChanges) {
// Incluir líneas de contexto + cambios
block.lines.forEach((line) => {
const prefix =
line.lineType === "added"
? "+"
: line.lineType === "deleted"
? "-"
: " ";
// Solo incluir líneas cambiadas o contexto inmediato
if (
line.lineType === "added" ||
line.lineType === "deleted" ||
line.lineType === "context"
) {
formatted += `${prefix} ${line.line || ""}\n`;
if (line.lineType === "added" || line.lineType === "deleted") {
changedLines++;
}
}
});
} else {
this.log(` 📝 Bloque ${blockIdx + 1} sin cambios (solo unchanged)`);
}
});
this.log(
` 📊 Diff procesado: ${changedLines} líneas modificadas de ${totalLines} totales`,
);
if (changedLines === 0) {
formatted +=
"\n⚠️ No se encontraron líneas modificadas (+ o -) en este archivo.\n";
}
return formatted;
}
/**
* Publica un comentario en un Pull Request
* @param {string} project - Nombre del proyecto
* @param {string} repository - ID o nombre del repositorio
* @param {number} pullRequestId - ID del Pull Request
* @param {Object} comment - Objeto de comentario
* @param {string} comment.content - Contenido del comentario en Markdown
* @param {number} comment.commentType - Tipo de comentario (1 = Text, 2 = CodeChange, 3 = System)
* @returns {Promise<Object>} - Thread creado
*/
async postPRComment(project, repository, pullRequestId, comment) {
try {
this.log(`\n💬 Publicando comentario en PR ${pullRequestId}...`);
const url = `https://dev.azure.com/${this.organization}/${project}/_apis/git/repositories/${repository}/pullRequests/${pullRequestId}/threads?api-version=7.0`;
const threadData = {
comments: [
{
parentCommentId: 0,
content: comment.content,
commentType: comment.commentType || 1,
},
],
status: comment.status || "active",
};
// Log para debugging
this.log(` URL: ${url}`);
this.log(` Tipo de comentario: ${threadData.comments[0].commentType}`);
this.log(
` Longitud del contenido: ${comment.content?.length || 0} caracteres`,
);
const response = await this.client.post(url, threadData);
this.log(
`✅ Comentario publicado exitosamente (Thread ID: ${response.data.id})`,
);
return response.data;
} catch (error) {
const errorMsg = error.response?.data?.message || error.message;
const errorDetails = error.response?.data
? `\n Detalles: ${JSON.stringify(error.response.data, null, 2)}`
: "";
this.log(`❌ Error publicando comentario: ${errorMsg}${errorDetails}`);
// Log adicional para debugging
if (error.response) {
this.log(` Status Code: ${error.response.status}`);
this.log(` Status Text: ${error.response.statusText}`);
}
throw new Error(`Error al publicar comentario: ${errorMsg}`);
}
}
/**
* Obtiene los threads (comentarios) existentes de un Pull Request
* @param {string} project - Nombre del proyecto
* @param {string} repository - ID o nombre del repositorio
* @param {number} pullRequestId - ID del Pull Request
* @returns {Promise<Array>} - Array de threads con comentarios
*/
async getPullRequestThreads(project, repository, pullRequestId) {
try {
this.log(
`\n📖 Obteniendo comentarios existentes del PR #${pullRequestId}...`,
);
const url = `https://dev.azure.com/${this.organization}/${project}/_apis/git/repositories/${repository}/pullRequests/${pullRequestId}/threads?api-version=7.0`;
const response = await this.client.get(url);
const threads = response.data.value || [];
this.log(`✅ ${threads.length} thread(s) de comentarios encontrados`);
return threads;
} catch (error) {
this.log(`⚠️ Error obteniendo threads del PR: ${error.message}`);
return [];
}
}
/**
* Publica múltiples comentarios en un Pull Request
* @param {string} project - Nombre del proyecto
* @param {string} repository - ID o nombre del repositorio
* @param {number} pullRequestId - ID del Pull Request
* @param {Array<Object>} comments - Array de comentarios
* @returns {Promise<Array>} - Array de threads creados
*/
async postPRComments(project, repository, pullRequestId, comments) {
try {
this.log(
`\n💬 Publicando ${comments.length} comentario(s) en PR ${pullRequestId}...`,
);
const threads = [];
for (const comment of comments) {
const thread = await this.postPRComment(
project,
repository,
pullRequestId,
comment,
);
threads.push(thread);
}
this.log(`✅ ${threads.length} comentario(s) publicados exitosamente`);
return threads;
} catch (error) {
this.log(`❌ Error publicando comentarios: ${error.message}`);
throw error;
}
}
/**
* Obtiene diffs completos de commits específicos
* NUEVO: Para modo follow-up - analizar cambios completos incluyendo archivos nuevos
* @param {string} project - Nombre del proyecto
* @param {string} repository - ID o nombre del repositorio
* @param {Array<string>} commitIds - IDs de commits a obtener
* @param {string} sourceBranch - Branch source del PR (para fallback)
* @returns {Promise<Array>} - Array de cambios con diffs completos
*/
async getCommitDiffs(project, repository, commitIds, sourceBranch = null) {
try {
this.log(
`\n📦 Obteniendo diffs completos de ${commitIds.length} commit(s)...`,
);
if (sourceBranch) {
this.log(` 📌 Branch source: ${sourceBranch}`);
}
const { allChanges, processedFiles } =
await this._collectAllCommitsDiffChanges({
project,
repository,
sourceBranch,
commitIds,
});
this.log(
`✅ ${allChanges.length} cambio(s) únicos obtenidos (${processedFiles.size} archivos)`,
);
return allChanges;
} catch (error) {
this.log(`❌ Error obteniendo diffs de commits: ${error.message}`);
throw error;
}
}
async _collectAllCommitsDiffChanges({
project,
repository,
sourceBranch,
commitIds,
}) {
const allChanges = [];
const processedFiles = new Set(); // Evitar duplicados entre commits
for (const commitId of commitIds) {
try {
const commitChanges = await this._collectCommitDiffChanges({
project,
repository,
sourceBranch,
commitId,
processedFiles,
});
allChanges.push(...commitChanges);
} catch (commitError) {
this.log(
` ❌ Error procesando commit ${commitId.substring(0, 8)}: ${
commitError.message
}`,
);
}
}
return { allChanges, processedFiles };
}
async _collectCommitDiffChanges({
project,
repository,
sourceBranch,
commitId,
processedFiles,
}) {
const shortCommitId = buildShortCommitId(commitId);
const url = buildCommitChangesUrl({
organization: this.organization,
project,
repository,
commitId,
});
const response = await this.client.get(url);
const changes = response.data.changes || [];
this.log(` ✓ Commit ${shortCommitId}: ${changes.length} archivo(s)`);
const commitChanges = [];
for (const change of changes) {
const preparedChange = this._prepareCommitChangeForDiff({
change,
commitId,
processedFiles,
});
if (preparedChange.shouldContinue) {
if (preparedChange.shouldPush) {
commitChanges.push(preparedChange.fileChange);
}
continue;
}
const { filePath, fileChange, processingMode } = preparedChange;
const processedFileChange = await this._applyProcessingModeToFileChange({
project,
repository,
sourceBranch,
commitId,
changeType: change.changeType,
filePath,
fileChange,
processingMode,
});
commitChanges.push(processedFileChange);
}
return commitChanges;
}
_prepareCommitChangeForDiff({ change, commitId, processedFiles }) {
const filePath = extractChangeFilePath(change);
if (!filePath) {
return { shouldContinue: true, shouldPush: false };
}
// Filtrar directorios (gitObjectType === 'tree') que causan 404
if (isDirectoryChange(change)) {
return { shouldContinue: true, shouldPush: false };
}
// Evitar duplicados (si el mismo archivo fue modificado en múltiples commits)
if (processedFiles.has(filePath)) {
return { shouldContinue: true, shouldPush: false };
}
processedFiles.add(filePath);
this.log(` 📄 ${filePath} (changeType: "${change.changeType}")`);
const fileChange = buildInitialFileChange({
filePath,
changeType: change.changeType,
commitId,
});
const processingMode = resolveChangeProcessingMode({
changeType: change.changeType,
shouldSkipFile: this._shouldSkipFileForDiff(filePath),
});
if (processingMode === "skip") {
Object.assign(
fileChange,
buildFileChangePatch({
diff: this._buildMemoryGuardDiffMessage(
filePath,
change.changeType,
"tipo de archivo/ruta excluida para optimización temprana",
),
}),
);
return {
shouldContinue: true,
shouldPush: true,
fileChange,
};
}
return {
shouldContinue: false,
shouldPush: false,
filePath,
fileChange,
processingMode,
};
}
async _applyProcessingModeToFileChange({
project,
repository,
sourceBranch,
commitId,
changeType,
filePath,
fileChange,
processingMode,
}) {
if (processingMode === "fetch") {
const fetchResult = await this._buildFetchDiffResultWithFallback({
project,
repository,
filePath,
changeType,
commitId,
sourceBranch,
});
Object.assign(fileChange, buildFileChangePatch(fetchResult));
} else if (processingMode === "delete") {
Object.assign(
fileChange,
buildFileChangePatch({ diff: buildDeletedFileDiff(filePath) }),
);
}
return fileChange;
}
async _buildFetchDiffResultWithFallback({
project,
repository,
filePath,
changeType,
commitId,
sourceBranch,
}) {
try {
return await this._buildPrimaryFetchDiffResult({
project,
repository,
filePath,
changeType,
commitId,
});
} catch (diffError) {
return this._buildFallbackFetchDiffResult({
project,
repository,
filePath,
changeType,
commitId,
sourceBranch,
primaryErrorMessage: diffError.message,
});
}
}
async _buildPrimaryFetchDiffResult({
project,
repository,
filePath,
changeType,
commitId,
}) {
if (isAddChangeType(changeType)) {
return this._buildAddFetchDiffResult({
project,
repository,
filePath,
commitId,
});
}
return this._buildEditFetchDiffResult({
project,
repository,
filePath,
commitId,
});
}
async _buildAddFetchDiffResult({ project, repository, filePath, commitId }) {
const contentUrl = buildGitItemsUrl({
organization: this.organization,
project,
repository,
filePath,
versionType: "commit",
version: commitId,
});
const contentResponse = await this.client.get(contentUrl, {
headers: { Accept: "text/plain" },
});
const content = normalizeAzureItemContent(contentResponse.data);
const built = this._buildAddedFileDiffCapped(filePath, content);
return {
diff: built.diff,
isNewFile: true,
linesAdded: built.linesAdded,
};
}
async _buildEditFetchDiffResult({ project, repository, filePath, commitId }) {
const editContext = await this._resolveEditDiffLookupContext({
project,
repository,
filePath,
commitId,
});
if (!editContext) {
return {};
}
return {
diff: await this._constructDiffText(
project,
repository,
filePath,
editContext.parentCommit,
commitId,
),
};
}
async _resolveEditDiffLookupContext({
project,
repository,
filePath,
commitId,
}) {
const commitUrl = buildCommitDetailsUrl({
organization: this.organization,
project,
repository,
commitId,
});
const commitResponse = await this.client.get(commitUrl);
const editedLookup = buildEditedDiffLookupRequest({
organization: this.organization,
project,
repository,
commitId,
commitData: commitResponse.data,
});
if (!editedLookup) {
return null;
}
const diffResponse = await this.client.get(editedLookup.diffUrl);
const editedContext = resolveEditedDiffBuildContext({
diffData: diffResponse.data,
filePath,
});
if (!editedContext.shouldConstruct) {
return null;
}
return {
parentCommit: editedLookup.parentCommit,
};
}
async _buildFallbackFetchDiffResult({
project,
repository,
filePath,
changeType,
commitId,
sourceBranch,
primaryErrorMessage,
}) {
const fallbackRequest = buildBranchFallbackRequest({
organization: this.organization,
project,
repository,
filePath,
sourceBranch,
});
try {
const altResponse = await this.client.get(fallbackRequest.url, {
headers: { Accept: "text/plain" },
});
const content = normalizeAzureItemContent(altResponse.data);
const built = this._buildAddedFileDiffCapped(filePath, content);
return buildFallbackDiffResult({
changeType,
filePath,
commitId,
addedDiff: built.diff,
linesAdded: built.linesAdded,
});
} catch (altError) {
this.log(` ❌ Método alternativo también falló: ${altError.message}`);
return buildUnavailableFallbackResult(filePath, primaryErrorMessage);
}
}
/**
* Construye texto diff desde contenidos de archivos
* @private
*/
async _constructDiffText(
project,
repository,
filePath,
baseVersion,
targetVersion,
) {
try {
// Obtener contenido base
const baseUrl = buildGitItemsUrl({
organization: this.organization,
project,
repository,
filePath,
version: baseVersion,
});
const baseResponse = await this.client.get(baseUrl, {
headers: { Accept: "text/plain" },
});
const baseContent = normalizeAzureItemContent(baseResponse.data);
// Obtener contenido target
const targetUrl = buildGitItemsUrl({
organization: this.organization,
project,
repository,
filePath,
version: targetVersion,
});
const targetResponse = await this.client.get(targetUrl, {
headers: { Accept: "text/plain" },
});
const targetContent = normalizeAzureItemContent(targetResponse.data);
const safetyLimits = this._getDiffSafetyLimits();
const combinedLength = baseContent.length + targetContent.length;
if (combinedLength > safetyLimits.maxDiffInputChars) {
return this._buildMemoryGuardDiffMessage(
filePath,
"edit",
`contenido combinado ${combinedLength.toLocaleString()} > ${safetyLimits.maxDiffInputChars.toLocaleString()} chars`,
);
}
const diffData = buildLineByLineDiff(baseContent, targetContent);
if (!diffData.hasChanges) {
return buildNoChangesDetectedDiff(filePath);
}
return buildUnifiedDiffText({
filePath,
baseLines: diffData.baseLines,
targetLines: diffData.targetLines,
diffLines: diffData.diffLines,
maxDiffOutputChars: safetyLimits.maxDiffOutputChars,
});
} catch (error) {
return `(error construyendo diff: ${error.message})`;
}
}
_buildAddedFileDiffCapped(filePath, content) {
const safetyLimits = this._getDiffSafetyLimits();
return buildAddedFileDiffCapped({
filePath,
content,
maxDiffOutputChars: safetyLimits.maxDiffOutputChars,
});
}
}
module.exports = { AzureDevOpsService };
|