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 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71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 5x 5x 5x 5x 5x 5x 11x 11x 11x 11x 11x 5x 5x 5x 5x 5x 5x 11x 11x 11x 4x 4x 11x 11x 11x 4x 4x 4x 11x 11x 11x 11x 11x 5x 5x 5x 11x 11x 11x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 11x 11x 11x 11x 11x 5x 5x 5x 5x 2x 2x 2x 5x 5x 5x 5x 5x 2x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 11x 11x 14x 5x 5x 6x 6x 6x 6x 6x 14x 8x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 2x 8x 4x 4x 14x 1x 1x 1x 1x 1x 14x 1x 1x 1x 1x 1x 1x 3x 9x 9x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 9x 2x 2x 7x 7x 7x 7x 7x 7x 7x 7x 7x 9x 7x 7x 6x 7x 6x 6x 6x 6x 6x 7x 1x 1x 7x 7x 9x 12x 12x 1x 1x 11x 6x 12x 4x 4x 4x 4x 4x 4x 4x 4x 2x 12x 2x 2x 2x 2x 12x 5x 5x 12x 3x 3x 3x 9x 1x 1x 1x 1x 1x 1x 17x 5x 5x 12x 12x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 8x 8x 4x 17x 1x 1x 3x 3x 17x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 21x 21x 21x 21x 32x 32x 32x 32x 1x 1x 1x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 56x 56x 56x 56x 57x 57x 57x 57x 1x 1x 1x 1x 1x 1x 70x 70x 70x 70x 70x 70x 70x 9x 6x 6x 9x 9x 9x 9x 9x 9x 9x 9x 9x 70x 70x 62x 62x 70x 70x 70x 1x 1x 1x 1x 1x 1x 10x 10x 4x 4x 4x 4x 4x 4x 6x 10x 5x 5x 16x 12x 12x 12x 4x 4x 4x 4x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 1x 1x 2x 16x 1x 1x 1x 1x 5x 10x 1x 1x 5x 5x 10x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 10x 10x 1x 1x 9x 10x 2x 2x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 10x 11x 11x 11x 11x 2x 2x 7x 11x 11x 11x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 11x 2x 2x 11x 4x 4x 4x 10x 1x 1x 1x 1x 1x 1x 66x 66x 66x 66x 66x 66x 66x 74x 9x 9x 65x 65x 65x 65x 65x 65x 65x 65x 66x 66x 66x 70x 65x 65x 68x 68x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 68x 68x 3x 3x 65x 65x 65x 5x 5x 5x 5x 70x 3x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 70x 2x 2x 2x 2x 2x 2x 70x 66x 66x 66x 66x 2x 2x 2x 2x 2x 2x 64x 64x 66x 1x 1x 1x 1x 1x 1x 22x 22x 22x 22x 1x 1x 1x 1x 1x 1x 28x 28x 8x 8x 20x 28x 1x 1x 1x 1x 1x 1x 73x 73x 9x 9x 64x 73x 1x 1x 1x 1x 1x 1x 852x 852x 852x 852x 15959x 15959x 15959x 15959x 15959x 15959x 15959x 15959x 15959x 15959x 15959x 15959x 15959x 852x 852x 852x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 5x 5x 17x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 9x 9x 9x 9x 9x 9x 2x 2x 2x 2x 2x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 1x 1x 1x 1x 1x 1x 9x 3x 3x 6x 9x 1x 1x 1x 1x 5x 5x 5x 9x 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 5x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 16x 16x 16x 6x 6x 6x 6x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 6x 6x 6x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 6x 6x 6x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 42x 42x 42x 42x 1x 1x 1x 1x 1x 1x 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 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 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 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 15x 22x 22x 22x 22x 22x 22x 22x 19x 4x 4x 19x 19x 19x 19x 19x 19x 19x 19x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 19x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 19x 3x 3x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x 1x 1x 1x 1x 1x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 1x 1x 1x 1x 1x 1x 25x 8x 8x 17x 25x 11x 11x 6x 6x 25x 25x 25x 1x 1x 1x 1x 1x 1x 47x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 47x 1x 1x 1x 1x 1x 1x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 3x 3x 1x 1x 2x 2x 3x 1x 1x 44x 44x 3x 3x 1x 1x 2x 2x 3x 1x 1x 44x 44x 4x 4x 44x 44x 44x 1x 1x 1x | /**
* TestPlanGenerator - Genera documentos de planes de prueba automáticamente
*
* A partir de un Work Item de Azure DevOps y sus PRs asociados, genera
* un plan de pruebas funcionales con escenarios generados por IA.
*
* Incluye integración con PR Review de G-Bot para casos de prueba específicos.
*
* @author Thunderlight Team
* @date 2026-08-03
*/
const {
Document,
Paragraph,
TextRun,
ImageRun,
ExternalHyperlink,
InternalHyperlink,
BookmarkStart,
BookmarkEnd,
Table,
TableRow,
TableCell,
Header,
HeadingLevel,
AlignmentType,
Packer,
WidthType,
BorderStyle,
} = require("docx");
const fs = require("fs").promises;
const path = require("path");
const os = require("os");
const axios = require("axios");
class TestPlanGenerator {
/**
* @param {WorkItemService} workItemService - Servicio de Work Items
* @param {AzureDevOpsService} azureDevOpsService - Servicio de Azure DevOps
* @param {SummaryService} summaryService - Servicio de IA
* @param {Function} logCallback - Función para logging
*/
constructor(
workItemService,
azureDevOpsService,
summaryService,
logCallback = null
) {
this.workItemService = workItemService;
this.azureDevOpsService = azureDevOpsService;
this.summaryService = summaryService;
this.logCallback = logCallback;
this._bookmarkSequence = 1;
this._scenarioImageCache = new Map();
}
/**
* Log interno
*/
log(message) {
if (this.logCallback) {
this.logCallback(message);
}
}
/**
* Genera un plan de pruebas completo
*
* @param {Object} options - Opciones de generación
* @param {string} options.workItemUrl - URL completa del Work Item
* @param {Array<string>} options.pullRequestUrls - URLs de PRs asociados
* @param {string} options.additionalContext - Contexto adicional
* @param {string} options.outputPath - Ruta donde guardar el documento
* @param {boolean} options.useAI - Si usar IA para generar escenarios
* @returns {Promise<Object>} Resultado con {success, path, scenarios, log}
*/
async generateTestPlan(options) {
const {
workItemUrl,
pullRequestUrls = [],
additionalContext = "",
outputPath = null,
useAI = true,
aiModel = null,
} = options;
if (!workItemUrl) {
throw new Error("workItemUrl es requerido");
}
const normalizedWorkItemUrl = String(workItemUrl).trim();
const normalizedPullRequestUrls = this._normalizePullRequestUrls(
pullRequestUrls,
);
if (!this._isValidWorkItemUrl(normalizedWorkItemUrl)) {
throw new Error(
"El URL del Work Item no tiene un formato válido de Azure DevOps.",
);
}
const invalidPullRequestUrl = normalizedPullRequestUrls.find(
(url) => !this._isValidPullRequestUrl(url),
);
if (invalidPullRequestUrl) {
throw new Error(`URL de Pull Request inválida: ${invalidPullRequestUrl}`);
}
if (normalizedPullRequestUrls.length > 0 && !this.azureDevOpsService) {
throw new Error(
"No hay configuración de Azure DevOps (Git/PRs) para analizar las URLs de Pull Request.",
);
}
try {
this.log(`${"═".repeat(60)}`);
this.log("🧪 INICIANDO GENERACIÓN DE PLAN DE PRUEBAS");
this.log(`${"═".repeat(60)}`);
// PASO 1: Parsear URL del Work Item y obtener detalles
this.log("\n📋 PASO 1/5: Obteniendo Work Item...");
const workItemInfo = this._parseWorkItemUrl(normalizedWorkItemUrl);
if (!workItemInfo) {
throw new Error("URL de Work Item inválida");
}
this.log(` ✓ Organización: ${workItemInfo.organization}`);
this.log(` ✓ Proyecto: ${workItemInfo.project}`);
this.log(` ✓ Work Item ID: ${workItemInfo.workItemId}`);
const workItem = await this.workItemService.getWorkItemDetails(
workItemInfo.workItemId
);
this.log(` ✅ Work Item obtenido: ${workItem.fields["System.Title"]}`);
let workItemAttachments = [];
try {
workItemAttachments = await this.workItemService.getWorkItemAttachments(
workItemInfo.workItemId
);
this.log(` ✅ Adjuntos del Work Item: ${workItemAttachments.length}`);
} catch (attachmentError) {
this.log(` ⚠️ No se pudieron obtener adjuntos del Work Item: ${attachmentError.message}`);
}
// PASO 2: Procesar Pull Requests
this.log("\n🔍 PASO 2/5: Procesando Pull Requests...");
const pullRequests = await this._processPullRequestUrls(
normalizedPullRequestUrls,
);
if (pullRequests.length > 0) {
this.log(` ✅ ${pullRequests.length} PR(s) procesado(s):`);
pullRequests.forEach((pr) => {
this.log(` • [${pr.repository}] #${pr.pullRequestId} - ${pr.title}`);
});
} else {
this.log(" ⚠️ No se proporcionaron URLs de PRs");
}
// PASO 3: Analizar archivos modificados
this.log("\n📁 PASO 3/5: Analizando archivos modificados...");
let filesChanged = [];
let prComments = [];
if (pullRequests.length > 0) {
filesChanged = await this._analyzeChangedFilesMultiplePRs(pullRequests);
this.log(` ✅ ${filesChanged.length} archivo(s) modificado(s)`);
// Obtener comentarios de PRs (incluye PR Review de G-Bot)
prComments = await this._getPullRequestComments(pullRequests);
this.log(` ✅ ${prComments.length} comentario(s) de PR capturado(s)`);
} else {
this.log(" ⚠️ Sin análisis de archivos (no hay PRs)");
}
// PASO 4: Generar escenarios de prueba con IA
this.log("\n🤖 PASO 4/5: Generando escenarios de prueba...");
const context = this._buildTestContext(
workItem,
pullRequests,
filesChanged,
prComments,
workItemAttachments,
additionalContext
);
// Determinar modelo de IA a usar
let preferredModel = aiModel || "gpt-4o";
if (!aiModel) {
try {
const vscode = require("vscode");
const config = vscode.workspace.getConfiguration("gbot.testPlan");
preferredModel = config.get("aiModel", "gpt-4o");
} catch (error) {
// Si vscode no está disponible (tests), usar default
preferredModel = "gpt-4o";
}
}
const scenarios = await this._generateTestScenarios(context, useAI, preferredModel);
this.log(` ✅ ${scenarios.length} escenario(s) generado(s)`);
// PASO 5: Crear documento Word
this.log("\n📄 PASO 5/5: Creando documento Word...");
const finalOutputPath = outputPath || this._getDefaultOutputPath(workItem);
const documentData = {
workItem,
workItemUrl: normalizedWorkItemUrl,
pullRequests,
filesChanged,
scenarios,
context,
};
await this._createWordDocument(documentData, finalOutputPath);
this.log(` ✅ Documento creado: ${finalOutputPath}`);
// Resultado final
this.log(`\n${"═".repeat(60)}`);
this.log("✅ PLAN DE PRUEBAS GENERADO EXITOSAMENTE");
this.log(`${"═".repeat(60)}`);
return {
success: true,
path: finalOutputPath,
scenarios,
log: "Generación completada",
};
} catch (error) {
this.log(`\n❌ ERROR: ${error.message}`);
throw error;
}
}
/**
* Obtiene ruta por defecto para guardar el documento
* @private
*/
_getDefaultOutputPath(workItem) {
const documentsDir = path.join(os.homedir(), "Documents", "G-Bot");
const workItemId = workItem?.id || "AUTO";
const rawTitle = String(workItem?.fields?.["System.Title"] || "").trim();
const safeTitle = this._sanitizeFileNamePart(rawTitle) || "Sin titulo";
const filename = `Pruebas THL- ${workItemId} ${safeTitle}.docx`;
return path.join(documentsDir, filename);
}
/**
* Sanitiza parte de nombre de archivo conservando legibilidad para negocio.
* @private
*/
_sanitizeFileNamePart(value, maxLen = 140) {
const text = String(value || "")
.replace(/[<>:"/\\|?*]/g, " ")
.replace(/\s+/g, " ")
.trim();
if (!text) {
return "";
}
if (text.length <= maxLen) {
return text;
}
const cropped = text.slice(0, maxLen);
const lastSpace = cropped.lastIndexOf(" ");
return (lastSpace > 0 ? cropped.slice(0, lastSpace) : cropped).trim();
}
/**
* Resuelve plantilla de referencia para plan de pruebas desde resources/templates.
* @private
*/
async _resolveTemplateReferencePath() {
try {
const templatesDir = path.join(__dirname, "..", "..", "resources", "templates");
const files = await fs.readdir(templatesDir);
const htmlTemplates = files.filter(
(file) =>
file.toLowerCase().endsWith(".html") ||
file.toLowerCase().endsWith(".htm"),
);
const docxTemplates = files.filter((file) => file.toLowerCase().endsWith(".docx"));
if (htmlTemplates.length > 0) {
return path.join(templatesDir, htmlTemplates[0]);
}
if (docxTemplates.length === 0) {
return null;
}
return path.join(templatesDir, docxTemplates[0]);
} catch {
return null;
}
}
/**
* Normaliza URLs de Pull Request eliminando vacíos y duplicados.
* @private
*/
_normalizePullRequestUrls(pullRequestUrls) {
if (!Array.isArray(pullRequestUrls)) {
return [];
}
return [...new Set(
pullRequestUrls
.map((url) => String(url || "").trim())
.filter(Boolean),
)];
}
/**
* Valida formato de URL de Work Item.
* @private
*/
_isValidWorkItemUrl(url) {
return Boolean(this._parseWorkItemUrl(url));
}
/**
* Valida formato de URL de Pull Request.
* @private
*/
_isValidPullRequestUrl(url) {
return Boolean(this._parsePullRequestUrl(url));
}
/**
* Intenta derivar color principal desde la plantilla HTML de referencia.
* @private
*/
async _resolveTemplateVisualProfile(templatePath) {
const defaults = {
scenarioLabelFill: "156082",
scenarioLabelText: "FFFFFF",
tableBorderColor: "FFFFFF",
bodyFontFamily: "Calibri",
bodyFontSizePt: 12,
heading1FontFamily: "Calibri",
heading1FontSizePt: 20,
heading2FontFamily: "Calibri",
heading2FontSizePt: 16,
headingColor: "000000",
bodyColor: "000000",
logoWidthPx: 353,
logoHeightPx: 121,
pageMarginTopPt: 36,
pageMarginRightPt: 36,
pageMarginBottomPt: 36,
pageMarginLeftPt: 36,
headerMarginPt: 35.45,
footerMarginPt: 35.45,
coverTitleFontFamily: "Arial",
coverTitleFontSizePt: 17,
coverLineHeightPercent: 115,
coverTitleMarginTopPt: 12,
coverTitleMarginBottomPt: 12,
coverBlankLinesBeforeLogo: 5,
coverBlankLinesAfterLogo: 4,
};
if (!templatePath) {
return defaults;
}
try {
const templateExt = path.extname(templatePath).toLowerCase();
const html = await fs.readFile(templatePath, "latin1");
if (templateExt === ".htm" || templateExt === ".html") {
const normalStyleMatch = html.match(
/p\.MsoNormal[\s\S]*?font-size:([0-9.]+)pt;[\s\S]*?font-family:"?([^,";]+)"?/i,
);
if (normalStyleMatch) {
defaults.bodyFontSizePt = Number(normalStyleMatch[1]) || defaults.bodyFontSizePt;
defaults.bodyFontFamily =
this._sanitizeTemplateFontFamily(normalStyleMatch[2]) ||
defaults.bodyFontFamily;
}
const heading1Match = html.match(
/h1[\s\S]*?font-size:([0-9.]+)pt;[\s\S]*?font-family:"?([^,";]+)"?/i,
);
if (heading1Match) {
defaults.heading1FontSizePt =
Number(heading1Match[1]) || defaults.heading1FontSizePt;
defaults.heading1FontFamily =
this._sanitizeTemplateFontFamily(heading1Match[2]) ||
defaults.heading1FontFamily;
}
const heading2Match = html.match(
/h2[\s\S]*?font-size:([0-9.]+)pt;[\s\S]*?font-family:"?([^,";]+)"?/i,
);
if (heading2Match) {
defaults.heading2FontSizePt =
Number(heading2Match[1]) || defaults.heading2FontSizePt;
defaults.heading2FontFamily =
this._sanitizeTemplateFontFamily(heading2Match[2]) ||
defaults.heading2FontFamily;
}
const scenarioLabelFillMatch = html.match(/background:#([0-9A-Fa-f]{6})/i);
if (scenarioLabelFillMatch && scenarioLabelFillMatch[1]) {
defaults.scenarioLabelFill = scenarioLabelFillMatch[1].toUpperCase();
}
const tableBorderMatch = html.match(/border:solid\s+([A-Za-z#0-9]+)\s+1\.0pt/i);
if (tableBorderMatch && tableBorderMatch[1]) {
const colorToken = String(tableBorderMatch[1]).toLowerCase();
defaults.tableBorderColor = colorToken === "white" ? "FFFFFF" : defaults.tableBorderColor;
}
const logoSizeMatch = html.match(
/<img[^>]*width=([0-9]+)[^>]*height=([0-9]+)[^>]*src=["'][^"']+["']/i,
);
if (logoSizeMatch) {
defaults.logoWidthPx = Number(logoSizeMatch[1]) || defaults.logoWidthPx;
defaults.logoHeightPx = Number(logoSizeMatch[2]) || defaults.logoHeightPx;
}
const pageSectionMatch = html.match(/@page\s+WordSection1\s*\{([\s\S]*?)\}/i);
if (pageSectionMatch && pageSectionMatch[1]) {
const pageSectionCss = pageSectionMatch[1];
const marginMatch = pageSectionCss.match(
/margin:\s*([0-9.]+)pt\s+([0-9.]+)pt\s+([0-9.]+)pt\s+([0-9.]+)pt/i,
);
if (marginMatch) {
defaults.pageMarginTopPt = Number(marginMatch[1]) || defaults.pageMarginTopPt;
defaults.pageMarginRightPt =
Number(marginMatch[2]) || defaults.pageMarginRightPt;
defaults.pageMarginBottomPt =
Number(marginMatch[3]) || defaults.pageMarginBottomPt;
defaults.pageMarginLeftPt = Number(marginMatch[4]) || defaults.pageMarginLeftPt;
}
const headerMarginMatch = pageSectionCss.match(/mso-header-margin:\s*([0-9.]+)pt/i);
if (headerMarginMatch) {
defaults.headerMarginPt = Number(headerMarginMatch[1]) || defaults.headerMarginPt;
}
const footerMarginMatch = pageSectionCss.match(/mso-footer-margin:\s*([0-9.]+)pt/i);
if (footerMarginMatch) {
defaults.footerMarginPt = Number(footerMarginMatch[1]) || defaults.footerMarginPt;
}
}
const coverTitleBlockMatch = html.match(
/<p class=MsoNormal align=center[^>]*>[\s\S]*?Pruebas[\s\S]*?<\/p>/i,
);
if (coverTitleBlockMatch && coverTitleBlockMatch[0]) {
const coverTitleBlock = coverTitleBlockMatch[0];
const coverTitleMarginTopMatch = coverTitleBlock.match(/margin-top:([0-9.]+)pt/i);
if (coverTitleMarginTopMatch) {
defaults.coverTitleMarginTopPt =
Number(coverTitleMarginTopMatch[1]) || defaults.coverTitleMarginTopPt;
}
const coverTitleMarginBottomMatch = coverTitleBlock.match(
/margin-bottom:([0-9.]+)pt/i,
);
if (coverTitleMarginBottomMatch) {
defaults.coverTitleMarginBottomPt =
Number(coverTitleMarginBottomMatch[1]) || defaults.coverTitleMarginBottomPt;
}
const coverTitleFontMatch = coverTitleBlock.match(
/font-size:([0-9.]+)pt;[\s\S]*?font-family:"?([^,";]+)"?/i,
);
if (coverTitleFontMatch) {
defaults.coverTitleFontSizePt =
Number(coverTitleFontMatch[1]) || defaults.coverTitleFontSizePt;
defaults.coverTitleFontFamily =
this._sanitizeTemplateFontFamily(coverTitleFontMatch[2]) ||
defaults.coverTitleFontFamily;
}
}
}
if (templateExt === ".htm") {
return defaults;
}
const colorMatches = [
...html.matchAll(/\.fc\d+\{color:rgb\((\d+),(\d+),(\d+)\);\}/g),
];
for (const match of colorMatches) {
const r = Number(match[1]);
const g = Number(match[2]);
const b = Number(match[3]);
const isDark = r < 35 && g < 35 && b < 35;
const isLight = r > 235 && g > 235 && b > 235;
const isGray = Math.abs(r - g) < 8 && Math.abs(g - b) < 8;
if (!isDark && !isLight && !isGray) {
defaults.scenarioLabelFill = this._rgbToHex(r, g, b);
return defaults;
}
}
return defaults;
} catch (error) {
this.log(
` ⚠️ No se pudo leer perfil visual de plantilla HTML: ${error.message}`,
);
return defaults;
}
}
/**
* Convierte RGB numérico a HEX de 6 caracteres.
* @private
*/
_rgbToHex(r, g, b) {
const toHex = (value) => {
const normalized = Math.max(0, Math.min(255, Number(value) || 0));
return normalized.toString(16).padStart(2, "0").toUpperCase();
};
return `${toHex(r)}${toHex(g)}${toHex(b)}`;
}
/**
* Resuelve logo desde templates para portada.
* @private
*/
async _resolveTemplateLogoBuffer(templatePath) {
if (!templatePath) {
return null;
}
const templateDir = path.dirname(templatePath);
const templateExt = path.extname(templatePath).toLowerCase();
const candidatePaths = [];
// Logo explícito configurable por convención.
candidatePaths.push(path.join(templateDir, "image.png"));
candidatePaths.push(path.join(templateDir, "logo.png"));
if (templateExt === ".htm" || templateExt === ".html") {
try {
const html = await fs.readFile(templatePath, "latin1");
const imgSrcMatch = html.match(/<img[^>]*src=["']([^"']+)["']/i);
if (imgSrcMatch && imgSrcMatch[1]) {
const src = this._decodeHtmlEntities(imgSrcMatch[1])
.replace(/^\.\//, "")
.replace(/^\//, "");
candidatePaths.unshift(path.join(templateDir, src));
}
} catch {
// Si falla lectura de HTML, continuamos con paths por convención.
}
}
for (const candidatePath of candidatePaths) {
try {
if (!candidatePath) {
continue;
}
const buffer = await fs.readFile(candidatePath);
const imageType = this._detectSupportedImageType(buffer);
if (buffer && buffer.length > 0 && imageType) {
this.log(
` 🖼️ Logo detectado: ${path.basename(candidatePath)} (${imageType})`,
);
return {
data: buffer,
type: imageType,
};
}
if (buffer && buffer.length > 0) {
this.log(
` ⚠️ Logo descartado por formato no compatible para Word Online: ${path.basename(candidatePath)}`,
);
}
} catch {
// Probar siguiente candidato.
}
}
this.log(" ⚠️ No se encontró logo en templates (image.png/logo.png).");
return null;
}
/**
* Detecta tipo de imagen compatible con DOCX (PNG/JPEG).
* @private
*/
_detectSupportedImageType(buffer) {
if (!buffer || buffer.length < 4) {
return null;
}
const isPng =
buffer.length >= 8 &&
buffer[0] === 0x89 &&
buffer[1] === 0x50 &&
buffer[2] === 0x4e &&
buffer[3] === 0x47 &&
buffer[4] === 0x0d &&
buffer[5] === 0x0a &&
buffer[6] === 0x1a &&
buffer[7] === 0x0a;
const isJpeg =
buffer[0] === 0xff &&
buffer[1] === 0xd8 &&
buffer[2] === 0xff;
if (isPng) {
return "png";
}
if (isJpeg) {
return "jpg";
}
return null;
}
/**
* Crea un párrafo con etiqueta en negrita y detalle normal.
* @private
*/
_createIndentedLabeledParagraph(label, detail, indent = undefined) {
const safeLabel = this._sanitizeDocxText(label || "");
const safeDetail = this._sanitizeDocxText(detail || "");
return new Paragraph({
indent,
children: [
new TextRun({
text: safeLabel,
bold: true,
}),
...(safeDetail
? [
new TextRun({
text: safeDetail,
}),
]
: []),
],
});
}
/**
* Crea un párrafo con viñeta y etiqueta en negrita.
* @private
*/
_createIndentedBulletLabeledParagraph(label, detail, indent = undefined) {
const safeLabel = this._sanitizeDocxText(label || "");
const safeDetail = this._sanitizeDocxText(detail || "");
return new Paragraph({
indent,
children: [
new TextRun({
text: "• ",
}),
new TextRun({
text: safeLabel,
bold: true,
}),
...(safeDetail
? [
new TextRun({
text: safeDetail,
}),
]
: []),
],
});
}
/**
* Extrae segmentos de texto e imágenes markdown de una cadena.
* @private
*/
_tokenizeMarkdownImages(value) {
const text = String(value || "");
const tokens = [];
const pattern = /!\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/gi;
let cursor = 0;
let match;
while ((match = pattern.exec(text)) !== null) {
if (match.index > cursor) {
tokens.push({ type: "text", value: text.slice(cursor, match.index) });
}
tokens.push({
type: "image",
alt: this._sanitizeDocxText(match[1] || ""),
url: String(match[2] || "").trim(),
});
cursor = pattern.lastIndex;
}
if (cursor < text.length) {
tokens.push({ type: "text", value: text.slice(cursor) });
}
return tokens;
}
/**
* Detecta dimensiones para imagen PNG/JPEG.
* @private
*/
_readImageDimensions(buffer, type) {
try {
if (type === "png" && buffer.length >= 24) {
const width = buffer.readUInt32BE(16);
const height = buffer.readUInt32BE(20);
if (width > 0 && height > 0) {
return { width, height };
}
}
if (type === "jpg" && buffer.length > 4) {
let offset = 2;
while (offset < buffer.length - 9) {
if (buffer[offset] !== 0xff) {
offset += 1;
continue;
}
const marker = buffer[offset + 1];
const size = buffer.readUInt16BE(offset + 2);
const isSofMarker =
marker >= 0xc0 &&
marker <= 0xcf &&
marker !== 0xc4 &&
marker !== 0xc8 &&
marker !== 0xcc;
if (isSofMarker && offset + 8 < buffer.length) {
const height = buffer.readUInt16BE(offset + 5);
const width = buffer.readUInt16BE(offset + 7);
if (width > 0 && height > 0) {
return { width, height };
}
}
if (!size || size < 2) {
break;
}
offset += 2 + size;
}
}
} catch {
// Fallback a tamaño por defecto.
}
return { width: 640, height: 360 };
}
/**
* Ajusta tamaño de imagen para caber en celdas de escenarios.
* @private
*/
_buildScenarioImageTransformation(buffer, type) {
const maxWidth = 460;
const maxHeight = 300;
const dims = this._readImageDimensions(buffer, type);
const width = Math.max(1, Number(dims.width) || maxWidth);
const height = Math.max(1, Number(dims.height) || maxHeight);
const ratio = Math.min(maxWidth / width, maxHeight / height, 1);
return {
width: Math.max(1, Math.round(width * ratio)),
height: Math.max(1, Math.round(height * ratio)),
};
}
/**
* Descarga y cachea una imagen para insertar en DOCX.
* @private
*/
async _resolveScenarioImageAsset(url) {
const normalizedUrl = this._normalizeHyperlinkUrl(url) || String(url || "").trim();
if (!normalizedUrl) {
return null;
}
if (this._scenarioImageCache.has(normalizedUrl)) {
return this._scenarioImageCache.get(normalizedUrl);
}
const requestConfig = {
responseType: "arraybuffer",
timeout: 15000,
validateStatus: () => true,
headers: {
Accept: "image/*,*/*;q=0.8",
},
};
const candidates = [normalizedUrl, encodeURI(normalizedUrl)].filter(Boolean);
for (const candidate of candidates) {
try {
const client = this.workItemService?.azureService?.client || axios;
const response = await client.get(candidate, requestConfig);
if (!response || response.status < 200 || response.status >= 300) {
continue;
}
const buffer = Buffer.from(response.data || []);
const type = this._detectSupportedImageType(buffer);
if (!type) {
continue;
}
const asset = {
data: buffer,
type,
transformation: this._buildScenarioImageTransformation(buffer, type),
};
this._scenarioImageCache.set(normalizedUrl, asset);
return asset;
} catch {
// Probar siguiente candidato de URL.
}
}
this._scenarioImageCache.set(normalizedUrl, null);
return null;
}
/**
* Convierte texto con markdown de imágenes en párrafos DOCX con imágenes embebidas.
* @private
*/
async _buildRichParagraphsFromMarkdown(text, options = {}) {
const { prefix = "" } = options;
const tokens = this._tokenizeMarkdownImages(this._sanitizeDocxText(text || ""));
const paragraphs = [];
let currentRuns = [];
let pendingPrefix = this._sanitizeDocxText(prefix || "");
const flushCurrentRuns = () => {
if (currentRuns.length === 0) {
return;
}
paragraphs.push(
new Paragraph({
children: currentRuns,
}),
);
currentRuns = [];
pendingPrefix = "";
};
for (const token of tokens) {
if (token.type === "text") {
const parts = String(token.value || "").split("\n");
parts.forEach((part, index) => {
const safePart = this._sanitizeDocxText(part);
if (safePart) {
const textWithPrefix = pendingPrefix
? `${pendingPrefix}${safePart}`
: safePart;
currentRuns.push(
new TextRun({
text: textWithPrefix,
}),
);
pendingPrefix = "";
}
if (index < parts.length - 1) {
flushCurrentRuns();
}
});
continue;
}
flushCurrentRuns();
const imageAsset = await this._resolveScenarioImageAsset(token.url);
if (imageAsset) {
if (pendingPrefix) {
paragraphs.push(
new Paragraph({
text: `${pendingPrefix}Imagen adjunta`,
}),
);
pendingPrefix = "";
}
paragraphs.push(
new Paragraph({
children: [
new ImageRun({
data: imageAsset.data,
type: imageAsset.type,
transformation: imageAsset.transformation,
}),
],
}),
);
} else {
const fallbackText = pendingPrefix
? `${pendingPrefix}Imagen adjunta no disponible.`
: "Imagen adjunta no disponible.";
paragraphs.push(new Paragraph({ text: this._sanitizeDocxText(fallbackText) }));
pendingPrefix = "";
}
}
flushCurrentRuns();
if (paragraphs.length === 0) {
return [
new Paragraph({
text: this._sanitizeDocxText(prefix ? `${prefix}-` : "-"),
}),
];
}
return paragraphs;
}
/**
* Limpia family de fuente para usarla en estilos DOCX.
* @private
*/
_sanitizeTemplateFontFamily(value) {
return String(value || "")
.replace(/["']/g, "")
.trim();
}
/**
* Convierte puntos tipográficos a half-points de docx.
* @private
*/
_toDocxHalfPoint(sizePt, fallback) {
const numeric = Number(sizePt);
if (!Number.isFinite(numeric) || numeric <= 0) {
return fallback;
}
return Math.round(numeric * 2);
}
/**
* Convierte puntos tipográficos a twips para márgenes/espaciados DOCX.
* @private
*/
_toTwip(sizePt, fallback) {
const numeric = Number(sizePt);
if (!Number.isFinite(numeric) || numeric < 0) {
return fallback;
}
return Math.round(numeric * 20);
}
/**
* Sanitiza texto para XML de DOCX (evita caracteres de control inválidos en Word Online).
* @private
*/
_sanitizeDocxText(value) {
const raw = String(value || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
let sanitized = "";
for (const char of raw) {
const codePoint = char.codePointAt(0);
const isAllowed =
codePoint === 0x9 ||
codePoint === 0xa ||
codePoint === 0xd ||
(codePoint >= 0x20 && codePoint <= 0xd7ff) ||
(codePoint >= 0xe000 && codePoint <= 0xfffd) ||
(codePoint >= 0x10000 && codePoint <= 0x10ffff);
if (isAllowed) {
sanitized += char;
}
}
return sanitized.replace(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/gu, "");
}
/**
* Normaliza URL para vínculos externos en DOCX.
* @private
*/
_normalizeHyperlinkUrl(value) {
try {
const normalized = new URL(String(value || "").trim());
return normalized.toString();
} catch {
return "";
}
}
/**
* Parsear URL de Work Item de Azure DevOps
* @private
*/
_parseWorkItemUrl(url) {
try {
const normalizedUrl = url.trim();
// Patrón: https://dev.azure.com/{org}/{project}/_workitems/edit/{id}
let pattern = /dev\.azure\.com\/([^\/]+)\/([^\/]+)\/_workitems\/edit\/(\d+)/i;
let match = normalizedUrl.match(pattern);
if (match) {
return {
organization: decodeURIComponent(match[1]),
project: decodeURIComponent(match[2]),
workItemId: parseInt(match[3], 10),
};
}
// Patrón alternativo: ?workitem={id}
pattern = /dev\.azure\.com\/([^\/]+)\/([^\/]+)\/_boards.*[?&]workitem=(\d+)/i;
match = normalizedUrl.match(pattern);
if (match) {
return {
organization: decodeURIComponent(match[1]),
project: decodeURIComponent(match[2]),
workItemId: parseInt(match[3], 10),
};
}
return null;
} catch (error) {
this.log(` ⚠️ Error parseando URL: ${error.message}`);
return null;
}
}
/**
* Procesar URLs de Pull Requests proporcionadas
* @private
*/
async _processPullRequestUrls(pullRequestUrls) {
if (!pullRequestUrls || pullRequestUrls.length === 0) {
return [];
}
if (!this.azureDevOpsService) {
throw new Error(
"AzureDevOpsService no está inicializado para procesar Pull Requests.",
);
}
const pullRequests = [];
for (const url of pullRequestUrls) {
try {
const prInfo = this._parsePullRequestUrl(url);
if (!prInfo) {
this.log(` ⚠️ URL inválida: ${url}`);
continue;
}
const prDetails = await this.azureDevOpsService.getPullRequestDetails(
prInfo.project,
prInfo.repository,
prInfo.pullRequestId
);
pullRequests.push({
pullRequestId: prInfo.pullRequestId,
title: prDetails.title || "Sin título",
repository: prInfo.repository,
project: prInfo.project,
url: url,
status: prDetails.status || "Unknown",
});
} catch (error) {
this.log(` ⚠️ Error procesando PR ${url}: ${error.message}`);
}
}
return pullRequests;
}
/**
* Parsear URL de Pull Request
* @private
*/
_parsePullRequestUrl(url) {
try {
const normalizedUrl = url.trim();
const pattern = /dev\.azure\.com\/[^\/]+\/([^\/]+)\/_git\/([^\/]+)\/pullrequest\/(\d+)/i;
const match = normalizedUrl.match(pattern);
if (!match) {
return null;
}
return {
project: decodeURIComponent(match[1]),
repository: decodeURIComponent(match[2]),
pullRequestId: parseInt(match[3], 10),
};
} catch (error) {
return null;
}
}
/**
* Obtener comentarios de revisión de PRs (incluye G-Bot PR Review)
* @private
*/
async _getPullRequestComments(pullRequests) {
const allComments = [];
for (const pr of pullRequests) {
try {
const threads = await this.azureDevOpsService.getPullRequestThreads(
pr.project,
pr.repository,
pr.pullRequestId
);
threads.forEach((thread) => {
if (thread.comments && thread.comments.length > 0) {
thread.comments.forEach((comment) => {
if (comment.author && comment.content) {
const commentType = this._detectCommentType(comment.content);
allComments.push({
repository: pr.repository,
pullRequestId: pr.pullRequestId,
author: comment.author.displayName || "Unknown",
content: this._stripHtml(comment.content),
commentType,
});
}
});
}
});
} catch (error) {
this.log(` ⚠️ Error obteniendo comentarios: ${error.message}`);
}
}
return allComments;
}
/**
* Detectar tipo de comentario de PR
* @private
*/
_detectCommentType(content) {
if (content.includes("Revisión Automática de PR") ||
content.includes("Issues Encontrados")) {
return "pr-review";
}
if (content.includes("Revisión de Seguimiento")) {
return "follow-up";
}
if (content.match(/Issue \[\d+\] - (Aplica|No Aplica)/)) {
return "developer-response";
}
return "general";
}
/**
* Analizar archivos modificados en múltiples PRs
* @private
*/
async _analyzeChangedFilesMultiplePRs(pullRequests) {
const allFilesChanged = [];
for (const pr of pullRequests) {
try {
this.log(` 📦 Analizando ${pr.repository}...`);
const changesResponse = await this.azureDevOpsService.getPullRequestChanges(
pr.project,
pr.repository,
pr.pullRequestId
);
// getPullRequestChanges devuelve un objeto con { allFiles, totalFiles, ... }
const changes = Array.isArray(changesResponse)
? changesResponse
: (changesResponse?.allFiles || []);
const filesInPR = changes
.filter((change) => change.changeType !== "delete")
.map((change) => ({
path: change.item?.path || change.path || "Unknown",
changeType: change.changeType,
isNew: change.changeType === "add",
isModified: change.changeType === "edit",
repository: pr.repository,
pullRequestId: pr.pullRequestId,
}));
allFilesChanged.push(...filesInPR);
} catch (error) {
this.log(` ⚠️ Error analizando PR: ${error.message}`);
}
}
return allFilesChanged;
}
/**
* Construir contexto para generación de escenarios
* @private
*/
_buildTestContext(
workItem,
pullRequests,
filesChanged,
prComments,
workItemAttachments,
additionalContext
) {
const fields = workItem.fields;
const description = this._stripHtml(fields["System.Description"] || "");
const acceptanceCriteria = this._stripHtml(
fields["System.AcceptanceCriteria"] ||
fields["Microsoft.VSTS.Common.AcceptanceCriteria"] ||
""
);
// Procesar comentarios de PR Review
const prReviewInfo = this._processPRReviewComments(prComments);
const workItemComments = Array.isArray(workItem.comments)
? workItem.comments
.map((comment) => {
const rawText = comment?.text || comment?.content || "";
return {
author: this._normalizeAuthorName(
comment?.createdBy || comment?.author,
),
text: this._stripHtml(rawText),
createdDate: comment?.createdDate || comment?.modifiedDate || "",
};
})
.filter((comment) => comment.text && comment.text.length > 0)
.slice(0, 40)
: [];
const normalizedAttachments = Array.isArray(workItemAttachments)
? workItemAttachments
.map((attachment) => ({
name: attachment?.name || "adjunto",
extension: attachment?.extension || "",
comment: this._stripHtml(attachment?.comment || ""),
size: attachment?.size || null,
}))
.slice(0, 50)
: [];
const pullRequestComments = Array.isArray(prComments)
? prComments
.map((comment) => ({
repository: comment?.repository || "Unknown",
pullRequestId: comment?.pullRequestId || "",
author: this._normalizeAuthorName(comment?.author),
type: comment?.commentType || "general",
content: this._stripHtml(comment?.content || ""),
}))
.filter((comment) => comment.content)
.slice(0, 50)
: [];
return {
workItemId: workItem.id,
title: fields["System.Title"] || "",
description,
acceptanceCriteria,
additionalContext: (additionalContext || "").trim(),
workItemComments,
workItemAttachments: normalizedAttachments,
workItemMetadata: {
state: fields["System.State"] || "",
workItemType: fields["System.WorkItemType"] || "",
assignedTo:
fields["System.AssignedTo"]?.displayName ||
fields["System.AssignedTo"] ||
"",
areaPath: fields["System.AreaPath"] || "",
tags: fields["System.Tags"] || "",
},
hasPRs: pullRequests.length > 0,
pullRequestsCount: pullRequests.length,
prDetails: pullRequests.map((pr) => ({
id: pr.pullRequestId,
title: pr.title,
repository: pr.repository,
})),
filesChanged: filesChanged.map((f) => ({
path: f.path,
isNew: f.isNew,
repository: f.repository,
})),
pullRequestComments,
prReviewInfo,
};
}
/**
* Procesar comentarios de PR Review
* @private
*/
_processPRReviewComments(prComments) {
const reviewInfo = {
issuesFound: [],
hasReviewComments: prComments.length > 0,
};
prComments.forEach((comment) => {
if (comment.commentType === "pr-review") {
const issues = this._parseReviewIssues(comment.content);
reviewInfo.issuesFound.push(...issues);
}
});
return reviewInfo;
}
/**
* Parsear issues de PR Review
* @private
*/
_parseReviewIssues(content) {
const issues = [];
const issuePattern = /[⚠️ℹ️💡]\s*\*\*(\d+)\.\s*\[(\w+)\]\s*([\w-]+)\*\*/g;
let match;
while ((match = issuePattern.exec(content)) !== null) {
issues.push({
number: match[1],
severity: match[2],
category: match[3],
});
}
return issues;
}
/**
* Generar escenarios de prueba
* @private
*/
async _generateTestScenarios(context, useAI, preferredModel = "gpt-4o") {
const minScenarioCount = 6;
if (!useAI || !this.summaryService) {
throw new Error(
"La generación de escenarios de prueba requiere GitHub Copilot habilitado. " +
"Por favor, instale y active GitHub Copilot en VS Code."
);
}
try {
this.log(` ℹ️ Modelo configurado: ${preferredModel}`);
const scenarios = await this.summaryService.generateTestScenarios(context, preferredModel);
if (!scenarios || scenarios.length === 0) {
throw new Error(
"GitHub Copilot no generó ningún escenario de prueba. " +
"Verifique que GitHub Copilot esté activo y tenga acceso a los modelos de lenguaje."
);
}
const filteredScenarios = this._filterOutOfContextScenarios(
scenarios,
context,
);
if (filteredScenarios.length < scenarios.length) {
this.log(
` ℹ️ Se omitieron ${scenarios.length - filteredScenarios.length} escenario(s) fuera de contexto del Work Item/PR.`,
);
}
if (filteredScenarios.length < minScenarioCount) {
throw new Error(
`GitHub Copilot solo generó ${filteredScenarios.length} escenario(s) válido(s). ` +
`Se requieren al menos ${minScenarioCount}. Intente nuevamente o agregue más contexto al Work Item.`
);
}
return this._renumberScenarios(filteredScenarios, context.workItemId);
} catch (error) {
this.log(` ❌ Error generando escenarios: ${error.message}`);
throw error;
}
}
/**
* Filtra escenarios que no tienen respaldo en el contexto funcional.
* @private
*/
_filterOutOfContextScenarios(scenarios, context) {
if (!Array.isArray(scenarios) || scenarios.length === 0) {
return [];
}
const contextCorpus = [
context?.title,
context?.description,
context?.acceptanceCriteria,
context?.additionalContext,
...(Array.isArray(context?.workItemComments)
? context.workItemComments.map((item) => item?.text)
: []),
...(Array.isArray(context?.pullRequestComments)
? context.pullRequestComments.map((item) => item?.content)
: []),
...(Array.isArray(context?.prDetails)
? context.prDetails.map((item) => item?.title)
: []),
]
.filter(Boolean)
.join(" ")
.toLowerCase();
const allowIncidents = /\bincident(es|s)?\b|\bincidente(s)?\b/.test(contextCorpus);
const allowProblems = /\bproblem(s)?\b|\bproblema(s)?\b/.test(contextCorpus);
const allowReports =
/\breporte(s)?\b|\binforme(s)?\b|\bmanta\b|\bcolumna(s)?\b/.test(
contextCorpus,
);
return scenarios.filter((scenario) => {
const scenarioText = `${scenario?.title || ""} ${scenario?.preconditions || ""} ${scenario?.expectedResult || ""} ${Array.isArray(scenario?.steps) ? scenario.steps.join(" ") : ""}`
.toLowerCase()
.trim();
if (!scenarioText) {
return false;
}
if (
!allowIncidents &&
/\bincident(es|s)?\b|\bincidente(s)?\b/.test(scenarioText)
) {
return false;
}
if (
!allowProblems &&
/\bproblem(s)?\b|\bproblema(s)?\b/.test(scenarioText)
) {
return false;
}
if (
!allowReports &&
/\breporte(s)?\b|\binforme(s)?\b|\bmanta\b/.test(scenarioText)
) {
return false;
}
return true;
});
}
/**
* Renumera escenarios con ID consistente
* @private
*/
_renumberScenarios(scenarios, workItemId) {
if (!Array.isArray(scenarios) || scenarios.length === 0) {
return [];
}
const scenarioPrefix = `THL-${workItemId || "AUTO"}`;
return scenarios.map((scenario, index) => ({
...scenario,
id: `${scenarioPrefix}-${index + 1}`,
}));
}
/**
* Construye escenarios base concretos y aplicables a negocio.
* @private
*/
_buildBaselineBusinessScenarios(flowContext, businessModule) {
if (flowContext.domain === "report") {
return this._buildReportBusinessScenarios(flowContext, businessModule);
}
const mainFlowQueryLabel = this._buildFlowQueryLabel(flowContext.mainFlowLabel);
const mainFlowShortLabel = this._buildFlowShortLabel(flowContext.mainFlowLabel);
const baseline = [
{
title: `Consultar ${mainFlowShortLabel}`,
preconditions:
"Usuario de negocio autenticado con permisos para consultar informacion",
steps: [
`Ingresar al módulo ${businessModule}`,
`Ejecutar la ${mainFlowQueryLabel}`,
"Validar que la informacion se muestre en pantalla",
],
expectedResult:
`El sistema muestra correctamente los resultados de ${mainFlowQueryLabel} para el usuario.`,
priority: "HIGH",
category: "Funcional",
},
{
title: `Revisar detalle de ${mainFlowShortLabel}`,
preconditions: "Consulta principal ejecutada con al menos un resultado",
steps: [
"Seleccionar un resultado de la consulta",
"Abrir el detalle del registro",
"Verificar campos visibles para negocio",
],
expectedResult:
"El sistema muestra detalle completo, legible y consistente para validacion funcional.",
priority: "MEDIUM",
category: "Funcional",
},
{
title: `Consultar sin resultados en ${mainFlowShortLabel}`,
preconditions: "Usuario autenticado en el módulo funcional",
steps: [
`Ejecutar ${mainFlowQueryLabel} sin coincidencias`,
"Observar mensaje mostrado por el sistema",
"Confirmar que el usuario puede ajustar la consulta",
],
expectedResult:
"El sistema informa claramente que no hay datos y permite continuar operando.",
priority: "MEDIUM",
category: "Funcional",
},
{
title: `Confirmar continuidad de ${mainFlowQueryLabel}`,
preconditions: "Flujo habitual definido y disponible en ambiente de pruebas",
steps: [
`Ejecutar el flujo actual de ${mainFlowQueryLabel}`,
"Comparar resultado con el comportamiento previo esperado",
"Confirmar que no hay diferencias para el usuario final",
],
expectedResult:
"El flujo actual se mantiene sin impacto funcional para el usuario.",
priority: "HIGH",
category: "Regresión",
},
];
if (flowContext.hasAuthChange) {
baseline.push({
title: `Acceso funcional estable a ${mainFlowShortLabel}`,
preconditions:
"Servicio de integracion disponible y usuario con permisos funcionales",
steps: [
`Ingresar al módulo ${businessModule}`,
`Ejecutar ${mainFlowQueryLabel}`,
"Validar que el flujo finaliza sin bloqueo para el usuario",
],
expectedResult:
`El usuario completa ${mainFlowQueryLabel} sin friccion ni pasos manuales extra.`,
priority: "HIGH",
category: "Integracion",
});
}
if (flowContext.relatedFlowLabel) {
baseline.push({
title: `Consultar ${flowContext.relatedFlowLabel}`,
preconditions: "Resultado principal disponible para relacionar informacion",
steps: [
`Abrir una consulta de ${mainFlowShortLabel}`,
`Visualizar la informacion de ${flowContext.relatedFlowLabel}`,
"Confirmar que la relacion entre datos es correcta",
],
expectedResult:
`El sistema muestra correctamente la relacion entre ${mainFlowShortLabel} y ${flowContext.relatedFlowLabel}.`,
priority: "HIGH",
category: "Funcional",
});
}
return baseline;
}
/**
* Construye escenarios base para cambios de reportes.
* @private
*/
_buildReportBusinessScenarios(flowContext, businessModule) {
const reportContext = flowContext.reportContext || {};
const primaryReport = reportContext.primaryReport || "Reporte Integral de Riesgos y Controles";
const secondaryReport = reportContext.secondaryReport || "Manta de Riesgos Plano";
const addedColumns = Array.isArray(reportContext.addedColumns)
? reportContext.addedColumns
: [];
const removedColumns = Array.isArray(reportContext.removedColumns)
? reportContext.removedColumns
: [];
const columnsPreview = addedColumns.slice(0, 6).join(", ");
const hasAvalRemoval = removedColumns.some(
(column) => column.toUpperCase() === "AVAL",
);
const baseline = [
{
title: `Abrir ${primaryReport}`,
preconditions:
"Usuario de negocio autenticado con permisos para consultar reportes",
steps: [
`Ingresar al módulo ${businessModule}`,
`Abrir el reporte ${primaryReport}`,
"Completar filtros y ejecutar Ver informe",
],
expectedResult:
`El sistema genera ${primaryReport} y presenta la informacion en pantalla.`,
priority: "HIGH",
category: "Funcional",
},
{
title: `Validar columnas nuevas en ${primaryReport}`,
preconditions: "Reporte ejecutado con datos visibles",
steps: [
`Abrir ${primaryReport} con filtros de negocio`,
"Revisar encabezados mostrados en el reporte",
"Confirmar que las columnas nuevas se visualizan correctamente",
],
expectedResult: columnsPreview
? `El reporte muestra las columnas solicitadas: ${columnsPreview}.`
: "El reporte muestra las columnas solicitadas por negocio en el orden esperado.",
priority: "HIGH",
category: "Funcional",
},
{
title: `Descargar ${primaryReport} en Excel`,
preconditions: "Reporte ejecutado y opcion de exportacion disponible",
steps: [
`Ejecutar ${primaryReport}`,
"Descargar el reporte en formato Excel",
"Verificar columnas y datos en el archivo descargado",
],
expectedResult:
"El Excel descargado contiene la misma estructura y datos visibles del reporte en pantalla.",
priority: "MEDIUM",
category: "Regresión",
},
{
title: `Abrir ${secondaryReport}`,
preconditions:
"Usuario de negocio autenticado con permisos para consultar reportes",
steps: [
`Ingresar al módulo ${businessModule}`,
`Abrir el reporte ${secondaryReport}`,
"Completar filtros y ejecutar Ver informe",
],
expectedResult:
`El sistema genera ${secondaryReport} con datos visibles para validacion.`,
priority: "MEDIUM",
category: "Funcional",
},
];
if (hasAvalRemoval) {
baseline.push({
title: "Confirmar que la columna AVAL no se muestra",
preconditions: `${secondaryReport} ejecutado con datos visibles`,
steps: [
`Abrir ${secondaryReport}`,
"Revisar todos los encabezados de columnas",
"Confirmar que la columna AVAL no aparece en pantalla ni en Excel",
],
expectedResult:
"La columna AVAL no se visualiza en el reporte ni en el archivo exportado.",
priority: "HIGH",
category: "Funcional",
});
}
baseline.push({
title: "Confirmar continuidad funcional de reportes",
preconditions: "Flujo habitual de reportes disponible en ambiente de pruebas",
steps: [
`Ejecutar ${primaryReport} y ${secondaryReport}`,
"Comparar resultados con el comportamiento esperado por negocio",
"Confirmar que no hay impactos funcionales en el uso diario",
],
expectedResult:
"Los reportes mantienen su funcionamiento esperado con las modificaciones aplicadas.",
priority: "HIGH",
category: "Regresión",
});
return baseline;
}
/**
* Convierte una guia textual en un escenario funcional concreto.
* @private
*/
_buildScenarioFromGuidance(guidance, source, flowContext, businessModule) {
if (flowContext.domain === "report") {
return this._buildReportScenarioFromGuidance(
guidance,
source,
flowContext,
businessModule,
);
}
const raw = this._normalizeBusinessNarrative(guidance || "");
if (!raw) {
return null;
}
const text = raw.toLowerCase();
const mainFlowQueryLabel = this._buildFlowQueryLabel(flowContext.mainFlowLabel);
const mainFlowShortLabel = this._buildFlowShortLabel(flowContext.mainFlowLabel);
if (/(set auto-complete|adjunto visual adjunto visual|^thl-\d+\b)/i.test(text)) {
return null;
}
if (/(oauth|client credentials|credencial de acceso|autentic)/i.test(text)) {
return {
title: `Confirmar acceso estable a ${mainFlowShortLabel}`,
preconditions:
"Integracion habilitada y usuario con permisos funcionales",
steps: [
`Ingresar al módulo ${businessModule}`,
`Ejecutar ${mainFlowQueryLabel}`,
"Validar que la operacion finaliza sin interrupciones",
],
expectedResult:
`El sistema permite ${mainFlowQueryLabel} de forma estable para el usuario final.`,
priority: source === "criteria" ? "HIGH" : "MEDIUM",
category: "Integracion",
};
}
if (/(sin impacto|sin cambios|flujo actual|se mantiene|continuidad)/i.test(text)) {
return {
title: `Comparar continuidad de ${mainFlowQueryLabel}`,
preconditions: "Flujo actual conocido por negocio para comparacion",
steps: [
`Ejecutar ${mainFlowQueryLabel} como se realiza actualmente`,
"Comparar resultados contra comportamiento esperado",
"Confirmar continuidad funcional para el usuario",
],
expectedResult:
"El sistema mantiene el mismo comportamiento funcional sin impacto en procesos vigentes.",
priority: "HIGH",
category: "Regresión",
};
}
if (/(timeout|error controlado|acceso no autorizado|acceso no autenticado|falla)/i.test(text)) {
return {
title: `Revisar mensaje de falla en ${mainFlowShortLabel}`,
preconditions: "Escenario de falla controlada disponible en ambiente de pruebas",
steps: [
`Ejecutar ${mainFlowQueryLabel} bajo condicion de falla controlada`,
"Validar mensaje mostrado al usuario",
"Confirmar que el usuario puede reintentar la operacion",
],
expectedResult:
"El sistema muestra un mensaje claro y permite continuar sin perder el control del proceso.",
priority: "MEDIUM",
category: "Funcional",
};
}
if (/(consulta|incident|incidente|problem|problema|servicenow)/i.test(text)) {
return {
title: `Confirmar resultado de ${mainFlowShortLabel}`,
preconditions: "Datos funcionales disponibles para consulta",
steps: [
`Ejecutar ${mainFlowQueryLabel} en el módulo ${businessModule}`,
"Revisar resultados mostrados en pantalla",
"Confirmar consistencia de la informacion para negocio",
],
expectedResult:
`El sistema presenta informacion confiable y util para la operacion de ${mainFlowQueryLabel}.`,
priority: source === "additional" ? "MEDIUM" : "HIGH",
category: "Funcional",
};
}
return null;
}
/**
* Convierte guia textual en escenarios concretos para cambios de reportes.
* @private
*/
_buildReportScenarioFromGuidance(guidance, source, flowContext, businessModule) {
const raw = this._normalizeBusinessNarrative(guidance || "");
if (!raw) {
return null;
}
const text = raw.toLowerCase();
const reportContext = flowContext.reportContext || {};
const primaryReport = reportContext.primaryReport || "Reporte Integral de Riesgos y Controles";
const secondaryReport = reportContext.secondaryReport || "Manta de Riesgos Plano";
if (/(set auto-complete|adjunto visual adjunto visual|^thl-\d+\b)/i.test(text)) {
return null;
}
if (/(aval|no exista|eliminar|remover|quitar)/i.test(text)) {
return {
title: "Verificar eliminacion de columna AVAL",
preconditions: `${secondaryReport} ejecutado en ambiente de pruebas`,
steps: [
`Abrir ${secondaryReport} en el módulo ${businessModule}`,
"Revisar encabezados y detalle del reporte",
"Confirmar que AVAL no aparece en pantalla ni en Excel",
],
expectedResult:
"La columna AVAL no se encuentra disponible para el usuario en ninguna vista del reporte.",
priority: "HIGH",
category: "Funcional",
};
}
if (/(columna|columnas|campo|campos|incluir|agregar|solicitad)/i.test(text)) {
return {
title: "Verificar columnas solicitadas por negocio",
preconditions: `${primaryReport} ejecutado con informacion visible`,
steps: [
`Abrir ${primaryReport}`,
"Ubicar las columnas solicitadas por negocio",
"Confirmar nombre, orden y visibilidad de cada columna",
],
expectedResult:
"Las columnas solicitadas por negocio se muestran correctamente en pantalla.",
priority: "HIGH",
category: "Funcional",
};
}
if (/(excel|descarg)/i.test(text)) {
return {
title: "Verificar exportacion de reportes en Excel",
preconditions: "Reportes ejecutados con opcion de descarga disponible",
steps: [
`Ejecutar ${primaryReport}`,
"Descargar archivo Excel",
"Validar que columnas y datos coinciden con la vista del reporte",
],
expectedResult:
"El archivo Excel mantiene estructura y datos esperados para negocio.",
priority: "MEDIUM",
category: "Regresión",
};
}
if (/(integral|riesgo|control)/i.test(text)) {
return {
title: `Validar datos visibles en ${primaryReport}`,
preconditions: "Reporte ejecutado con datos de prueba",
steps: [
`Abrir ${primaryReport}`,
"Revisar filas y columnas principales",
"Confirmar consistencia de la informacion mostrada",
],
expectedResult:
"El reporte muestra informacion completa y consistente para el usuario de negocio.",
priority: source === "criteria" ? "HIGH" : "MEDIUM",
category: "Funcional",
};
}
return null;
}
/**
* Construye etiqueta de consulta legible evitando duplicaciones.
* @private
*/
_buildFlowQueryLabel(mainFlowLabel) {
const label = String(mainFlowLabel || "flujo principal").trim();
if (!label) {
return "consulta funcional";
}
return /^consulta\s+de\s+/i.test(label) ? label : `consulta de ${label}`;
}
/**
* Obtiene etiqueta corta de flujo para titulos.
* @private
*/
_buildFlowShortLabel(mainFlowLabel) {
const label = String(mainFlowLabel || "flujo principal").trim();
return label.replace(/^consulta\s+de\s+/i, "") || "flujo principal";
}
/**
* Normaliza conjunto final de escenarios evitando duplicados funcionales.
* @private
*/
_finalizeScenarioSet(scenarios, maxCount = 12) {
if (!Array.isArray(scenarios) || scenarios.length === 0) {
return [];
}
const selected = [];
const usedIntentKeys = new Set();
const usedTitleKeys = new Set();
for (const scenario of scenarios) {
if (!scenario || !scenario.title || !Array.isArray(scenario.steps)) {
continue;
}
const titleKey = String(scenario.title || "")
.toLowerCase()
.replace(/\s+/g, " ")
.trim();
if (!titleKey || usedTitleKeys.has(titleKey)) {
continue;
}
const intentKey = this._deriveScenarioIntentKey(scenario);
if (usedIntentKeys.has(intentKey)) {
continue;
}
usedTitleKeys.add(titleKey);
usedIntentKeys.add(intentKey);
selected.push(scenario);
if (selected.length >= maxCount) {
break;
}
}
return selected;
}
/**
* Deriva una clave funcional para evitar escenarios repetidos por intención.
* @private
*/
_deriveScenarioIntentKey(scenario) {
const text = `${scenario?.title || ""} ${scenario?.expectedResult || ""} ${(scenario?.steps || []).join(" ")}`
.toLowerCase()
.replace(/\s+/g, " ")
.trim();
if (/\baval\b/.test(text)) return "report-remove-aval";
if (/\bexcel\b|\bdescarg/.test(text)) return "report-export";
if (/\bcolumna\b|\bcampo\b/.test(text)) return "report-columns";
if ((/\breporte\b|\binforme\b/.test(text)) && /\babrir\b/.test(text)) {
if (/\bintegral\b/.test(text)) return "report-open-integral";
if (/\bplano\b|\bmanta\b/.test(text)) return "report-open-plano";
return "report-open";
}
if (/incidente\s+de\s+rti|riesgo\s+tecnologic|buscar\s+un?\s+problem|asociar\s+un?\s+problem|avanzar\s+incidente/.test(text)) {
return "service-incident-rti-problem-flow";
}
if (/\bdetalle\b/.test(text)) return "service-detail";
if (/sin coincidencias|sin resultados|no hay datos/.test(text)) return "service-no-results";
if (/continuidad|sin cambios|sin impacto|flujo habitual|flujo actual/.test(text)) return "service-continuity";
if (/acceso estable|sin bloqueo|sin interrupciones|sin pasos manuales/.test(text)) return "service-access-stability";
if (/relacionad/.test(text)) return "service-related-information";
if (/anexo/.test(text)) return "service-attachment-trace";
if (/mensaje de falla|error controlado|acceso no autorizado|acceso no autenticado/.test(text)) return "service-error-handling";
if (/consultar|consulta/.test(text)) return "service-main-query";
return `generic-${text.slice(0, 80)}`;
}
/**
* Detecta duplicados cercanos por similitud de contenido.
* @private
*/
_isNearDuplicateScenario(candidate, selectedScenarios) {
const candidateTokens = this._tokenizeScenarioForSimilarity(candidate);
if (candidateTokens.size === 0) {
return false;
}
for (const existing of selectedScenarios) {
const existingTokens = this._tokenizeScenarioForSimilarity(existing);
const similarity = this._jaccardSimilarity(candidateTokens, existingTokens);
if (similarity >= 0.78) {
return true;
}
}
return false;
}
/**
* Tokeniza escenario para comparacion de similitud.
* @private
*/
_tokenizeScenarioForSimilarity(scenario) {
const stopWords = new Set([
"el", "la", "los", "las", "de", "del", "para", "por", "con", "sin",
"que", "en", "y", "o", "un", "una", "al", "se", "es", "usuario",
"sistema", "flujo", "modulo", "funcional", "validar", "confirmar", "revisar",
]);
const text = `${scenario?.title || ""} ${scenario?.expectedResult || ""} ${(scenario?.steps || []).join(" ")}`
.toLowerCase()
.replace(/[^a-z0-9áéíóúüñ\s]/gi, " ")
.replace(/\s+/g, " ")
.trim();
const tokens = new Set();
text.split(" ").forEach((token) => {
const clean = token.trim();
if (!clean || clean.length < 4 || stopWords.has(clean)) {
return;
}
tokens.add(clean);
});
return tokens;
}
/**
* Similaridad de Jaccard entre dos conjuntos.
* @private
*/
_jaccardSimilarity(setA, setB) {
if (!setA.size && !setB.size) {
return 1;
}
let intersection = 0;
for (const item of setA) {
if (setB.has(item)) {
intersection += 1;
}
}
const union = setA.size + setB.size - intersection;
if (union === 0) {
return 0;
}
return intersection / union;
}
/**
* Convierte contexto adicional critico en escenario e2e concreto.
* @private
*/
_buildCriticalAdditionalContextScenario(additionalContext, flowContext, businessModule) {
const text = String(additionalContext || "").toLowerCase();
if (!text) {
return null;
}
const hasIncidentCreation = /(crear\s+un?\s+incidente|incidente\s+de\s+rti|riesgo\s+tecnologic)/.test(text);
const hasProblemLookup = /(buscar\s+un?\s+problem|campo\s+de\s+buscar\s+problem|asociar\s+un?\s+problem)/.test(text);
const hasAdvanceFlow = /(avanzar\s+incidente|finalizar\s+el\s+escenario|avanzandolo|avanzarlo|cerrar\s+incidente)/.test(text);
if (!(hasIncidentCreation && hasProblemLookup)) {
return null;
}
const mainFlowQueryLabel = this._buildFlowQueryLabel(flowContext.mainFlowLabel);
const steps = [
`Ingresar al módulo ${businessModule}`,
"Crear un incidente de RTI o riesgo tecnologico",
"Validar que se habilite el campo para buscar problem",
"Buscar y asociar un problem al incidente",
hasAdvanceFlow
? "Guardar el incidente y avanzar su estado"
: "Guardar el incidente y validar su relacion con el problem",
];
return {
title: "Crear incidente RTI con problem asociado",
preconditions:
"Usuario autenticado en HCI con permisos para crear y avanzar incidentes",
steps,
expectedResult: hasAdvanceFlow
? `El usuario crea y avanza el incidente con problem asociado sin errores y manteniendo ${mainFlowQueryLabel}.`
: `El usuario crea el incidente con problem asociado sin errores y manteniendo ${mainFlowQueryLabel}.`,
priority: "HIGH",
category: "Funcional",
};
}
/**
* Determina el enfoque funcional principal desde el contexto consolidado.
* @private
*/
_inferBusinessFlowContext(context) {
const coreSources = [
context?.title,
context?.description,
context?.acceptanceCriteria,
...(Array.isArray(context?.prDetails)
? context.prDetails.map((item) => item?.title)
: []),
]
.filter(Boolean)
.join(" ")
.toLowerCase();
const corpus = [
context?.title,
context?.description,
context?.acceptanceCriteria,
context?.additionalContext,
...(Array.isArray(context?.workItemComments)
? context.workItemComments.map((item) => item?.text)
: []),
...(Array.isArray(context?.pullRequestComments)
? context.pullRequestComments.map((item) => item?.content)
: []),
...(Array.isArray(context?.prDetails)
? context.prDetails.map((item) => item?.title)
: []),
]
.filter(Boolean)
.join(" ")
.toLowerCase();
const reportContextDetected =
/(\breporte\b|\breportes\b|\binforme\b|\bmanta\b|\bcolumna\b|\bcolumnas\b)/.test(coreSources);
if (reportContextDetected) {
const contextFragments = [
context?.title,
context?.description,
context?.acceptanceCriteria,
...(Array.isArray(context?.workItemComments)
? context.workItemComments.map((item) => item?.text)
: []),
...(Array.isArray(context?.pullRequestComments)
? context.pullRequestComments.map((item) => item?.content)
: []),
...(Array.isArray(context?.prDetails)
? context.prDetails.map((item) => item?.title)
: []),
].filter(Boolean);
const quotedTerms = this._extractQuotedTerms(contextFragments, 12);
const listedTerms = this._extractListedColumnTerms(contextFragments, 12);
const mergedTerms = [...new Set([...quotedTerms, ...listedTerms])];
const removedColumns = mergedTerms.filter((term) => /\baval\b/i.test(term));
const addedColumns = mergedTerms.filter((term) => !/\baval\b/i.test(term));
return {
domain: "report",
mainFlowLabel: "gestion de reportes",
relatedFlowLabel: "",
hasAuthChange: false,
reportContext: {
primaryReport:
/integral\s+riesg|riesgo\s*\/\s*control/i.test(coreSources)
? "Reporte Integral de Riesgos y Controles"
: "Reporte Integral",
secondaryReport: /manta\s+de\s+riesgos\s+plano/i.test(coreSources)
? "Manta de Riesgos Plano"
: "Reporte Plano de Riesgos",
addedColumns,
removedColumns,
},
};
}
const hasIncidents = /\bincident(es|s)?\b|\bincidente(s)?\b/.test(corpus);
const hasProblems = /\bproblem(s)?\b|\bproblema(s)?\b/.test(corpus);
const hasAuthChange = /(oauth|client credentials|token|credencial|autentic)/.test(corpus);
let mainFlowLabel = "flujo principal";
if (hasIncidents) {
mainFlowLabel = "consulta de incidents";
} else if (hasProblems) {
mainFlowLabel = "consulta de problems";
} else if (/\bconsulta\b/.test(corpus)) {
mainFlowLabel = "consulta funcional";
}
const relatedFlowLabel = hasIncidents && hasProblems
? "problems relacionados"
: "";
return {
domain: "service",
mainFlowLabel,
relatedFlowLabel,
hasAuthChange,
reportContext: null,
};
}
/**
* Extrae textos entre comillas para nombres de campos/columnas.
* @private
*/
_extractQuotedTerms(values, maxItems = 10) {
const text = Array.isArray(values)
? values.filter(Boolean).join(" ")
: String(values || "");
const matches = [];
const seen = new Set();
const regex = /["“”']([^"“”'\n]{3,90})["“”']/g;
let match = regex.exec(text);
while (match) {
const candidate = String(match[1] || "")
.replace(/\s+/g, " ")
.trim();
const key = candidate.toLowerCase();
if (
candidate &&
!seen.has(key) &&
!/^(reporte|informe|filtro)$/i.test(candidate)
) {
seen.add(key);
matches.push(candidate);
if (matches.length >= maxItems) {
break;
}
}
match = regex.exec(text);
}
return matches;
}
/**
* Extrae candidatos de nombres de columnas en texto libre (listas separadas por comas).
* @private
*/
_extractListedColumnTerms(values, maxItems = 10) {
const text = Array.isArray(values)
? values.filter(Boolean).join(" ")
: String(values || "");
const matches = [];
const seen = new Set();
const segmentRegex = /columnas?\s*:?\s*([^\.\n]{12,500})/gi;
let segmentMatch = segmentRegex.exec(text);
while (segmentMatch) {
const segment = String(segmentMatch[1] || "");
const candidates = segment
.split(/,|\sy\s/gi)
.map((part) => part.replace(/["“”']/g, "").trim())
.filter((part) => part.length >= 4 && part.length <= 80)
.filter((part) => !/^(nuevas?|solicitadas?|reporte|informe|riesgo|control)$/i.test(part));
for (const candidate of candidates) {
const key = candidate.toLowerCase();
if (seen.has(key)) {
continue;
}
seen.add(key);
matches.push(candidate);
if (matches.length >= maxItems) {
return matches;
}
}
segmentMatch = segmentRegex.exec(text);
}
return matches;
}
/**
* Extrae frases de negocio concretas desde texto largo.
* @private
*/
_extractBusinessGuidancePoints(value, maxItems = 5) {
const rawValue = String(value || "").trim();
if (!rawValue) {
return [];
}
const normalized = this._normalizeBusinessNarrative(rawValue);
if (!normalized) {
return [];
}
const clauses = normalized
.split(/\n+|;+|(?<!\d)\.(?!\d)/g)
.map((part) => part.trim())
.filter((part) => part.length >= 15)
.map((part) => part.replace(/^[-•]\s*/, ""));
const unique = [];
const seen = new Set();
for (const clause of clauses) {
const key = clause.toLowerCase();
if (
/^(hola|buenas|saludos|gracias)\b/i.test(key) ||
/set auto-complete/i.test(key) ||
/^thl-\d+\b/i.test(key) ||
/^\d+(\.\d+)?$/.test(key)
) {
continue;
}
if ((key.match(/adjunto visual/g) || []).length >= 2) {
continue;
}
if (seen.has(key)) {
continue;
}
seen.add(key);
unique.push(clause);
if (unique.length >= maxItems) {
break;
}
}
return unique;
}
/**
* Construye titulo concreto para negocio y evita cortes a media palabra.
* @private
*/
_buildBusinessScenarioTitle(value) {
let title = this._normalizeBusinessNarrative(value || "")
.replace(/^validar criterio funcional:\s*/i, "")
.replace(/^validar\s+/i, "")
.replace(/^que\s+/i, "")
.replace(/[.:;\s]+$/g, "")
.trim();
if (!title) {
return "Flujo funcional principal";
}
title = title.charAt(0).toUpperCase() + title.slice(1);
return this._truncateAtWordBoundary(title, 95);
}
/**
* Recorta respetando palabras completas.
* @private
*/
_truncateAtWordBoundary(value, maxLen = 95) {
const text = this._normalizeBusinessNarrative(value || "");
if (text.length <= maxLen) {
return text;
}
const slice = text.slice(0, maxLen);
const lastSpace = slice.lastIndexOf(" ");
if (lastSpace <= 0) {
return `${slice.trim()}...`;
}
return `${slice.slice(0, lastSpace).trim()}...`;
}
/**
* Infere nombre de módulo de negocio desde título del Work Item.
* @private
*/
_inferBusinessModuleName(context) {
const corpus = [
context?.title,
context?.description,
context?.acceptanceCriteria,
context?.additionalContext,
]
.filter(Boolean)
.join(" ")
.toLowerCase();
const title = String(context?.title || "").toLowerCase();
if (title.includes("traslado")) return "de Traslados";
if (title.includes("riesgo")) return "de Riesgos y Controles";
if (title.includes("usuario")) return "de Administración de Usuarios";
if (title.includes("concili")) return "de Conciliaciones";
if (/\bhci\b|\bincident|\bproblem/.test(corpus)) return "de HCI";
if (/\breporte|\binforme|\bmanta/.test(corpus)) return "de Reportes";
return "funcional correspondiente";
}
/**
* Normaliza texto para narrativas funcionales de negocio.
* @private
*/
_normalizeBusinessNarrative(value) {
return this._sanitizeDocxText(
String(value || "")
.replace(/!\[[^\]]*\]\([^)]*\)/g, "adjunto visual")
.replace(/\s+/g, " ")
.replace(/\btoken\b/gi, "credencial de acceso")
.replace(/\b(endpoint|api|backend|frontend|json|xml)\b/gi, "servicio")
.replace(/\b(http\s*)?401\b/gi, "acceso no autenticado")
.replace(/\b(http\s*)?403\b/gi, "acceso no autorizado")
.replace(/\b(http\s*)?500\b/gi, "error controlado")
.replace(/\btimeout\b/gi, "respuesta fuera de tiempo esperado")
.replace(/\b[\w.-]+\.(cs|ts|js|sql|json|xml|config|csproj|sln)\b/gi, "artefacto interno")
.trim(),
);
}
/**
* Crear documento Word
* @private
*/
async _createWordDocument(data, outputPath) {
const { workItem, workItemUrl, scenarios, context } = data;
const fields = workItem.fields;
const sections = [];
const safeWorkItemTitle = this._sanitizeDocxText(fields["System.Title"] || "");
const safeWorkItemLink = this._normalizeHyperlinkUrl(workItemUrl);
const sectionAnchors = {
objective: "sec-objetivo",
requirements: "sec-requisitos",
results: "sec-documentacion-resultados",
review: "sec-revision-validacion",
scenarios: "sec-escenarios-prueba",
};
const scenarioTocEntries = scenarios.map((scenario, index) => {
const code = this._sanitizeDocxText(scenario?.id || `THL-AUTO-${index + 1}`);
const title = this._sanitizeDocxText(
String(scenario?.title || "Escenario sin título").trim(),
);
return {
bookmarkId: this._buildBookmarkId(`${code}-${index + 1}`, "scn"),
label: `${code}: ${title}`,
};
});
const templateReferencePath = await this._resolveTemplateReferencePath();
const templateLogoAsset = await this._resolveTemplateLogoBuffer(
templateReferencePath,
);
const templateVisualProfile = await this._resolveTemplateVisualProfile(
templateReferencePath,
);
const templateReferenceName = templateReferencePath
? path.basename(templateReferencePath)
: null;
if (templateReferenceName) {
this.log(` 🧷 Plantilla de referencia aplicada: ${templateReferenceName}`);
this.log(
` 🎨 Color base detectado para escenarios: #${templateVisualProfile.scenarioLabelFill}`,
);
this.log(
` 📐 Márgenes detectados (pt): ${templateVisualProfile.pageMarginTopPt}/${templateVisualProfile.pageMarginRightPt}/${templateVisualProfile.pageMarginBottomPt}/${templateVisualProfile.pageMarginLeftPt}`,
);
} else {
this.log(" ⚠️ No se encontró plantilla en resources/templates. Se usará estructura estándar.");
}
const coverFontFamily =
templateVisualProfile.coverTitleFontFamily || "Arial";
const coverFontSize = this._toDocxHalfPoint(
templateVisualProfile.coverTitleFontSizePt,
34,
);
const coverLineHeightTwip = this._toTwip(
(Number(templateVisualProfile.coverTitleFontSizePt) || 17) *
(Number(templateVisualProfile.coverLineHeightPercent) || 115) /
100,
391,
);
const coverTitleMarginTop = this._toTwip(
templateVisualProfile.coverTitleMarginTopPt,
240,
);
const coverTitleMarginBottom = this._toTwip(
templateVisualProfile.coverTitleMarginBottomPt,
240,
);
for (let i = 0; i < (templateVisualProfile.coverBlankLinesBeforeLogo || 5); i += 1) {
sections.push(
new Paragraph({
alignment: AlignmentType.CENTER,
spacing: {
line: coverLineHeightTwip,
},
children: [
new TextRun({
text: " ",
font: coverFontFamily,
size: coverFontSize,
}),
],
}),
);
}
if (templateLogoAsset) {
sections.push(
new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new ImageRun({
data: templateLogoAsset.data,
type: templateLogoAsset.type,
transformation: {
width: templateVisualProfile.logoWidthPx || 353,
height: templateVisualProfile.logoHeightPx || 121,
},
}),
],
}),
new Paragraph({ text: "" }),
);
}
for (let i = 0; i < (templateVisualProfile.coverBlankLinesAfterLogo || 4); i += 1) {
sections.push(
new Paragraph({
alignment: AlignmentType.CENTER,
spacing: {
line: coverLineHeightTwip,
},
children: [
new TextRun({
text: " ",
font: coverFontFamily,
size: coverFontSize,
}),
],
}),
);
}
sections.push(
new Paragraph({
children: [
new TextRun({
text: "Pruebas ",
font: coverFontFamily,
size: coverFontSize,
}),
...(safeWorkItemLink
? [
new ExternalHyperlink({
link: safeWorkItemLink,
children: [
new TextRun({
text: `THL-${workItem.id}`,
font: coverFontFamily,
size: coverFontSize,
color: "0563C1",
underline: {},
}),
],
}),
]
: [
new TextRun({
text: `THL-${workItem.id}`,
font: coverFontFamily,
size: coverFontSize,
}),
]),
],
alignment: AlignmentType.CENTER,
spacing: {
before: coverTitleMarginTop,
after: coverTitleMarginBottom,
line: coverLineHeightTwip,
},
}),
new Paragraph({
children: [
new TextRun({
text: safeWorkItemTitle,
font: coverFontFamily,
size: coverFontSize,
}),
],
alignment: AlignmentType.CENTER,
spacing: {
before: coverTitleMarginTop,
after: coverTitleMarginBottom,
line: coverLineHeightTwip,
},
})
);
// Contenido
sections.push(
new Paragraph({
text: "Contenido",
heading: HeadingLevel.HEADING_2,
pageBreakBefore: true,
}),
...this._createOnlineCompatibleTableOfContents(
sectionAnchors,
scenarioTocEntries,
),
new Paragraph({ text: "" })
);
// Objetivo
const objectiveText = [
`Validar funcionalmente la implementación del Work Item ${workItem.id}: ${safeWorkItemTitle || "Sin título"}.`,
"Confirmar que los criterios de aceptación definidos en Azure DevOps se cumplan de extremo a extremo.",
context?.additionalContext
? `Contexto adicional considerado: ${this._sanitizeDocxText(context.additionalContext)}`
: null,
]
.filter(Boolean)
.join(" ");
sections.push(
this._createBookmarkedHeadingParagraph(
"Objetivo",
HeadingLevel.HEADING_1,
sectionAnchors.objective,
),
new Paragraph({
text: this._sanitizeDocxText(objectiveText),
}),
new Paragraph({ text: "" })
);
// Requisitos
sections.push(
this._createBookmarkedHeadingParagraph(
"Requisitos",
HeadingLevel.HEADING_1,
sectionAnchors.requirements,
),
new Paragraph({ text: "Para llevar a cabo el ciclo de pruebas, se requiere:" }),
new Paragraph({ text: "" }),
new Paragraph({ text: "• Acceso al sitio (Suite SIXPRO - BAC)" }),
new Paragraph({ text: "• Ambiente de pruebas disponible y estable" }),
new Paragraph({ text: "• Datos de prueba válidos para ejecutar escenarios" }),
new Paragraph({ text: "" })
);
// Documentación de Resultados
const resultsIndent = { left: this._toTwip(35.4, 708) };
const resultsSubIndent = { left: this._toTwip(88.8, 1776) };
sections.push(
this._createBookmarkedHeadingParagraph(
"Documentación de Resultados",
HeadingLevel.HEADING_1,
sectionAnchors.results,
),
new Paragraph({ text: "Se agrega el detalle de cada una de las pruebas a realizar:" }),
new Paragraph({ text: "" }),
this._createIndentedLabeledParagraph("Descripción: ", "explicación del escenario.", resultsIndent),
this._createIndentedLabeledParagraph("Pasos Realizados: ", "Realizado.", resultsIndent),
this._createIndentedLabeledParagraph("Resultado Esperado: ", "Esperado", resultsIndent),
this._createIndentedLabeledParagraph("Resultado Obtenido", "", resultsIndent),
new Paragraph({ text: "Estado del resultado obtenido al ejecutar la prueba", indent: resultsIndent }),
this._createIndentedBulletLabeledParagraph("Correcto: ", "La funcionalidad cumple con lo esperado", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("Incorrecto: ", "No se cumple con lo esperado", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("Parcial: ", "Se cumple en una parte del sistema, pero falla en otra", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("Error crítico: ", "Error en el sistema", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("Bloqueado: ", "No fue posible ejecutar la prueba por dependencia externa", resultsSubIndent),
new Paragraph({ text: "" }),
this._createIndentedLabeledParagraph("Estado", "", resultsIndent),
this._createIndentedBulletLabeledParagraph("Pendiente: ", "Pendiente de aprobación por ejecutar el ciclo de pruebas", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("Aprobado: ", "Resultado esperado coincide con el obtenido", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("Fallido: ", "Resultado obtenido no coincide con lo esperado", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("Bloqueado: ", "No se pudo ejecutar por falta de datos, permisos o defectos abiertos", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("En ejecución: ", "Caso aún en validación", resultsSubIndent),
this._createIndentedBulletLabeledParagraph("No ejecutado: ", "Caso definido pero pendiente de ejecutar", resultsSubIndent),
this._createIndentedLabeledParagraph("Comentarios: ", "Notas adicionales o problemas encontrados.", resultsIndent),
new Paragraph({ text: "" })
);
// Revisión y Validación
sections.push(
this._createBookmarkedHeadingParagraph(
"Revisión y Validación",
HeadingLevel.HEADING_1,
sectionAnchors.review,
),
new Paragraph({
text: "• Revisar los resultados de las pruebas con el equipo de desarrollo y asegurar que todos los escenarios fueron cubiertos.",
}),
new Paragraph({
text: "• Validar que los mensajes de error sean claros y útiles para el usuario.",
}),
new Paragraph({ text: "" })
);
// Escenarios de Prueba
sections.push(
this._createBookmarkedHeadingParagraph(
"Escenarios de Prueba",
HeadingLevel.HEADING_1,
sectionAnchors.scenarios,
),
new Paragraph({ text: "" })
);
for (let index = 0; index < scenarios.length; index += 1) {
const scenario = scenarios[index];
const scenarioSection = await this._createScenarioSection(
scenario,
index + 1,
scenarioTocEntries[index]?.bookmarkId,
templateVisualProfile,
);
sections.push(...scenarioSection);
}
const documentHeader = this._createDocumentHeader(
templateLogoAsset,
templateVisualProfile,
);
// Crear documento
const doc = new Document({
styles: this._buildDocumentStyles(templateVisualProfile),
sections: [
{
headers: {
default: documentHeader,
},
properties: {
page: {
margin: {
top: this._toTwip(templateVisualProfile.pageMarginTopPt, 720),
right: this._toTwip(templateVisualProfile.pageMarginRightPt, 720),
bottom: this._toTwip(templateVisualProfile.pageMarginBottomPt, 720),
left: this._toTwip(templateVisualProfile.pageMarginLeftPt, 720),
header: this._toTwip(templateVisualProfile.headerMarginPt, 709),
footer: this._toTwip(templateVisualProfile.footerMarginPt, 709),
gutter: 0,
},
},
},
children: sections,
},
],
});
// Asegurar que el directorio existe
const dir = path.dirname(outputPath);
await fs.mkdir(dir, { recursive: true });
// Guardar
const buffer = await Packer.toBuffer(doc);
await fs.writeFile(outputPath, buffer);
if (templateReferencePath) {
const templateExt = path.extname(templateReferencePath).toLowerCase();
if (templateExt === ".html" || templateExt === ".htm") {
this.log(
" ℹ️ Template HTML detectado: se aplicó estructura de documento alineada al template y estilos de escenario consistentes.",
);
}
}
this.log(
" ℹ️ Se generó tabla de contenido estática para máxima compatibilidad con Word Online.",
);
}
/**
* Crea una tabla de contenido estática para compatibilidad con Word Online.
* @private
*/
_createOnlineCompatibleTableOfContents(sectionAnchors, scenarioTocEntries) {
const entries = [
{ label: "Objetivo", anchor: sectionAnchors.objective },
{ label: "Requisitos", anchor: sectionAnchors.requirements },
{ label: "Documentación de Resultados", anchor: sectionAnchors.results },
{ label: "Revisión y Validación", anchor: sectionAnchors.review },
{ label: "Escenarios de Prueba", anchor: sectionAnchors.scenarios },
...scenarioTocEntries.map((entry) => ({
label: entry.label,
anchor: entry.bookmarkId,
isScenario: true,
})),
];
return entries.map((entry) =>
new Paragraph({
indent: entry.isScenario
? { left: this._toTwip(18, 360) }
: undefined,
children: [
new InternalHyperlink({
anchor: entry.anchor,
children: [
new TextRun({
text: this._sanitizeDocxText(entry.label),
color: "0563C1",
underline: {},
}),
],
}),
],
}),
);
}
/**
* Crea un heading con bookmark interno para navegación desde tabla de contenido.
* @private
*/
_createBookmarkedHeadingParagraph(title, headingLevel, bookmarkId) {
const bookmarkRangeId = this._nextBookmarkSequence();
return new Paragraph({
heading: headingLevel,
children: [
new BookmarkStart(this._sanitizeDocxText(bookmarkId), bookmarkRangeId),
new TextRun({
text: this._sanitizeDocxText(title),
}),
new BookmarkEnd(bookmarkRangeId),
],
});
}
/**
* Genera ID válido de bookmark para navegación interna.
* @private
*/
_buildBookmarkId(value, prefix = "sec") {
const normalized = this._sanitizeDocxText(String(value || ""))
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 40);
return `${prefix}-${normalized || "item"}`;
}
/**
* Calcula dimensiones de logo para encabezado por página.
* @private
*/
_buildHeaderLogoTransformation(visualProfile = null) {
const baseWidth = Number(visualProfile?.logoWidthPx) || 353;
const baseHeight = Number(visualProfile?.logoHeightPx) || 121;
const maxWidth = 160;
const maxHeight = 56;
const ratio = Math.min(maxWidth / baseWidth, maxHeight / baseHeight, 1);
return {
width: Math.max(1, Math.round(baseWidth * ratio)),
height: Math.max(1, Math.round(baseHeight * ratio)),
};
}
/**
* Crea encabezado con logo para todas las páginas.
* @private
*/
_createDocumentHeader(logoAsset, visualProfile = null) {
const children = [];
if (logoAsset) {
children.push(
new Paragraph({
alignment: AlignmentType.RIGHT,
spacing: {
after: 40,
},
children: [
new ImageRun({
data: logoAsset.data,
type: logoAsset.type,
transformation: this._buildHeaderLogoTransformation(visualProfile),
}),
],
}),
);
}
children.push(
new Paragraph({
border: {
bottom: {
style: BorderStyle.SINGLE,
size: 1,
color: "D9D9D9",
},
},
spacing: {
after: 80,
},
}),
);
return new Header({ children });
}
/**
* Obtiene secuencia incremental para bookmarks.
* @private
*/
_nextBookmarkSequence() {
const current = this._bookmarkSequence;
this._bookmarkSequence += 1;
return current;
}
/**
* Estilos base para mantener consistencia tipográfica en Word.
* @private
*/
_buildDocumentStyles(visualProfile = null) {
const bodyFont = visualProfile?.bodyFontFamily || "Calibri";
const heading1Font = visualProfile?.heading1FontFamily || bodyFont;
const heading2Font = visualProfile?.heading2FontFamily || heading1Font;
const bodyFontSize = this._toDocxHalfPoint(visualProfile?.bodyFontSizePt, 24);
const heading1FontSize = this._toDocxHalfPoint(
visualProfile?.heading1FontSizePt,
40,
);
const heading2FontSize = this._toDocxHalfPoint(
visualProfile?.heading2FontSizePt,
32,
);
const headingColor = visualProfile?.headingColor || "000000";
const bodyColor = visualProfile?.bodyColor || "000000";
const labelColor = visualProfile?.scenarioLabelText || "FFFFFF";
return {
default: {
document: {
run: {
font: bodyFont,
size: bodyFontSize,
color: bodyColor,
},
paragraph: {
spacing: {
line: 276,
after: 120,
},
},
},
},
paragraphStyles: [
{
id: "Heading1",
name: "Heading 1",
basedOn: "Normal",
next: "Normal",
quickFormat: true,
run: {
font: heading1Font,
size: heading1FontSize,
bold: true,
color: headingColor,
},
paragraph: {
spacing: {
before: 160,
after: 120,
line: 276,
},
outlineLevel: 0,
},
},
{
id: "Heading2",
name: "Heading 2",
basedOn: "Normal",
next: "Normal",
quickFormat: true,
run: {
font: heading2Font,
size: heading2FontSize,
bold: true,
color: headingColor,
},
paragraph: {
spacing: {
before: 120,
after: 80,
line: 276,
},
outlineLevel: 1,
},
},
],
characterStyles: [
{
id: "ScenarioLabel",
name: "Scenario Label",
basedOn: "DefaultParagraphFont",
run: {
font: bodyFont,
size: bodyFontSize,
bold: true,
color: labelColor,
},
},
],
};
}
/**
* Crear sección de escenario
* @private
*/
async _createScenarioSection(scenario, number, bookmarkId = null, visualProfile = null) {
const scenarioCode = this._sanitizeDocxText(scenario.id || `THL-AUTO-${number}`);
const scenarioBaseTitle = this._sanitizeDocxText(
scenario.title || `Escenario ${number}`,
);
const scenarioTitle = `${scenarioCode}: ${scenarioBaseTitle}`;
const descriptionText = this._sanitizeDocxText(
scenario.preconditions || `Validar ${scenarioBaseTitle}`,
);
const resolvedVisualProfile = {
scenarioLabelFill: "156082",
scenarioLabelText: "FFFFFF",
tableBorderColor: "FFFFFF",
...(visualProfile || {}),
};
const descriptionParagraphs = await this._buildRichParagraphsFromMarkdown(
descriptionText,
);
const steps = Array.isArray(scenario.steps)
? scenario.steps.filter(Boolean)
: [];
const stepParagraphs = [];
if (steps.length > 0) {
for (let idx = 0; idx < steps.length; idx += 1) {
const step = steps[idx];
const normalizedStep = /^\s*\d+\./.test(step)
? step
: `${idx + 1}. ${step}`;
const stepParts = await this._buildRichParagraphsFromMarkdown(normalizedStep);
stepParagraphs.push(...stepParts);
}
} else {
stepParagraphs.push(new Paragraph({ text: "1. Ejecutar flujo funcional principal" }));
}
const expectedLines = String(scenario.expectedResult || "Resultado esperado no especificado")
.split(/\n+/)
.map((line) => line.trim())
.filter(Boolean);
const expectedParagraphs = [];
if (expectedLines.length > 0) {
for (const line of expectedLines) {
const lineWithoutBullet = this._sanitizeDocxText(
line.replace(/^[-•]\s*/, ""),
);
const lineParts = await this._buildRichParagraphsFromMarkdown(
lineWithoutBullet,
{ prefix: "• " },
);
expectedParagraphs.push(...lineParts);
}
} else {
expectedParagraphs.push(new Paragraph({ text: "• Resultado esperado no especificado" }));
}
const scenarioTable = new Table({
width: { size: 100, type: WidthType.PERCENTAGE },
borders: {
top: {
style: BorderStyle.SINGLE,
size: 1,
color: resolvedVisualProfile.tableBorderColor,
},
bottom: {
style: BorderStyle.SINGLE,
size: 1,
color: resolvedVisualProfile.tableBorderColor,
},
left: {
style: BorderStyle.SINGLE,
size: 1,
color: resolvedVisualProfile.tableBorderColor,
},
right: {
style: BorderStyle.SINGLE,
size: 1,
color: resolvedVisualProfile.tableBorderColor,
},
insideHorizontal: {
style: BorderStyle.SINGLE,
size: 1,
color: resolvedVisualProfile.tableBorderColor,
},
insideVertical: {
style: BorderStyle.SINGLE,
size: 1,
color: resolvedVisualProfile.tableBorderColor,
},
},
rows: [
new TableRow({
children: [
this._createScenarioLabelCell("Descripción", resolvedVisualProfile),
new TableCell({
width: { size: 75, type: WidthType.PERCENTAGE },
children: descriptionParagraphs,
}),
],
}),
new TableRow({
children: [
this._createScenarioLabelCell("Pasos", resolvedVisualProfile),
new TableCell({ children: stepParagraphs }),
],
}),
new TableRow({
children: [
this._createScenarioLabelCell(
"Resultado Esperado",
resolvedVisualProfile,
),
new TableCell({ children: expectedParagraphs }),
],
}),
new TableRow({
children: [
this._createScenarioLabelCell(
"Resultado Obtenido",
resolvedVisualProfile,
),
new TableCell({ children: [new Paragraph({ text: "Pendiente" })] }),
],
}),
new TableRow({
children: [
this._createScenarioLabelCell("Estado", resolvedVisualProfile),
new TableCell({ children: [new Paragraph({ text: "Pendiente" })] }),
],
}),
new TableRow({
children: [
this._createScenarioLabelCell("Comentarios", resolvedVisualProfile),
new TableCell({ children: [new Paragraph({ text: "" })] }),
],
}),
],
});
const scenarioTitleParagraph = bookmarkId
? new Paragraph({
heading: HeadingLevel.HEADING_2,
children: (() => {
const bookmarkRangeId = this._nextBookmarkSequence();
return [
new BookmarkStart(this._sanitizeDocxText(bookmarkId), bookmarkRangeId),
new TextRun({
text: this._sanitizeDocxText(scenarioTitle),
}),
new BookmarkEnd(bookmarkRangeId),
];
})(),
})
: new Paragraph({
text: this._sanitizeDocxText(scenarioTitle),
heading: HeadingLevel.HEADING_2,
});
return [
scenarioTitleParagraph,
new Paragraph({ text: "" }),
scenarioTable,
new Paragraph({ text: "" }),
];
}
/**
* Crea celda de etiqueta para escenario (texto blanco + fondo #156082).
* @private
*/
_createScenarioLabelCell(text, visualProfile = null) {
const scenarioLabelFill = visualProfile?.scenarioLabelFill || "156082";
const scenarioLabelText = visualProfile?.scenarioLabelText || "FFFFFF";
return new TableCell({
width: { size: 25, type: WidthType.PERCENTAGE },
shading: {
fill: scenarioLabelFill,
color: "auto",
val: "clear",
},
children: [
new Paragraph({
children: [
new TextRun({
text: this._sanitizeDocxText(text),
style: "ScenarioLabel",
bold: true,
color: scenarioLabelText,
}),
],
}),
],
});
}
/**
* Normaliza nombre de autor a un string legible.
* @private
*/
_normalizeAuthorName(value) {
if (!value) {
return "Unknown";
}
if (typeof value === "string") {
return value.trim() || "Unknown";
}
const displayName =
value.displayName || value.name || value.uniqueName || value.id;
return String(displayName || "Unknown").trim() || "Unknown";
}
/**
* Eliminar HTML
* @private
*/
_stripHtml(html) {
if (!html) return "";
const withoutTags = String(html)
.replace(/<br\s*\/?\s*>/gi, "\n")
.replace(/<\/p>/gi, "\n")
.replace(/<\/li>/gi, "\n")
.replace(/<li[^>]*>/gi, "- ")
.replace(/<[^>]+>/g, " ");
return this._sanitizeDocxText(
this._decodeHtmlEntities(withoutTags)
.replace(/\r/g, "")
.replace(/[ \t]+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.replace(/[ \t]{2,}/g, " ")
.trim(),
);
}
/**
* Decodifica entidades HTML (incluyendo tildes y caracteres latinos).
* @private
*/
_decodeHtmlEntities(value) {
const namedEntities = {
nbsp: " ",
amp: "&",
lt: "<",
gt: ">",
quot: '"',
apos: "'",
aacute: "á",
eacute: "é",
iacute: "í",
oacute: "ó",
uacute: "ú",
Aacute: "Á",
Eacute: "É",
Iacute: "Í",
Oacute: "Ó",
Uacute: "Ú",
ntilde: "ñ",
Ntilde: "Ñ",
uuml: "ü",
Uuml: "Ü",
iexcl: "¡",
iquest: "¿",
};
return String(value || "")
.replace(/&#(\d+);/g, (_, code) => {
const numeric = Number(code);
if (!Number.isFinite(numeric) || numeric < 0 || numeric > 0x10ffff) {
return _;
}
try {
return String.fromCodePoint(numeric);
} catch {
return _;
}
})
.replace(/&#x([0-9a-f]+);/gi, (_, code) => {
const numeric = Number.parseInt(code, 16);
if (!Number.isFinite(numeric) || numeric < 0 || numeric > 0x10ffff) {
return _;
}
try {
return String.fromCodePoint(numeric);
} catch {
return _;
}
})
.replace(/&([a-zA-Z]+);/g, (match, name) =>
Object.prototype.hasOwnProperty.call(namedEntities, name)
? namedEntities[name]
: match,
);
}
}
module.exports = TestPlanGenerator;
|