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 | 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 45x 45x 45x 45x 45x 941x 939x 941x 1x 1x 1x 1x 1x 1x 941x 45x 45x 45x 45x 45x 45x 285x 2x 2x 2x 3x 1x 1x 285x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 25x 27x 1x 1x 1x 1x 1x 26x 26x 26x 1x 1x 1x 1x 1x 27x 45x 45x 45x 45x 45x 45x 45x 45x 45x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 279x 279x 175x 175x 279x 6x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 9x 1x 1x 9x 1x 1x 1x 4x 4x 4x 2x 2x 9x 2x 2x 2x 1x 1x 2x 4x 4x 279x 275x 275x 174x 174x 174x 174x 275x 275x 279x 30x 30x 30x 19x 19x 19x 19x 19x 19x 19x 19x 19x 30x 30x 30x 1x 1x 1x 1x 1x 35x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 377x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 377x 2256x 2x 2x 2x 2x 2x 2x 2256x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 377x 2256x 2256x 376x 376x 376x 376x 376x 376x 376x 376x 376x 376x 377x 45x 45x 45x 45x 45x 45x 45x 45x 45x 43x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 82x 42x 42x 42x 43x 13x 13x 28x 28x 28x 41x 1x 43x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 41x 1x 1x 26x 26x 26x 26x 26x 41x 3x 3x 3x 3x 2x 2x 3x 1x 1x 3x 3x 23x 23x 23x 23x 41x 1x 1x 22x 22x 22x 22x 22x 22x 22x 41x 1x 1x 21x 21x 35x 1x 1x 20x 20x 34x 1x 1x 1x 43x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 9x 7x 7x 9x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 19x 19x 19x 19x 19x 32x 32x 32x 32x 32x 32x 2x 2x 2x 2x 2x 2x 2x 32x 30x 30x 29x 29x 30x 32x 32x 32x 32x 32x 32x 4x 4x 32x 32x 32x 31x 31x 31x 31x 31x 31x 3x 3x 3x 31x 28x 28x 28x 28x 31x 31x 31x 31x 31x 31x 31x 31x 31x 357x 357x 357x 357x 357x 357x 357x 357x 357x 39x 39x 39x 39x 39x 39x 357x 357x 357x 357x 318x 318x 318x 356x 356x 356x 356x 357x 6x 6x 6x 6x 6x 6x 33x 33x 33x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 33x 17x 17x 33x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 357x 350x 350x 350x 350x 350x 350x 350x 350x 350x 350x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 350x 350x 350x 356x 357x 36x 36x 36x 31x 31x 31x 31x 31x 31x 31x 31x 31x 28x 28x 28x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 4x 4x 4x 31x 31x 31x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 30x 31x 1x 31x 30x 30x 30x 30x 10x 30x 20x 30x 10x 10x 10x 6x 10x 4x 10x 6x 6x 6x 5x 6x 1x 6x 5x 5x 5x 4x 5x 1x 5x 4x 4x 31x 31x 31x 90x 90x 90x 90x 90x 90x 90x 90x 11x 11x 11x 31x 31x 31x 165x 165x 16x 16x 16x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 17x 17x 17x 17x 15x 15x 15x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 16x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 2x 2x 31x 31x 31x 31x 31x 31x 31x 31x 17x 17x 17x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 14x 14x 14x 17x 17x 17x 17x 5x 17x 3x 3x 3x 11x 11x 11x 11x 11x 2x 2x 2x 2x 2x 9x 17x 17x 17x 17x 17x 17x 6x 15x 2x 3x 1x 1x 1x 8x 8x 11x 2x 2x 2x 2x 2x 31x 31x 31x 31x 31x 31x 31x 31x 31x 26x 26x 26x 26x 26x 26x 26x 2x 2x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 44x 44x 44x 44x 44x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 43x 43x 43x 43x 44x 44x 44x 44x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 44x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 8x 4x 4x 4x 2x 2x 2x 1x 1x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 36x 18x 18x 18x 18x 16x 16x 16x 16x 18x 17x 17x 17x 17x 17x 18x 1x 1x 28x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 7x 7x 5x 5x 5x 5x 5x 7x 7x 5x 6x 2x 2x 9x 2x 2x 2x 2x 2x 2x 2x 2x 2x 26x 26x 26x 26x 26x 26x 36x 26x 26x 26x 26x 17x 17x 17x 17x 17x 4x 4x 4x 4x 17x 26x 26x 31x 31x 31x 31x 31x 31x 40x 40x 40x 40x 40x 40x 40x 40x 40x 31x 31x 31x 31x 31x 31x 16x 16x 16x 16x 4x 4x 4x 4x 4x 4x 4x 4x 16x 16x 16x 16x 16x 31x 31x 31x 31x 31x 31x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 3x 3x 3x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 17x 9x 9x 9x 9x 9x 9x 9x 9x 31x 31x 31x 31x 31x 31x 31x 31x 29x 3x 3x 3x 26x 26x 26x 26x 16x 16x 16x 10x 10x 10x 8x 8x 7x 7x 7x 7x 8x 10x 10x 10x 10x 42x 42x 42x 16x 42x 1x 26x 3x 23x 5x 21x 17x 17x 42x 10x 10x 10x 10x 10x 10x 10x 31x 31x 31x 32x 32x 32x 32x 32x 32x 32x 32x 32x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 19x 1x 1x 1x 18x 9x 9x 9x 9x 1x 1x 19x 31x 31x 20x 20x 31x 31x 31x 31x 19x 19x 19x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 190x 190x 31x 31x 31x 31x 31x 31x 31x 11x 32x 11x 11x 11x 11x 11x 11x 31x 31x 31x 31x 1x 32x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 32x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 4x 4x 4x 4x 7x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 7x 15x 15x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 7x 2x 2x 2x 6x 5x 5x 5x 5x 7x 17x 17x 17x 17x 17x 17x 17x 17x 15x 15x 15x 31x 31x 31x 31x 32x 1x 32x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 31x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 31x 31x 32x 1x 1x 1x 32x 45x 45x 45x 45x 45x 45x 45x 45x 45x 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 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 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 45x 45x 45x 45x 45x 1x 1x 1x 45x 45x 45x 45x 45x 45x 45x 34x 34x 33x 1x 1x 1x 1x 34x 45x 45x 45x 45x 45x 45x 45x 45x 34x 34x 5x 31x 29x 29x 34x 45x 45x 45x 45x 45x 45x 45x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 45x 45x 45x 45x 45x 45x 45x 45x 5x 4x 4x 4x 4x 4x 4x 5x 45x 45x 45x | /**
* Generador de PDFs para Work Items usando pdf-lib (sin navegador)
* Construye PDFs programáticamente desde datos de Azure DevOps API
* Mucho más ligero que Puppeteer (~1MB vs ~300MB)
*
* Características:
* - Preserva formato HTML (negritas, listas, párrafos)
* - Enlaces clickeables en descripciones y comentarios
* - Imágenes inline embebidas en el PDF
*/
const {
PDFDocument,
StandardFonts,
rgb,
PDFName,
PDFString,
} = require("pdf-lib");
const fontkit = require("fontkit");
const path = require("path");
const fs = require("fs").promises;
const axios = require("axios");
const cheerio = require("cheerio");
const {
sanitizeFileName,
generateWorkItemFileName,
} = require("../utils/fileNameSanitizer");
const {
resolveWorkItemUrl,
extractMentionGuids,
buildIdentitiesUrl,
mapIdentitiesToUserMap,
sortCommentsByCreatedDateDesc,
formatCommentDateDisplay,
buildImageDownloadConfig,
detectImageEmbedType,
getImageDownloadErrorMessage,
calculateImageRenderDimensions,
createRichContentState,
buildRichTextPayload,
shouldFlushRichTextState,
appendRichTextPayload,
getLineBreakOffset,
countElementsByType,
replaceMentionGuidsWithNames,
buildWorkItemMetadata,
} = require("./workItemPdfDocumentHelpers");
class WorkItemPDFGenerator {
/**
* @param {Function} logCallback - Función para logging
*/
constructor(logCallback = null) {
this.logCallback = logCallback;
// 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)
}
// Sistema de tracking de errores para mejorar observabilidad (Issue #2)
this._errorCount = 0;
this._warnings = [];
// Fuente Unicode personalizada (opcional - para soporte completo de emojis)
this._customFont = null;
this._customFontBold = null;
this._useUnicodeFont = false;
}
/**
* Log interno - Usa logger estructurado con fallback
*/
log(message) {
if (this.logCallback) {
this.logCallback(message);
} else if (this.logger) {
// Usar logger estructurado si está disponible
this.logger.info(message);
} else {
// Fallback solo si no hay logger disponible
console.warn("[WorkItemPDFGenerator] No logger configured:", 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;
}
}
/**
* Crea una anotación de link en PDF (Issue #1 - Refactorización)
* Elimina duplicación de código en creación de links
* @param {PDFDocument} pdfDoc - Documento PDF
* @param {PDFPage} page - Página actual
* @param {string} link - URL del link
* @param {number} x - Coordenada X (esquina inferior izquierda)
* @param {number} y - Coordenada Y (esquina inferior izquierda)
* @param {number} width - Ancho del texto
* @param {number} height - Alto del texto
* @returns {boolean} true si se creó exitosamente, false si hubo error
* @private
*/
_createPdfLinkAnnotation(pdfDoc, page, link, x, y, width, height) {
try {
// Crear diccionario de acción URI
const actionDict = pdfDoc.context.obj({});
actionDict.set(PDFName.of("S"), PDFName.of("URI"));
actionDict.set(PDFName.of("URI"), PDFString.of(link));
// Crear anotación de link
// Rect format: [x1, y1, x2, y2] donde (x1,y1) es esquina inferior-izquierda
// y (x2,y2) es esquina superior-derecha
const linkAnnotation = pdfDoc.context.obj({});
linkAnnotation.set(PDFName.of("Type"), PDFName.of("Annot"));
linkAnnotation.set(PDFName.of("Subtype"), PDFName.of("Link"));
linkAnnotation.set(
PDFName.of("Rect"),
pdfDoc.context.obj([x, y, x + width, y + height]),
);
linkAnnotation.set(PDFName.of("Border"), pdfDoc.context.obj([0, 0, 0]));
linkAnnotation.set(PDFName.of("C"), pdfDoc.context.obj([0, 0, 1]));
linkAnnotation.set(PDFName.of("A"), actionDict);
linkAnnotation.set(PDFName.of("H"), PDFName.of("I")); // Highlight mode: Invert
// Registrar anotación en la página
const linkAnnotationRef = pdfDoc.context.register(linkAnnotation);
const annotations = page.node.Annots();
if (annotations) {
annotations.push(linkAnnotationRef);
} else {
page.node.set(
PDFName.of("Annots"),
pdfDoc.context.obj([linkAnnotationRef]),
);
}
return true;
} catch (error) {
this._errorCount++;
this._warnings.push(`Error al crear link: ${error.message}`);
this.log(` ⚠️ Error al crear link: ${error.message}`);
return false;
}
}
/**
* Intenta cargar fuente Unicode personalizada (Noto Sans, Arial Unicode, etc.)
* para soporte completo de emojis y caracteres especiales
* @param {PDFDocument} pdfDoc - Documento PDF
* @returns {Promise<boolean>} true si se cargó exitosamente
* @private
*/
async _loadUnicodeFont(pdfDoc) {
try {
// Registrar fontkit para soportar fuentes TrueType personalizadas
pdfDoc.registerFontkit(fontkit);
// Rutas posibles de fuentes Unicode (en orden de preferencia)
const fontPaths = [
// Fuente personalizada en resources (si el usuario la agrega)
path.join(__dirname, "../../resources/fonts/NotoSans-Regular.ttf"),
path.join(__dirname, "../../resources/fonts/NotoSans-Bold.ttf"),
// Fuentes del sistema Windows (usar path.normalize para compatibilidad)
path.normalize("C:/Windows/Fonts/Arial.ttf"),
path.normalize("C:/Windows/Fonts/arialbd.ttf"), // Arial Bold
path.normalize("C:/Windows/Fonts/NotoSans-Regular.ttf"),
// Fuentes del sistema Linux
"/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
// Fuentes del sistema macOS
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
"/Library/Fonts/Arial Unicode.ttf",
];
// Intentar cargar fuente regular
for (const fontPath of fontPaths) {
try {
if (this._isDebugEnabled()) {
this.log(` 🔍 Intentando cargar: ${fontPath}`);
}
const fontBytes = await fs.readFile(fontPath);
if (this._isDebugEnabled()) {
this.log(
` 📦 Archivo leído: ${(fontBytes.length / 1024).toFixed(1)} KB`,
);
}
this._customFont = await pdfDoc.embedFont(fontBytes);
this._useUnicodeFont = true;
this.log(`✅ Fuente Unicode cargada: ${path.basename(fontPath)}`);
this.log(
` 📏 Tamaño: ${(fontBytes.length / 1024 / 1024).toFixed(2)} MB`,
);
this.log(
` ℹ️ Emojis y caracteres especiales se preservarán completamente`,
);
// Intentar cargar versión Bold de la misma fuente
let boldPath = fontPath.replace("-Regular", "-Bold");
// Manejo especial para fuentes del sistema
const fontBaseName = path.basename(fontPath).toLowerCase();
if (fontBaseName === "arial.ttf") {
// Arial regular -> arialbd.ttf
boldPath = path.join(path.dirname(fontPath), "arialbd.ttf");
} else if (!boldPath.includes("-Bold")) {
// Si no es una fuente con "-Regular" en el nombre, probar agregando "bd" antes de .ttf
boldPath = fontPath.replace(".ttf", "bd.ttf");
}
try {
const boldBytes = await fs.readFile(boldPath);
this._customFontBold = await pdfDoc.embedFont(boldBytes);
this.log(` ✅ Fuente Bold cargada: ${path.basename(boldPath)}`);
} catch (error) {
// Si no hay Bold, usar la regular para negrita también
this._customFontBold = this._customFont;
if (this._isDebugEnabled()) {
this.log(` ℹ️ No se encontró fuente Bold, usando regular`);
}
}
return true;
} catch (error) {
// Fuente no encontrada o error al embeder, continuar con la siguiente
if (this._isDebugEnabled()) {
this.log(
` ⚠️ Error con ${path.basename(fontPath)}: ${error.message}`,
);
}
continue;
}
}
// No se encontró ninguna fuente Unicode
if (this._isDebugEnabled()) {
this.log(
` ℹ️ No se encontró fuente Unicode, usando modo sanitización`,
);
this.log(
` 💡 Para soporte completo de emojis, descarga Noto Sans de:`,
);
this.log(` https://fonts.google.com/noto/specimen/Noto+Sans`);
this.log(` Y colócala en: vscode-extension/resources/fonts/`);
}
return false;
} catch (error) {
if (this._isDebugEnabled()) {
this.log(` ⚠️ Error cargando fuente Unicode: ${error.message}`);
}
return false;
}
}
/**
* Limpia texto para que sea compatible con codificación WinAnsi de pdf-lib
* FALLBACK: Solo se usa cuando no hay fuente Unicode disponible
* - Elimina caracteres invisibles problemáticos (Zero Width Space, control chars)
* - Mapeo mínimo de símbolos básicos (✅→✓, ❌→✗, ⚠️→⚠)
* - Elimina resto de emojis Unicode no soportados por WinAnsi
* - Preserva acentos españoles (Latin-1: á, é, í, ó, ú, ñ, ü)
* @param {string} text - Texto a limpiar
* @returns {string} Texto limpio compatible con WinAnsi
* @private
*/
_sanitizeTextForPDF(text) {
if (!text || typeof text !== "string") return "";
// PASO 1: Eliminar caracteres de control invisibles (causan errores de codificación)
// 0x00-0x1F (excepto \n, \r, \t) y 0x7F (DEL)
text = String(text).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
// PASO 2: Eliminar caracteres de ancho cero (CRÍTICO - causan error WinAnsi)
// Zero Width Space (0x200B), Zero Width Joiner (0x200C), Zero Width Non-Joiner (0x200D), BOM (0xFEFF)
text = text.replace(/[\u200B-\u200D\uFEFF]/g, "");
// PASO 3: Reemplazar emojis comunes por equivalentes WinAnsi compatibles
// Solo símbolos básicos - el resto se eliminará en PASO 4
const emojiMap = {
"✅": "✓", // Check mark
"❌": "✗", // X mark
"⚠️": "⚠", // Warning (ya es Latin-1)
"✔️": "✓", // Check mark variante
"→": "->", // Flecha derecha
"←": "<-", // Flecha izquierda
};
// Aplicar reemplazos de emojis
for (const [emoji, replacement] of Object.entries(emojiMap)) {
if (text.includes(emoji)) {
const regex = new RegExp(
emoji.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
"g",
);
text = text.replace(regex, replacement);
}
}
// PASO 4: Eliminar emojis restantes que no tienen reemplazo definido
// Solo rangos principales de emojis Unicode
const emojiRanges = [
/[\u{1F600}-\u{1F64F}]/gu, // Emoticons
/[\u{1F300}-\u{1F5FF}]/gu, // Símbolos y pictogramas
/[\u{1F680}-\u{1F6FF}]/gu, // Transporte
/[\u{1F900}-\u{1F9FF}]/gu, // Símbolos suplementarios
/[\u{1FA00}-\u{1FAFF}]/gu, // Símbolos extendidos
/[\u{2600}-\u{26FF}]/gu, // Símbolos diversos (excepto los ya mapeados)
];
for (const emojiRegex of emojiRanges) {
text = text.replace(emojiRegex, "");
}
// PASO 5: Eliminar otros caracteres problemáticos fuera del rango WinAnsi
// WinAnsi soporta: 0x20-0x7E (ASCII imprimible) y 0xA0-0xFF (Latin-1 extendido)
// IMPORTANTE: Esto mantiene acentos españoles (á, é, í, ó, ú, ñ, ü) que están en Latin-1
text = text.replace(/[^\x20-\x7E\xA0-\xFF\r\n\t]/g, "");
// PASO 6: Normalizar espacios múltiples (preservar legibilidad)
text = text.replace(/[ \t]+/g, " ").trim();
return text;
}
/**
* Validar que una URL sea segura para descargar imágenes
* Previene ataques SSRF (Server-Side Request Forgery)
* @param {string} url - URL a validar
* @returns {boolean} true si es segura, false si no
* @private
*/
_isValidImageUrl(url) {
if (!url || typeof url !== "string") return false;
try {
const parsedUrl = new URL(url);
// Whitelist de dominios permitidos
const allowedDomains = [
"dev.azure.com",
"visualstudio.com",
"githubusercontent.com",
"github.com",
];
// Verificar que el dominio esté en la whitelist
const isAllowedDomain = allowedDomains.some(
(domain) =>
parsedUrl.hostname === domain ||
parsedUrl.hostname.endsWith("." + domain),
);
if (!isAllowedDomain) {
return false;
}
// Verificar que use https (excepto localhost para testing)
if (
parsedUrl.protocol !== "https:" &&
parsedUrl.hostname !== "localhost"
) {
return false;
}
// Verificar que no apunte a recursos internos ni IPs privadas
const hostname = parsedUrl.hostname.toLowerCase();
// Rangos de IPs privadas (RFC 1918) y localhost
const blockedHosts = [
"localhost",
"127.0.0.1",
"0.0.0.0",
"169.254.169.254", // AWS metadata service
];
if (blockedHosts.includes(hostname)) {
return false;
}
// Bloquear rangos de IPs privadas: 10.x.x.x, 172.16-31.x.x, 192.168.x.x
const ipv4Regex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
const ipMatch = hostname.match(ipv4Regex);
if (ipMatch) {
const [, a, b, c, d] = ipMatch.map(Number);
// 10.0.0.0/8
if (a === 10) return false;
// 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
if (a === 172 && b >= 16 && b <= 31) return false;
// 192.168.0.0/16
if (a === 192 && b === 168) return false;
}
// Validar IPv6 rangos privados (fc00::/7, fe80::/10, ::1 localhost)
const ipv6PrivateRegex =
/^(fc[0-9a-f]{2}|fd[0-9a-f]{2}|fe[89ab][0-9a-f]):/i;
if (ipv6PrivateRegex.test(hostname)) {
return false;
}
// Validar localhost IPv6 y rangos reservados adicionales
const ipv6Blocked = [
"::1", // IPv6 localhost
"::", // IPv6 unspecified
"::ffff:127.0.0.1", // IPv4-mapped IPv6 localhost
];
if (ipv6Blocked.includes(hostname)) {
return false;
}
// Bloquear rangos IPv6 site-local (deprecated pero aún usados)
if (hostname.startsWith("fec0:")) {
return false;
}
return true;
} catch (error) {
// URL inválida
return false;
}
}
/**
* Validar URL final después de redirecciones
* Previene SSRF con cadenas de redirecciones que escapan el dominio permitido
* @param {string} finalUrl - URL final después de redirecciones
* @param {string} originalUrl - URL original solicitada
* @returns {boolean} true si la URL final es válida
* @private
*/
_isValidFinalUrl(finalUrl, originalUrl) {
if (!finalUrl || finalUrl === originalUrl) return true;
// Revalidar URL final contra los mismos controles de seguridad
return this._isValidImageUrl(finalUrl);
}
/**
* Generar PDF de un work item usando pdf-lib
* @param {Object} workItem - Work item con detalles completos (incluye comments)
* @param {Array<string>} selectedFields - Campos seleccionados para incluir
* @param {string} outputDirectory - Directorio de salida
* @param {string} organization - Organización de Azure DevOps (para descargar imágenes)
* @param {string} pat - PAT de Azure DevOps (para descargar imágenes)
* @param {string} fileName - Nombre del archivo (opcional)
* @returns {Promise<string>} Ruta completa del PDF generado
*/
async generatePDF(
workItem,
selectedFields,
outputDirectory,
organization = null,
pat = null,
fileName = null,
) {
try {
// Cachear debug mode para optimizar performance (evitar múltiples lecturas de config)
const debugEnabled = this._isDebugEnabled();
const workItemId = workItem.id;
this.log(`\n✅ Generando PDF para work item ${workItemId}...`);
if (debugEnabled) {
this.log(
`🔧 Parámetros: organization='${organization}', pat=${pat ? "[PRESENTE]" : "[AUSENTE]"}`,
);
this.log(`📁 Directorio de salida: ${outputDirectory}`);
}
// Validar directorio de salida
await this._ensureDirectory(outputDirectory);
// Generar nombre de archivo si no se provee
if (!fileName) {
const title = workItem.fields
? workItem.fields["System.Title"]
: "Sin título";
const workItemType = workItem.fields
? workItem.fields["System.WorkItemType"]
: "WorkItem";
fileName = generateWorkItemFileName(workItemId, title, workItemType);
} else {
fileName = sanitizeFileName(fileName);
if (!fileName.endsWith(".pdf")) {
fileName += ".pdf";
}
}
const outputPath = path.join(outputDirectory, fileName);
// Verificar si el archivo ya existe
const fileExists = await this._fileExists(outputPath);
if (fileExists) {
this.log(`El archivo ${fileName} será sobrescrito`);
}
// Crear documento PDF
const pdfDoc = await PDFDocument.create();
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
const fontBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
// Intentar cargar fuente Unicode para soportar emojis y caracteres especiales
await this._loadUnicodeFont(pdfDoc);
if (this._useUnicodeFont) {
this.log(
`✅ Fuente Unicode cargada - Emojis y caracteres especiales serán preservados`,
);
} else {
this.log(
`⚠️ Fuente Unicode no disponible - Se aplicará sanitización de texto`,
);
}
// Configuración de página
let page = pdfDoc.addPage();
const { width, height } = page.getSize();
const margin = 50;
let y = height - margin;
// Funciones auxiliares
const addText = (
text,
size,
fontType,
color = rgb(0, 0, 0),
link = null,
) => {
// Determinar fuente a usar: custom Unicode o estándar
let actualFont = fontType;
if (this._useUnicodeFont) {
// Usar fuente Unicode personalizada
actualFont =
fontType === fontBold
? this._customFontBold || this._customFont
: this._customFont;
}
// Solo sanitizar si NO hay fuente Unicode disponible
let cleanText = text;
if (!this._useUnicodeFont) {
cleanText = this._sanitizeTextForPDF(text);
if (!cleanText) return;
}
const textWidth = actualFont.widthOfTextAtSize(cleanText, size);
const startY = y; // Guardar Y inicial para el link
if (textWidth > width - 2 * margin) {
// Wrap text si es muy largo
const words = cleanText.split(" ");
let line = "";
const lines = []; // Guardar líneas para agregar links después
for (const word of words) {
const testLine = line + word + " ";
const testWidth = actualFont.widthOfTextAtSize(testLine, size);
if (testWidth > width - 2 * margin && line !== "") {
lines.push({ text: line.trim(), y: y });
page.drawText(line, {
x: margin,
y,
size,
font: actualFont,
color,
});
y -= size + 5;
line = word + " ";
if (y < margin) {
page = pdfDoc.addPage();
y = height - margin;
}
} else {
line = testLine;
}
}
if (line !== "") {
lines.push({ text: line.trim(), y: y });
page.drawText(line.trim(), {
x: margin,
y,
size,
font: actualFont,
color,
});
y -= size + 5;
}
// Agregar links para cada línea si se proporciona link
if (link && lines.length > 0) {
let successCount = 0;
for (const lineInfo of lines) {
const lineWidth = actualFont.widthOfTextAtSize(
lineInfo.text,
size,
);
if (
this._createPdfLinkAnnotation(
pdfDoc,
page,
link,
margin,
lineInfo.y - 3,
lineWidth,
size + 3,
)
) {
successCount++;
}
}
if (successCount > 0 && this._isDebugEnabled()) {
this.log(
` 🔗 Link multi-línea agregado (${successCount}/${lines.length} líneas): ${link.substring(0, 60)}...`,
);
}
}
} else {
page.drawText(cleanText, {
x: margin,
y,
size,
font: actualFont,
color,
});
// Agregar link si se proporciona
if (link) {
if (
this._createPdfLinkAnnotation(
pdfDoc,
page,
link,
margin,
y - 3,
textWidth,
size + 3,
)
) {
if (this._isDebugEnabled()) {
this.log(
` 🔗 Link agregado en PDF: ${link.substring(0, 60)}...`,
);
}
}
}
y -= size + 5;
}
if (y < margin) {
page = pdfDoc.addPage();
y = height - margin;
}
};
const addBadge = (text, bgColor, textColor = rgb(1, 1, 1)) => {
// Determinar fuente a usar: custom Unicode o estándar
const badgeFont = this._useUnicodeFont ? this._customFont : font;
// Solo sanitizar si NO hay fuente Unicode disponible
let cleanText = text;
if (!this._useUnicodeFont) {
cleanText = this._sanitizeTextForPDF(text);
if (!cleanText) return;
}
const badgeSize = 9;
const padding = 6;
const textWidth = badgeFont.widthOfTextAtSize(cleanText, badgeSize);
const badgeWidth = textWidth + padding * 2;
const badgeHeight = badgeSize + padding;
// Dibujar rectángulo de fondo
page.drawRectangle({
x: margin,
y: y - badgeHeight + 2,
width: badgeWidth,
height: badgeHeight,
color: bgColor,
borderWidth: 0,
});
// Dibujar texto centrado
page.drawText(cleanText, {
x: margin + padding,
y: y - badgeSize - 2,
size: badgeSize,
font: badgeFont,
color: textColor,
});
y -= badgeHeight + 8;
if (y < margin) {
page = pdfDoc.addPage();
y = height - margin;
}
};
const hexToRgb = (hex) => {
// Remover # si existe
hex = hex.replace(/^#/, "");
// Convertir a RGB
const r = parseInt(hex.substring(0, 2), 16) / 255;
const g = parseInt(hex.substring(2, 4), 16) / 255;
const b = parseInt(hex.substring(4, 6), 16) / 255;
return rgb(r, g, b);
};
const getStateColor = (state, stateColorHex = null) => {
// Si tenemos el color real desde Azure DevOps, usarlo
if (stateColorHex) {
try {
return hexToRgb(stateColorHex);
} catch (error) {
this.log(
` ⚠️ Error convirtiendo color hex ${stateColorHex}: ${error.message}`,
);
}
}
// Fallback: colores según estados comunes de Azure DevOps
const stateLower = state.toLowerCase();
if (
stateLower.includes("done") ||
stateLower.includes("closed") ||
stateLower.includes("completed") ||
stateLower.includes("cerrado") ||
stateLower.includes("finalizado")
) {
return rgb(0.2, 0.6, 0.3); // Verde
} else if (
stateLower.includes("active") ||
stateLower.includes("in progress") ||
stateLower.includes("doing") ||
stateLower.includes("activo") ||
stateLower.includes("en progreso")
) {
return rgb(0, 0.5, 0.9); // Azul
} else if (
stateLower.includes("new") ||
stateLower.includes("proposed") ||
stateLower.includes("nuevo") ||
stateLower.includes("propuesto")
) {
return rgb(0.7, 0.7, 0.7); // Gris
} else if (
stateLower.includes("resolved") ||
stateLower.includes("ready") ||
stateLower.includes("resuelto") ||
stateLower.includes("listo")
) {
return rgb(0.4, 0.7, 0.9); // Azul claro
} else if (
stateLower.includes("removed") ||
stateLower.includes("cut") ||
stateLower.includes("eliminado") ||
stateLower.includes("cortado")
) {
return rgb(0.8, 0.2, 0.2); // Rojo
} else {
return rgb(0.5, 0.5, 0.5); // Gris por defecto
}
};
const addLine = () => {
page.drawLine({
start: { x: margin, y },
end: { x: width - margin, y },
thickness: 1,
color: rgb(0.75, 0.75, 0.75),
});
y -= 20;
if (y < margin) {
page = pdfDoc.addPage();
y = height - margin;
}
};
const addSpace = () => {
y -= 10;
if (y < margin) {
page = pdfDoc.addPage();
y = height - margin;
}
};
/**
* Renderizar un comentario como card con separación visual
* @param {string} author - Autor del comentario
* @param {string} date - Fecha del comentario
* @param {string} commentText - Texto del comentario (HTML/Markdown)
* @returns {Promise<void>}
*/
const addCommentCard = async (author, date, commentText) => {
// Solo sanitizar si NO hay fuente Unicode disponible
let cleanAuthor = author;
let cleanDate = date;
if (!this._useUnicodeFont) {
cleanAuthor = this._sanitizeTextForPDF(author);
cleanDate = this._sanitizeTextForPDF(date);
}
// Espacio antes de la card
y -= 8;
// Header con fondo gris claro
const headerHeight = 18;
page.drawRectangle({
x: margin,
y: y - headerHeight + 4,
width: width - 2 * margin,
height: headerHeight,
color: rgb(0.95, 0.95, 0.95),
borderWidth: 0,
});
// Texto del header
const headerFont =
this._useUnicodeFont && this._customFontBold
? this._customFontBold
: this._useUnicodeFont
? this._customFont
: fontBold;
page.drawText(`${cleanAuthor} - ${cleanDate}`, {
x: margin + 8,
y: y - 2,
size: 9,
font: headerFont,
color: rgb(0.2, 0.2, 0.2),
});
y -= headerHeight + 10;
// Contenido del comentario
await addRichContent(commentText, 9);
// Línea inferior para separar
y -= 5;
page.drawLine({
start: { x: margin, y },
end: { x: width - margin, y },
thickness: 0.5,
color: rgb(0.85, 0.85, 0.85),
});
// Espacio después de la card
y -= 10;
if (y < margin) {
page = pdfDoc.addPage();
y = height - margin;
}
};
/**
* Convertir Markdown básico a HTML
* @param {string} text - Texto con Markdown
* @returns {string} HTML equivalente
*/
const markdownToHTML = (text) => {
const normalizedText = ["", String(text)][Number(Boolean(text))];
let html = normalizedText;
// PASO 1: Proteger URLs en imágenes y enlaces (convertir primero)
// Usamos placeholders temporales para evitar que _ en URLs se interpreten como itálicas
const imageUrls = [];
const linkUrls = [];
// Imágenes:  -> <img src="URL_PLACEHOLDER_N" alt="alt">
html = html.replace(/!\[([^\]]*)\]\(([^\)]+)\)/g, (match, alt, url) => {
const index = imageUrls.length;
imageUrls.push(url);
this.log(
` 🔄 Convirtiendo Markdown imagen: }...)`,
);
return `<img src="IMAGE_URL_PLACEHOLDER_${index}" alt="${alt}">`;
});
// Enlaces: [text](url) -> <a href="URL_PLACEHOLDER_N">text</a>
html = html.replace(/\[([^\]]+)\]\(([^\)]+)\)/g, (match, text, url) => {
const index = linkUrls.length;
linkUrls.push(url);
return `<a href="LINK_URL_PLACEHOLDER_${index}">${text}</a>`;
});
// PASO 2: Ahora sí aplicar formato de texto (sin afectar URLs protegidas)
// Negritas: **texto** o __texto__ -> <strong>texto</strong>
html = html.replace(/\*\*([^\*]+)\*\*/g, "<strong>$1</strong>");
html = html.replace(/__([^_]+)__/g, "<strong>$1</strong>");
// Itálicas: *texto* o _texto_ -> <em>texto</em>
// Usar regex más específico para evitar conflictos con URLs
html = html.replace(/\B\*([^\*]+)\*\B/g, "<em>$1</em>");
html = html.replace(/\b_([^_]+)_\b/g, "<em>$1</em>");
// Saltos de línea: convertir \n a <br>
html = html.replace(/\n/g, "<br>");
// PASO 3: Restaurar URLs desde placeholders
imageUrls.forEach((url, index) => {
html = html.replace(`IMAGE_URL_PLACEHOLDER_${index}`, url);
});
linkUrls.forEach((url, index) => {
html = html.replace(`LINK_URL_PLACEHOLDER_${index}`, url);
});
return html;
};
/**
* Descargar y embeder imagen en el PDF
* @param {string} imageUrl - URL de la imagen
* @returns {Promise<PDFImage|null>} Imagen embebida o null si falla
*/
const downloadAndEmbedImage = async (imageUrl) => {
try {
// CRÍTICO: Validar URL para prevenir SSRF (Server-Side Request Forgery)
if (!this._isValidImageUrl(imageUrl)) {
this.log(
`URL de imagen rechazada (validación de seguridad): ${imageUrl}`,
);
return null;
}
this.log(
` 🖼️ Descargando imagen: ${imageUrl.substring(0, 80)}...`,
);
const axiosConfig = buildImageDownloadConfig(imageUrl, pat);
// Descargar imagen
const response = await axios.get(imageUrl, axiosConfig);
// Validar URL final después de redirecciones
const finalUrl =
response.request?.res?.responseUrl || response.config?.url;
if (
finalUrl &&
finalUrl !== imageUrl &&
!this._isValidFinalUrl(finalUrl, imageUrl)
) {
this.log(` ⚠️ URL final post-redirect rechazada: ${finalUrl}`);
return null;
}
const imageBytes = response.data;
// Validar tamaño real de respuesta (doble chequeo)
if (imageBytes.byteLength > 2 * 1024 * 1024) {
this.log(
` ⚠️ Imagen excede 2MB (${(imageBytes.byteLength / 1024 / 1024).toFixed(1)}MB), omitida`,
);
return null;
}
const contentType = response.headers["content-type"] || "";
const embedType = detectImageEmbedType({ contentType, imageUrl });
// Embeder según tipo
let image = null;
if (embedType === "png") {
image = await pdfDoc.embedPng(imageBytes);
} else if (embedType === "jpg") {
image = await pdfDoc.embedJpg(imageBytes);
} else {
this.log(`Formato de imagen no soportado: ${contentType}`);
return null;
}
return image;
} catch (error) {
// Manejo explícito de timeouts y errores de red
const errorMsg = getImageDownloadErrorMessage(error);
this.log(` ⚠️ Error descargando imagen: ${errorMsg}`);
return null;
}
};
/**
* Parsear HTML y extraer contenido estructurado con formato
* Soporta tags HTML comunes y preserva estructura (listas, párrafos, imágenes)
* @param {string} html - HTML o Markdown a parsear
* @returns {Array<{type: string, text?: string, bold?: boolean, link?: string, src?: string, alt?: string}>} Elementos estructurados
*/
const parseHTMLContent = (html) => {
html = ["", String(html)][Number(Boolean(html))];
// Detectar si contiene Markdown (sintaxis  o [...](...))
const hasMarkdown = /!\[[^\]]*\]\([^\)]+\)|\[[^\]]+\]\([^\)]+\)/.test(
html,
);
if (hasMarkdown) {
html = markdownToHTML(html);
}
// Normalizar saltos de línea antes de parsear
// Convertir \n\n (doble salto) en <p> para preservar párrafos
const doubleLineBreaks = (html.match(/\n\n+/g) || []).length;
const singleLineBreaks =
(html.match(/\n/g) || []).length - doubleLineBreaks * 2;
if (doubleLineBreaks > 0 || singleLineBreaks > 0) {
if (this._isDebugEnabled()) {
this.log(
` 📄 Normalizando saltos de línea: ${doubleLineBreaks} párrafo(s), ${singleLineBreaks} salto(s) simple(s)`,
);
}
}
html = html.replace(/\n\n+/g, "</p><p>");
// Convertir \n simple en <br> para preservar saltos de línea
html = html.replace(/\n/g, "<br>");
const $ = cheerio.load(html, { decodeEntities: true });
const elements = [];
// Función recursiva para procesar nodos
const processNode = (node, context = {}) => {
const $node = $(node);
const tagName = node.tagName ? node.tagName.toLowerCase() : "";
// Detectar menciones: <span class="mention-preview-person">@Usuario</span>
if (tagName === "span") {
const classAttr = $node.attr("class") || "";
if (classAttr.includes("mention-preview-person")) {
const mentionText = $node.text().trim();
if (mentionText) {
if (this._isDebugEnabled()) {
this.log(` 👤 Mención detectada: ${mentionText}`);
}
elements.push({
type: "text",
text: mentionText,
bold: true, // Menciones en negrita
italic: false,
link: null,
});
return; // No procesar hijos
}
}
}
const isBold =
context.bold ||
["strong", "b", "h1", "h2", "h3", "h4", "h5", "h6"].includes(
tagName,
);
const isItalic = context.italic || ["em", "i"].includes(tagName);
if (node.type === "text") {
const text = $(node).text().trim();
if (text) {
elements.push({
type: "text",
text: text,
bold: context.bold,
italic: context.italic,
link: context.link,
});
}
} else if (tagName === "a") {
// Enlaces especiales: menciones de usuarios (@usuario)
const dataMention = $node.attr("data-vss-mention");
const href = $node.attr("href") || "";
let linkText = $node.text().trim();
if (linkText) {
// Si es una mención (@usuario), renderizar como texto especial sin link
if (
dataMention ||
(linkText.startsWith("@") && href.includes("mailto:"))
) {
// Intentar extraer nombre real del atributo data-vss-mention="version:2.0,<guid>"
// o del contenido del nodo. Si linkText es @<id>, intentar obtener mejor nombre.
if (dataMention && linkText.match(/^@[a-f0-9-]+$/i)) {
// Es un @id, intentar extraer nombre del title o del contenido
const title = $node.attr("title") || "";
if (title && !title.includes("@")) {
linkText = "@" + title;
}
}
if (this._isDebugEnabled()) {
this.log(` 👤 Mención procesada: ${linkText}`);
}
elements.push({
type: "text",
text: linkText,
bold: true, // Menciones en negrita para destacar
italic: false,
link: null, // No mostrar como link clickeable
});
} else {
// Enlace normal
elements.push({
type: "link",
text: linkText,
link: href,
bold: isBold,
italic: isItalic,
});
}
}
} else if (tagName === "img") {
// Imágenes
const src = $node.attr("src") || $node.attr("data-src") || "";
const alt = $node.attr("alt") || "Imagen";
if (this._isDebugEnabled()) {
this.log(
` 🔍 Imagen detectada en HTML: src="${src.substring(0, 80)}", alt="${alt}"`,
);
}
if (src) {
elements.push({
type: "image",
src: src,
alt: alt,
});
} else {
this.log(` ⚠️ Imagen sin atributo src encontrada`);
}
} else if (tagName === "li") {
// Items de lista
elements.push({ type: "bullet" });
$node.contents().each((i, child) => {
processNode(child, {
bold: isBold,
italic: isItalic,
link: context.link,
});
});
elements.push({ type: "newline" });
} else if (["br", "p", "div"].includes(tagName)) {
// Saltos de línea
$node.contents().each((i, child) => {
processNode(child, {
bold: isBold,
italic: isItalic,
link: context.link,
});
});
if (tagName === "p" || tagName === "div") {
elements.push({ type: "paragraph" });
} else {
elements.push({ type: "newline" });
}
} else {
// Otros tags: procesar hijos con contexto
$node.contents().each((i, child) => {
processNode(child, {
bold: isBold,
italic: isItalic,
link: context.link,
});
});
}
};
// Procesar body
$("body")
.contents()
.each((i, node) => {
processNode(node);
});
// Log de depuración: contar elementos por tipo
if (this._isDebugEnabled()) {
const paragraphs = elements.filter(
(e) => e.type === "paragraph",
).length;
const newlines = elements.filter((e) => e.type === "newline").length;
if (paragraphs > 0 || newlines > 0) {
this.log(
` 📋 Elementos parseados: ${paragraphs} párrafo(s), ${newlines} salto(s) de línea`,
);
}
}
return elements;
};
/**
* Helper: Renderizar línea acumulada de texto
*/
const flushCurrentLine = (
currentLine,
currentBold,
currentLink,
fontSize,
) => {
if (!currentLine) return;
const fontToUse = currentBold ? fontBold : font;
const color = currentLink ? rgb(0, 0.4, 0.8) : rgb(0, 0, 0);
addText(currentLine.trim(), fontSize, fontToUse, color, currentLink);
};
/**
* Helper: Procesar elemento de texto/link
*/
const processTextElement = (element, state, fontSize) => {
const payload = buildRichTextPayload(element);
// Si cambia formato o hay link, renderizar línea acumulada
if (shouldFlushRichTextState(state, payload)) {
flushCurrentLine(
state.currentLine,
state.currentBold,
state.currentLink,
fontSize,
);
state.currentLine = "";
}
const nextState = appendRichTextPayload(state, payload);
state.currentLine = nextState.currentLine;
state.currentBold = nextState.currentBold;
state.currentLink = nextState.currentLink;
};
/**
* Helper: Procesar elemento bullet
*/
const processBulletElement = (state, fontSize) => {
flushCurrentLine(
state.currentLine,
state.currentBold,
state.currentLink,
fontSize,
);
state.currentLine = "";
state.currentLink = null;
addText("• ", fontSize, font);
y += fontSize + 5;
};
/**
* Helper: Procesar elemento newline/paragraph
*/
const processNewlineElement = (
state,
fontSize,
addSpaceAfter = false,
) => {
flushCurrentLine(
state.currentLine,
state.currentBold,
state.currentLink,
fontSize,
);
state.currentLine = "";
state.currentLink = null;
y += getLineBreakOffset(fontSize, addSpaceAfter);
if (y < margin) {
page = pdfDoc.addPage();
y = height - margin;
}
};
/**
* Procesar elemento imagen
* Descarga, escala y renderiza la imagen en el PDF
* @param {Object} element - Elemento de tipo imagen {type: 'image', src, alt}
* @param {Object} state - Estado de renderizado {currentLine, currentBold, currentLink}
* @param {number} fontSize - Tamaño de fuente actual
*/
const processImageElement = async (element, state, fontSize) => {
// Renderizar línea acumulada antes de la imagen
flushCurrentLine(
state.currentLine,
state.currentBold,
state.currentLink,
fontSize,
);
state.currentLine = "";
state.currentLink = null;
// Descargar y embeder imagen
const image = await downloadAndEmbedImage(element.src);
if (image) {
// Escalado inteligente basado en dimensiones reales
const imageLayout = calculateImageRenderDimensions({
imageWidth: image.width,
imageHeight: image.height,
availableHeight: y - margin,
maxWidth: width - 2 * margin,
});
if (!imageLayout) {
addText(
`[Imagen: ${element.alt}]`,
fontSize - 1,
font,
rgb(0.5, 0.5, 0.5),
);
return;
}
const imgWidth = imageLayout.width;
const imgHeight = imageLayout.height;
// Verificar espacio en página
if (y - imgHeight < margin) {
page = pdfDoc.addPage();
y = height - margin;
}
page.drawImage(image, {
x: margin,
y: y - imgHeight,
width: imgWidth,
height: imgHeight,
});
y -= imgHeight + 10;
} else {
// Si falla, mostrar texto alternativo
addText(
`[Imagen: ${element.alt}]`,
fontSize - 1,
font,
rgb(0.5, 0.5, 0.5),
);
}
};
/**
* Renderizar contenido rico (HTML parseado) en el PDF
* @param {string} html - HTML a renderizar
* @param {number} fontSize - Tamaño de fuente
*/
const addRichContent = async (html, fontSize = 10) => {
if (!html) {
addText("Sin contenido", fontSize, font, rgb(0.6, 0.6, 0.6));
return;
}
const elements = parseHTMLContent(html);
if (elements.length === 0) {
addText("Sin contenido", fontSize, font, rgb(0.6, 0.6, 0.6));
return;
}
// Log de depuración: contar imágenes detectadas
if (this._isDebugEnabled()) {
const imageCount = countElementsByType(elements, "image");
if (imageCount > 0) {
this.log(
` 🖼️ ${imageCount} imagen(es) detectadas en el contenido HTML`,
);
}
}
const state = createRichContentState();
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
if (element.type === "text" || element.type === "link") {
processTextElement(element, state, fontSize);
} else if (element.type === "bullet") {
processBulletElement(state, fontSize);
} else if (element.type === "newline") {
processNewlineElement(state, fontSize, false);
} else if (element.type === "paragraph") {
processNewlineElement(state, fontSize, true);
} else if (element.type === "image") {
await processImageElement(element, state, fontSize);
}
}
flushCurrentLine(
state.currentLine,
state.currentBold,
state.currentLink,
fontSize,
);
};
// Obtener campos
const fields = workItem.fields || {};
// ENCABEZADO CON LINK
const workItemType = fields["System.WorkItemType"] || "Work Item";
const title = fields["System.Title"] || "Sin título";
const state = fields["System.State"] || "N/A";
const projectName = fields["System.TeamProject"] || "";
if (this._isDebugEnabled()) {
this.log(`🔍 Construyendo URL del work item...`);
this.log(
` - workItem._links?.html?.href: ${workItem._links?.html?.href || "NO PRESENTE"}`,
);
this.log(` - workItem.url: ${workItem.url || "NO PRESENTE"}`);
this.log(
` - organization (parámetro): ${organization || "NO PRESENTE"}`,
);
this.log(` - projectName: ${projectName || "NO PRESENTE"}`);
}
// Construir URL del work item (desde _links o manualmente)
const { organizationUrl, source: urlSource } = resolveWorkItemUrl({
workItem,
organization,
projectName,
workItemId,
});
if (this._isDebugEnabled()) {
if (urlSource === "workItem.url") {
this.log(
` ✅ URL construida desde workItem.url: ${organizationUrl}`,
);
} else if (urlSource === "manual") {
this.log(
` 🔗 URL del work item construida manualmente: ${organizationUrl}`,
);
} else if (urlSource === "links") {
this.log(` ✅ URL obtenida de _links: ${organizationUrl}`);
}
}
if (!organizationUrl) {
this.log(` ⚠️ ADVERTENCIA: No se pudo construir URL del work item`);
}
// Título completo en una línea: WorkItemType #ID - Title
const fullTitle = `${workItemType} #${workItemId} - ${title}`;
if (this._isDebugEnabled()) {
this.log(` 📋 Título completo: "${fullTitle}"`);
this.log(` 🔗 URL para título: "${organizationUrl}"`);
}
addText(
fullTitle,
14,
fontBold,
rgb(0, 0.4, 0.8),
organizationUrl, // Agregar link al título completo
);
addSpace();
// Estado con badge de color (usar color real de Azure DevOps si está disponible)
addText("Estado:", 10, font, rgb(0.4, 0.4, 0.4));
const stateColorHex = workItem.stateColor || null;
addBadge(state, getStateColor(state, stateColorHex));
addSpace();
addLine();
// METADATA
addText("INFORMACIÓN GENERAL", 12, fontBold);
addSpace();
const metadata = buildWorkItemMetadata({
fields,
workItemType,
state,
selectedFields,
});
for (const [label, value] of metadata) {
addText(`${label}: ${value}`, 10, font);
}
addSpace();
addLine();
// DESCRIPCIÓN
if (
selectedFields.includes("description") &&
fields["System.Description"]
) {
addText("DESCRIPCIÓN", 12, fontBold);
addSpace();
await addRichContent(fields["System.Description"], 10);
addSpace();
addLine();
}
// CRITERIOS DE ACEPTACIÓN
if (
selectedFields.includes("acceptanceCriteria") &&
fields["Microsoft.VSTS.Common.AcceptanceCriteria"]
) {
addText("CRITERIOS DE ACEPTACIÓN", 12, fontBold);
addSpace();
await addRichContent(
fields["Microsoft.VSTS.Common.AcceptanceCriteria"],
10,
);
addSpace();
addLine();
}
// COMENTARIOS (siempre incluidos si existen)
if (workItem.comments && workItem.comments.length > 0) {
this.log(
`💬 Agregando ${workItem.comments.length} comentario(s) al PDF`,
);
addText(`COMENTARIOS (${workItem.comments.length})`, 12, fontBold);
addSpace();
// Invertir orden: más reciente primero, más antiguo al final
const sortedComments = sortCommentsByCreatedDateDesc(workItem.comments);
this.log(` 🔄 Comentarios ordenados: más reciente primero`);
// Extraer todos los GUIDs únicos de menciones de todos los comentarios
const allGuids = extractMentionGuids(sortedComments);
// Obtener nombres reales de usuarios mencionados mediante API de identidades
let userMap = {};
if (allGuids.length > 0) {
if (this._isDebugEnabled()) {
this.log(
` 👥 Detectadas ${allGuids.length} mención(es) única(s) con GUID`,
);
this.log(` 🔍 Consultando API de identidades de Azure DevOps...`);
}
try {
const identitiesClient = axios.create({
auth: {
username: "",
password: pat,
},
headers: {
"Content-Type": "application/json",
},
timeout: 30000,
});
// API de identidades: requiere permiso "Identity (Read)" en el PAT
const identitiesUrl = buildIdentitiesUrl({
organization,
guids: allGuids,
});
if (this._isDebugEnabled()) {
this.log(` 🌐 URL: ${identitiesUrl.substring(0, 100)}...`);
}
const response = await identitiesClient.get(identitiesUrl);
const identities = response.data.value || [];
userMap = mapIdentitiesToUserMap(identities);
if (this._isDebugEnabled()) {
this.log(
` ✅ Obtenidos ${Object.keys(userMap).length} nombre(s) de usuario de ${allGuids.length} solicitados`,
);
}
} catch (error) {
const status = error.response?.status;
if (status === 401) {
this.log(
` ⚠️ Error 401: El PAT no tiene permisos para acceder a la API de identidades`,
);
this.log(
` 💡 Solución: Regenera el PAT con el permiso "Identity (Read)" o "User Profile (Read)"`,
);
this.log(
` ℹ️ Las menciones se mostrarán como "@Usuario" en lugar de nombres reales`,
);
} else if (status === 403) {
this.log(
` ⚠️ Error 403: Acceso denegado a la API de identidades`,
);
this.log(
` 💡 Verifica que el PAT tenga los permisos necesarios`,
);
} else {
this.log(
` ⚠️ Error obteniendo nombres de usuarios: ${error.message}`,
);
}
// userMap permanece vacío, se usará "Usuario" como fallback
}
}
for (const comment of sortedComments) {
let commentText = comment.text || "";
const author = comment.createdBy || "Unknown";
// Reemplazar menciones con GUID por nombres reales (o "Usuario" si no se pudo obtener)
const mentionResolution = replaceMentionGuidsWithNames(
commentText,
userMap,
);
commentText = mentionResolution.text;
if (mentionResolution.changed && this._isDebugEnabled()) {
if (mentionResolution.hasRealNames) {
this.log(
` ✅ ${mentionResolution.mentionCount} mención(es) reemplazadas con nombres reales`,
);
} else {
this.log(
` ⚠️ ${mentionResolution.mentionCount} mención(es) reemplazadas con "@Usuario" (nombres no disponibles)`,
);
}
}
const { dateDisplay } = formatCommentDateDisplay(comment, (msg) =>
this.log(msg),
);
// Renderizar comentario como card
await addCommentCard(author, dateDisplay, commentText);
}
addLine();
}
// CHILD ITEMS
if (
selectedFields.includes("childItems") &&
workItem.childItems &&
workItem.childItems.length > 0
) {
addText(`ITEMS HIJOS (${workItem.childItems.length})`, 12, fontBold);
addSpace();
for (const child of workItem.childItems) {
addText(`• #${child.id} - ${child.title} [${child.state}]`, 9, font);
}
addSpace();
addLine();
}
// Guardar PDF
const pdfBytes = await pdfDoc.save();
await fs.writeFile(outputPath, pdfBytes);
this.log(`✅ PDF generado exitosamente: ${fileName}`);
// Reporte final de warnings
if (this._errorCount > 0) {
this.log(
`⚠️ Se encontraron ${this._errorCount} advertencias durante la generación`,
);
if (this._warnings.length > 0 && this._isDebugEnabled()) {
this.log(` Detalle de advertencias:`);
this._warnings.forEach((warning, index) => {
this.log(` ${index + 1}. ${warning}`);
});
}
}
return outputPath;
} catch (error) {
this.log(`❌ Error generando PDF: ${error.message}`);
throw error;
}
}
/**
* Generar PDFs para múltiples work items
* @param {Array<Object>} workItemsData - Array de {workItem, selectedFields, folder, organization, pat}
* @param {string} baseOutputDirectory - Directorio base de SharePoint
* @param {Function} progressCallback - Callback para reportar progreso (opcional)
* @returns {Promise<Array<Object>>} Array de resultados {workItemId, success, path, error}
*/
async generateMultiplePDFs(
workItemsData,
baseOutputDirectory,
progressCallback = null,
) {
const results = [];
const total = workItemsData.length;
this.log(`\nGenerando ${total} PDF(s)...`);
for (let i = 0; i < workItemsData.length; i++) {
const { workItem, selectedFields, folder, organization, pat } =
workItemsData[i];
const workItemId = workItem.id;
try {
// Construir ruta de salida completa
// Si folder es una ruta absoluta (contiene : en Windows o empieza con / en Unix),
// usarla directamente. Si no, concatenarla con baseOutputDirectory
let outputDirectory;
if (path.isAbsolute(folder)) {
// Ruta absoluta seleccionada por el usuario - usar directamente
outputDirectory = folder;
} else {
// Ruta relativa (modo legacy) - concatenar con base
outputDirectory = path.join(baseOutputDirectory, folder);
}
// Reportar progreso
if (progressCallback) {
progressCallback(i + 1, total, workItemId);
}
this.log(`\n[${i + 1}/${total}] Procesando work item ${workItemId}...`);
// Generar PDF
const pdfPath = await this.generatePDF(
workItem,
selectedFields,
outputDirectory,
organization,
pat,
);
results.push({
workItemId,
success: true,
path: pdfPath,
folder,
error: null,
});
} catch (error) {
this.log(
`Error generando PDF del work item ${workItemId}: ${error.message}`,
);
results.push({
workItemId,
success: false,
path: null,
folder,
error: error.message,
});
}
}
// Resumen de resultados
const successCount = results.filter((r) => r.success).length;
const failCount = results.filter((r) => !r.success).length;
this.log(`\nResumen de generación:`);
this.log(` Exitosos: ${successCount}/${total}`);
if (failCount > 0) {
this.log(` Fallidos: ${failCount}/${total}`);
}
return results;
}
/**
* Cerrar navegador (no aplica para pdf-lib, mantener compatibilidad)
*/
async closeBrowser() {
// No hace nada, mantenido para compatibilidad
this.log("✅ Recursos liberados");
}
/**
* Verificar si un directorio existe, si no, crearlo
* @param {string} directory - Ruta del directorio
* @private
*/
async _ensureDirectory(directory) {
try {
await fs.access(directory);
} catch (error) {
// El directorio no existe, crearlo
this.log(`Creando directorio: ${directory}`);
await fs.mkdir(directory, { recursive: true });
}
}
/**
* Verificar si un archivo existe
* @param {string} filePath - Ruta del archivo
* @returns {Promise<boolean>}
* @private
*/
async _fileExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
/**
* Obtener información de un PDF generado
* @param {string} pdfPath - Ruta del PDF
* @returns {Promise<Object>} {exists, size, createdAt}
*/
async getPDFInfo(pdfPath) {
try {
const stats = await fs.stat(pdfPath);
return {
exists: true,
size: stats.size,
sizeFormatted: this._formatFileSize(stats.size),
createdAt: stats.birthtime,
modifiedAt: stats.mtime,
};
} catch (error) {
return {
exists: false,
size: 0,
sizeFormatted: "0 B",
createdAt: null,
modifiedAt: null,
};
}
}
/**
* Formatear tamaño de archivo
* @param {number} bytes - Tamaño en bytes
* @returns {string}
* @private
*/
_formatFileSize(bytes) {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB"];
const k = 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(2)} ${units[i]}`;
}
}
module.exports = WorkItemPDFGenerator;
|