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 | 104x 104x 104x 104x 60x 276x 46x 230x 10x 220x 147x 39x 108x 108x 108x 96x 38x 58x 58x 58x 96x 60x 36x 24x 8x 28x 104x 14x 13x 1x 3x 1x 14x 10x 42x 104x 44x 44x 44x 44x 44x 44x 44x 8x 8x 8x 8x 8x 8x 8x 7x 7x 7x 5x 8x 5x 3x 5x 3x 3x 1x 1x 1x 2x 535x 535x 535x 535x 8x 8x 6x 529x 113x 113x 106x 106x 423x 22x 21x 1x 22x 104x 34x 34x 104x 104x 433x 433x 119x 314x 314x 8x 2x 1x 1x 1x 3x 29x 18x 11x 5x 6x 6x 2x 6x 1x 6x 5x 7x 3x 4x 4x 1x 3x 3x 1x 2x 7x 22x 22x 22x 22x 1x 1x 21x 22x 22x 1x 21x 21x 1x 20x 2x 2x 2x 2x 2x 2x 22x 22x 22x 22x 22x 22x 22x 22x 2x 2x 22x 22x 22x 22x 22x 22x 104x 104x 104x 22x 22x 22x 15x 7x 22x 22x 22x 22x 22x 22x 15x 7x 5x 2x 2x 2x 2x 2x 22x 16x 6x 1x 2x 1x 1x 1x 33x 33x 33x 33x 33x 33x 1x 33x 3x 3x 3x 33x 33x 1x 33x 33x 33x 33x 33x 14x 33x 33x 33x 2x 2x 2x 2x 1x 1x 33x 33x 33x 32x 32x 2x 32x 33x 32x 32x 1x 32x 33x 14x 33x 33x 33x 1x 1x 1x 1x 33x 1x 1x 33x 1x 33x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 1x 3x 3x 3x 3x 3x 4x 4x 4x 4x 2x 2x 1x 1x 1x 1x 4x 1x 4x 4x 4x 3x 2x 2x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 403x 52x 52x 52x 52x 52x 52x 52x 52x 52x 51x 52x 52x 52x 51x 51x 51x 22x 104x 31x 31x 2x 29x 31x 31x 31x 31x 31x 31x 29x 29x 29x 31x 31x 30x 31x 29x 32x 32x 25x 7x 7x 1x 1x 1x 7x 1x 1x 1x 7x 1x 1x 1x 1x 1x 7x 6x 1x 32x 32x 28x 4x 32x 1x 3x 3x 1x 3x 2x 3x 1x 3x 1x 3x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 32x 32x 28x 4x 4x 4x 4x 4x 4x 4x 4x 4x 32x 32x 32x 32x 32x 32x 32x 26x 32x 1x 32x 32x 1x 32x 1x 1x 1x 1x 32x 1x 32x 32x 32x 32x 3x 3x 32x 32x 1x 1x 32x 32x 2x 2x 1x 1x 32x 32x 2x 2x 32x 32x 4x 4x 3x 3x 32x 32x 4x 4x 32x 4x 4x 4x 4x 4x 5x 32x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 4x 4x 4x 4x 4x 4x 1x 4x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 2x 2x 10x 1x 9x 10x 10x 10x 10x 10x 10x 10x 10x 466x 466x 466x 466x 163x 303x 100x 203x 52x 151x 2x 2x 2x 1x 2x 2x 2x 2x 126x 58x 68x 196x 100x 31x 69x 127x 127x 27x 100x 100x 39x 61x 61x 19x 42x 105x 105x 105x 51x 54x 54x 3x 1x 2x 2x 2x 2x 2x 20x 10x 10x 10x 20x 20x 20x 10x 20x 1x 20x 20x 20x 2x 20x 10x 20x 1x 1x 1x 1x 1x 1x 1x 104x 20x 20x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 20x 20x 20x 20x 20x 20x 26x 26x 26x 26x 26x 4x 22x 26x 26x 2x 2x 26x 4x 4x 22x 15x 15x 26x 26x 20x 26x 22x 26x 26x 22x 22x 26x 7x 7x 7x 1x 6x 79x 28x 51x 2x 49x 87x 59x 28x 28x 28x 28x 28x 28x 79x 79x 79x 30x 49x 28x 29x 29x 29x 29x 29x 9x 9x 79x 29x 79x 79x 29x 29x 29x 29x 9x 9x 29x 11x 11x 29x 8x 8x 29x 12x 12x 12x 12x 29x 29x 4x 25x 8x 17x 7x 29x 104x 104x 104x 104x 104x 1x 1x 1x 26x 25x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 104x 26x 26x 9x 9x 1x 8x 6x 2x 9x 3x 3x 14x 7x 7x 14x 26x 26x 26x 7x 8x 26x 26x 26x 1x 25x 6x 6x 19x 19x 19x 19x 19x 19x 19x 3x 3x 3x 3x 37x 37x 37x 18x 18x 18x 18x 18x 18x 104x 5x 3x 2x 2x 5x 5x 5x 5x 9x 5x 2x 2x 1x 1x 1x | /**
* Human-readable output formatters
*
* Centralized formatting utilities for consistent CLI output.
* Detail views (issue, event, org, project) are built as markdown and rendered
* via renderMarkdown(). List rows still use lightweight inline formatting for
* performance, while list tables are rendered via writeTable() → renderMarkdown().
*/
// biome-ignore lint/performance/noNamespaceImport: Sentry SDK recommends namespace import
import * as Sentry from "@sentry/node-core/light";
import prettyMs from "pretty-ms";
import type {
DashboardDetail,
DashboardWidget,
} from "../../types/dashboard.js";
import type {
BreadcrumbsEntry,
ExceptionEntry,
ExceptionValue,
IssueStatus,
RequestEntry,
SentryEvent,
SentryIssue,
SentryOrganization,
SentryProject,
StackFrame,
TraceSpan,
Writer,
} from "../../types/index.js";
import { resolveOrgDisplayName } from "../api-client.js";
import { getReplayIdFromEvent } from "../replay-search.js";
import { withSerializeSpan } from "../telemetry.js";
import { type FixabilityTier, muted } from "./colors.js";
import {
colorTag,
escapeMarkdownCell,
escapeMarkdownInline,
isPlainOutput,
mdKvTable,
mdRow,
mdTableHeader,
renderMarkdown,
safeCodeSpan,
} from "./markdown.js";
import { sparkline } from "./sparkline.js";
import { colorizeSql, isDbSpanOp } from "./sql.js";
import { type Column, writeTable } from "./table.js";
import { computeSpanDurationMs, formatRelativeTime } from "./time-utils.js";
// Color tag maps
/** Markdown color tags for Seer fixability tiers */
const FIXABILITY_TAGS: Record<FixabilityTier, Parameters<typeof colorTag>[0]> =
{
high: "green",
med: "yellow",
low: "red",
};
// Status Formatting
const STATUS_ICONS: Record<IssueStatus, string> = {
resolved: colorTag("green", "✓"),
resolvedInNextRelease: colorTag("green", "✓"),
unresolved: colorTag("yellow", "●"),
ignored: colorTag("muted", "−"),
muted: colorTag("muted", "−"),
};
const STATUS_LABELS: Record<IssueStatus, string> = {
resolved: `${colorTag("green", "✓")} Resolved`,
resolvedInNextRelease: `${colorTag("green", "✓")} Resolved in Next Release`,
unresolved: `${colorTag("yellow", "●")} Unresolved`,
ignored: `${colorTag("muted", "−")} Ignored`,
muted: `${colorTag("muted", "−")} Muted`,
};
/** Maximum features to display before truncating with "... and N more" */
const MAX_DISPLAY_FEATURES = 10;
/**
* Capitalize the first letter of a string
*/
function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* Convert Seer fixability score to a tier label.
*
* Thresholds are simplified from Sentry core (sentry/seer/autofix/constants.py)
* into 3 tiers for CLI display.
*
* @param score - Numeric fixability score (0-1)
* @returns `"high"` | `"med"` | `"low"`
*/
export function getSeerFixabilityLabel(score: number): FixabilityTier {
if (score > 0.66) {
return "high";
}
if (score > 0.33) {
return "med";
}
return "low";
}
/**
* Format fixability score as "label(pct%)" for compact list display.
*
* @param score - Numeric fixability score, or null/undefined if unavailable
* @returns Formatted string like `"med(50%)"`, or `""` when score is unavailable
*/
export function formatFixability(score: number | null | undefined): string {
if (score === null || score === undefined) {
return "";
}
const label = getSeerFixabilityLabel(score);
const pct = Math.round(score * 100);
return `${label}(${pct}%)`;
}
/**
* Format fixability score for detail view: "Label (pct%)".
*
* Uses capitalized label with space before parens for readability
* in the single-issue detail display.
*
* @param score - Numeric fixability score, or null/undefined if unavailable
* @returns Formatted string like `"Med (50%)"`, or `""` when score is unavailable
*/
export function formatFixabilityDetail(
score: number | null | undefined
): string {
if (score === null || score === undefined) {
return "";
}
const label = getSeerFixabilityLabel(score);
const pct = Math.round(score * 100);
return `${capitalize(label)} (${pct}%)`;
}
/** Map of entry type strings to their TypeScript types */
type EntryTypeMap = {
exception: ExceptionEntry;
breadcrumbs: BreadcrumbsEntry;
request: RequestEntry;
};
/**
* Extract a typed entry from event entries by type
* @returns The entry if found, null otherwise
*/
function extractEntry<T extends keyof EntryTypeMap>(
event: SentryEvent,
type: T
): EntryTypeMap[T] | null {
if (!event.entries) {
return null;
}
for (const entry of event.entries) {
if (
entry &&
typeof entry === "object" &&
"type" in entry &&
entry.type === type
) {
return entry as EntryTypeMap[T];
}
}
return null;
}
/** Regex to extract base URL from a permalink */
const BASE_URL_REGEX = /^(https?:\/\/[^/]+)/;
/**
* Format a features list as a markdown bullet list.
*
* @param features - Array of feature names (may be undefined)
* @returns Markdown string, or empty string if no features
*/
function formatFeaturesMarkdown(features: string[] | undefined): string {
if (!features || features.length === 0) {
return "";
}
const displayFeatures = features.slice(0, MAX_DISPLAY_FEATURES);
const items = displayFeatures.map((f) => `- ${f}`).join("\n");
const more =
features.length > MAX_DISPLAY_FEATURES
? `\n*... and ${features.length - MAX_DISPLAY_FEATURES} more*`
: "";
return `\n**Features** (${features.length}):\n\n${items}${more}`;
}
/**
* Get status icon for an issue status
*/
export function formatStatusIcon(status: string | undefined): string {
return STATUS_ICONS[status as IssueStatus] ?? colorTag("yellow", "●");
}
/**
* Get full status label for an issue status
*/
export function formatStatusLabel(status: string | undefined): string {
return (
STATUS_LABELS[status as IssueStatus] ?? `${colorTag("yellow", "●")} Unknown`
);
}
// Issue Formatting
/** Quantifier suffixes indexed by groups of 3 digits (K=10^3, M=10^6, …, E=10^18) */
const QUANTIFIERS = ["", "K", "M", "B", "T", "P", "E"];
/**
* Abbreviate large numbers with K/M/B/T/P/E suffixes (up to 10^18).
*
* The decimal is only shown when the rounded value is < 100 (e.g. "12.3K",
* "1.5M" but not "100M").
*
* @param raw - Stringified count
* @returns Abbreviated string without padding
*/
function abbreviateCount(raw: string): string {
const n = Number(raw);
Iif (Number.isNaN(n)) {
Sentry.logger.warn(`Unexpected non-numeric issue count: ${raw}`);
return "?";
}
Eif (n < 1000) {
return raw;
}
const tier = Math.min(Math.floor(Math.log10(n) / 3), QUANTIFIERS.length - 1);
const suffix = QUANTIFIERS[tier] ?? "";
const scaled = n / 10 ** (tier * 3);
const rounded1dp = Number(scaled.toFixed(1));
Iif (rounded1dp < 100) {
return `${rounded1dp.toFixed(1)}${suffix}`;
}
const rounded = Math.round(scaled);
if (rounded >= 1000 && tier < QUANTIFIERS.length - 1) {
const nextSuffix = QUANTIFIERS[tier + 1] ?? "";
return `${(rounded / 1000).toFixed(1)}${nextSuffix}`;
}
return `${Math.min(rounded, 999)}${suffix}`;
}
/**
* Options for formatting short IDs with alias highlighting.
*/
export type FormatShortIdOptions = {
/** Project slug to determine the prefix for suffix highlighting */
projectSlug?: string;
/** Project alias (e.g., "e", "w", "o1:d") for multi-project display */
projectAlias?: string;
/** Whether in multi-project mode (highlights alias chars in short ID) */
isMultiProject?: boolean;
};
/**
* Format short ID for multi-project mode by highlighting the alias characters.
* Only highlights the specific characters that form the alias:
* - CLI-25 with alias "c" → **C**LI-**25**
*
* @returns Formatted string with ANSI highlights, or null if no match found
*/
function formatShortIdWithAlias(
shortId: string,
projectAlias: string
): string | null {
// Extract the project part of the alias — cross-org collision aliases use
// the format "o1/d" where only "d" should match against the short ID parts.
const aliasPart = projectAlias.includes("/")
? (projectAlias.split("/").pop() ?? projectAlias)
: projectAlias;
const aliasUpper = aliasPart.toUpperCase();
const aliasLen = aliasUpper.length;
const parts = shortId.split("-");
const issueSuffix = parts.pop() ?? "";
const projectParts = parts;
if (!aliasUpper.includes("-")) {
for (let i = projectParts.length - 1; i >= 0; i--) {
const part = projectParts[i];
if (part?.startsWith(aliasUpper)) {
const result = projectParts.map((p, idx) => {
if (idx === i) {
return `${colorTag("bu", p.slice(0, aliasLen))}${p.slice(aliasLen)}`;
}
return p;
});
return `${result.join("-")}-${colorTag("bu", issueSuffix)}`;
}
}
}
const projectPortion = projectParts.join("-");
if (projectPortion.startsWith(aliasUpper)) {
const highlighted = colorTag("bu", projectPortion.slice(0, aliasLen));
const rest = projectPortion.slice(aliasLen);
return `${highlighted}${rest}-${colorTag("bu", issueSuffix)}`;
}
return null;
}
/**
* Format a short ID with highlighting to show what the user can type as shorthand.
*
* - Single project: CLI-25 → CLI-**25** (suffix highlighted)
* - Multi-project: CLI-WEBSITE-4 with alias "w" → CLI-**W**EBSITE-**4** (alias chars highlighted)
*
* @param shortId - Full short ID (e.g., "CLI-25", "CLI-WEBSITE-4")
* @param options - Formatting options (projectSlug and/or projectAlias)
* @returns Formatted short ID with highlights
*/
export function formatShortId(
shortId: string,
options?: FormatShortIdOptions | string
): string {
const opts: FormatShortIdOptions =
typeof options === "string" ? { projectSlug: options } : (options ?? {});
const { projectSlug, projectAlias, isMultiProject } = opts;
const upperShortId = shortId.toUpperCase();
if (isMultiProject && projectAlias) {
const formatted = formatShortIdWithAlias(upperShortId, projectAlias);
if (formatted) {
return formatted;
}
}
if (projectSlug) {
const prefix = `${projectSlug.toUpperCase()}-`;
if (upperShortId.startsWith(prefix)) {
const suffix = shortId.slice(prefix.length);
return `${prefix}${colorTag("bu", suffix.toUpperCase())}`;
}
}
return upperShortId;
}
/**
* Compute the alias shorthand for an issue (e.g., "o1:d-a3", "w-2a").
* This is what users type to reference the issue.
*
* @param shortId - Full short ID (e.g., "DASHBOARD-A3")
* @param projectAlias - Project alias (e.g., "o1:d", "w")
* @returns Alias shorthand (e.g., "o1:d-a3", "w-2a") or empty string if no alias
*/
function computeAliasShorthand(shortId: string, projectAlias?: string): string {
if (!projectAlias) {
return "";
}
const suffix = shortId.split("-").pop()?.toLowerCase() ?? "";
return `${projectAlias}-${suffix}`;
}
// Issue Table Helpers
/** Minimum terminal width to show the TREND sparkline column. */
export const TREND_MIN_TERM_WIDTH = 100;
/**
* Whether the TREND sparkline column will be rendered in the issue table.
*
* Returns `true` when the terminal is wide enough (≥ {@link TREND_MIN_TERM_WIDTH}).
* Non-TTY output defaults to 80 columns, which is below the threshold.
*
* Used by the issue list command to decide whether to request stats data
* from the API — when TREND won't be shown, stats can be collapsed to
* save 200-500ms per request.
*/
export function willShowTrend(): boolean {
const termWidth = process.stdout.columns || 80;
return termWidth >= TREND_MIN_TERM_WIDTH;
}
/** Lines per issue row in non-compact mode (2-line content + separator). */
const LINES_PER_DEFAULT_ROW = 3;
/**
* Fixed line overhead for the rendered table.
*
* Top border (1) + header row (1) + header separator (1) + bottom border (1) = 4,
* minus 1 because the last data row has no trailing separator (row separators
* are drawn between data rows only: `r > 0 && r < allRows.length - 1`).
* Net overhead = 3.
*/
const TABLE_LINE_OVERHEAD = 3;
/**
* Determine whether auto-compact should activate based on terminal height.
*
* Returns `true` when the estimated non-compact table height exceeds the
* terminal's row count, meaning compact mode would keep output on-screen.
*
* Returns `false` when terminal height is unknown (non-TTY/piped output)
* to prefer full output for downstream parsing.
*
* @param rowCount - Number of issue rows to render
* @returns Whether compact mode should be used
*/
export function shouldAutoCompact(rowCount: number): boolean {
const termHeight = process.stdout.rows;
if (!termHeight) {
return false;
}
const estimatedHeight =
rowCount * LINES_PER_DEFAULT_ROW + TABLE_LINE_OVERHEAD;
return estimatedHeight > termHeight;
}
/**
* Substatus label for the TREND column's second line.
* Matches Sentry web UI visual indicators.
*/
export function substatusLabel(substatus?: string | null): string {
switch (substatus) {
case "regressed":
return colorTag("red", "Regressed");
case "escalating":
return colorTag("yellow", "Escalating");
case "new":
return colorTag("green", "New");
case "ongoing":
return colorTag("muted", "Ongoing");
default:
return "";
}
}
/**
* Build issue subtitle from metadata for the ISSUE column.
*
* Prefers `metadata.value` (error message), falling back to
* `metadata.type` + `metadata.function` for structured metadata.
*
* The result is a single line — truncation to the available column
* width is handled by the table renderer's word-wrapping/truncation.
*
* @param metadata - Issue metadata from the API
* @returns Subtitle string, or empty string if no relevant metadata
*/
export function formatIssueSubtitle(
metadata?: SentryIssue["metadata"]
): string {
if (!metadata) {
return "";
}
if (metadata.value) {
return collapseWhitespace(metadata.value);
}
const parts: string[] = [];
if (metadata.type) {
parts.push(metadata.type);
}
if (metadata.function) {
parts.push(`in ${metadata.function}`);
}
return parts.join(" ");
}
/**
* Collapse runs of whitespace (including newlines) into single spaces
* and trim the result. Prevents multi-line metadata values from blowing
* up the ISSUE cell height.
*/
function collapseWhitespace(s: string): string {
return s.replace(/\s+/g, " ").trim();
}
/**
* Extract sparkline data points from the issue stats object.
*
* Stats keys depend on `groupStatsPeriod` ("24h", "14d", "auto", etc.).
* Each entry in the time-series is `[timestamp, count]`.
* Takes the first available key since the API returns one key matching
* the requested period.
*
* @param stats - Issue stats object from the API
* @returns Array of numeric counts for each time bucket
*/
export function extractStatsPoints(stats?: Record<string, unknown>): number[] {
if (!stats) {
return [];
}
const key = Object.keys(stats)[0];
if (!key) {
return [];
}
const buckets = stats[key];
if (!Array.isArray(buckets)) {
return [];
}
return buckets.map((b: unknown) =>
Array.isArray(b) && b.length >= 2 ? Number(b[1]) || 0 : 0
);
}
/** Row data prepared for the issue table */
export type IssueTableRow = {
issue: SentryIssue;
/** Org slug — used as project key in trimWithProjectGuarantee and similar utilities. */
orgSlug: string;
formatOptions: FormatShortIdOptions;
};
/**
* Format the SHORT ID cell with optional alias.
*
* Default (2-line): linked short ID on line 1, muted alias on line 2.
* Compact (single-line): alias appended as a suffix on the same line.
*
* @param issue - The Sentry issue
* @param formatOptions - Formatting options with alias info
* @param compact - Whether to use single-line layout
* @returns Cell string
*/
function formatIdCell(
issue: SentryIssue,
formatOptions: FormatShortIdOptions,
compact = false
): string {
const formatted = formatShortId(issue.shortId, formatOptions);
const linked = issue.permalink
? `[${formatted}](${issue.permalink})`
: formatted;
const alias = computeAliasShorthand(
issue.shortId,
formatOptions.projectAlias
);
if (alias) {
const sep = compact ? " " : "\n";
return `${linked}${sep}${colorTag("muted", alias)}`;
}
return linked;
}
/**
* Format the ISSUE cell.
*
* Default (2-line): bold title on line 1, muted subtitle on line 2.
* Compact (single-line): bold title only — truncated with "…" by the renderer.
*
* @param issue - The Sentry issue
* @param compact - Whether to use single-line layout
* @returns Cell string
*/
function formatIssueCell(issue: SentryIssue, compact = false): string {
const title = `**${escapeMarkdownInline(issue.title)}**`;
if (compact) {
return title;
}
const subtitle = formatIssueSubtitle(issue.metadata);
if (subtitle) {
return `${title}\n${colorTag("muted", escapeMarkdownInline(subtitle))}`;
}
return title;
}
/**
* Format the TREND cell with sparkline and substatus label.
*
* Default (2-line): sparkline on line 1, substatus label on line 2.
* Compact (single-line): sparkline + substatus on the same line.
*
* @param issue - The Sentry issue
* @param compact - Whether to use single-line layout
* @returns Cell string
*/
function formatTrendCell(issue: SentryIssue, compact = false): string {
const points = extractStatsPoints(
issue.stats as Record<string, unknown> | undefined
);
const graph = points.length > 0 ? colorTag("muted", sparkline(points)) : "";
const status = substatusLabel(issue.substatus);
const parts = [graph, status].filter(Boolean);
const sep = compact ? " " : "\n";
return parts.join(sep);
}
/**
* Write an issue list as a Unicode-bordered markdown table.
*
* Columns match the Sentry web UI issue stream layout:
*
* | SHORT ID (+ alias) | ISSUE | SEEN | AGE | TREND | EVENTS | USERS | TRIAGE |
*
* Default mode: 2-line rows (title + subtitle, sparkline + substatus, etc.)
* for maximum information density. Row separators drawn between rows.
*
* Compact mode (`--compact`): single-line rows for quick scanning. All cells
* collapsed to one line, long titles truncated with "…".
*
* Callers should resolve auto-compact (via {@link shouldAutoCompact}) before
* passing `compact` — this function treats `undefined` as `false`.
*
* @param stdout - Output writer
* @param rows - Issues with formatting options
* @param options - Display options
*/
export function writeIssueTable(
stdout: Writer,
rows: IssueTableRow[],
options?: { compact?: boolean }
): void {
const compact = options?.compact ?? false;
const showTrend = willShowTrend();
const columns: Column<IssueTableRow>[] = [
// SHORT ID — primary identifier (+ alias), never shrink
{
header: "SHORT ID",
shrinkable: false,
value: ({ issue, formatOptions }) =>
formatIdCell(issue, formatOptions, compact),
},
// ISSUE — title (+ subtitle in default mode)
{
header: "ISSUE",
value: ({ issue }) => formatIssueCell(issue, compact),
},
// SEEN — lastSeen
{
header: "SEEN",
value: ({ issue }) => formatRelativeTime(issue.lastSeen ?? undefined),
},
// AGE — firstSeen
{
header: "AGE",
value: ({ issue }) => formatRelativeTime(issue.firstSeen ?? undefined),
},
];
// TREND — sparkline + substatus (2-line), auto-hidden on narrow terminals
if (showTrend) {
columns.push({
header: "TREND",
value: ({ issue }) => formatTrendCell(issue, compact),
shrinkable: false,
});
}
columns.push(
// EVENTS — period-scoped count
{
header: "EVENTS",
value: ({ issue }) => abbreviateCount(`${issue.count}`),
align: "right",
},
// USERS — affected user count
{
header: "USERS",
value: ({ issue }) => abbreviateCount(`${issue.userCount ?? 0}`),
align: "right",
},
// TRIAGE — combined priority + fixability for actionability
{
header: "TRIAGE",
value: ({ issue }) =>
formatTriageCell(issue.priority, issue.seerFixabilityScore),
}
);
// Row separators colored with the muted palette color (#898294 → RGB 137,130,148)
// so they're lighter than the solid outer borders.
const mutedAnsi = "\x1b[38;2;137;130;148m";
writeTable(stdout, rows, columns, {
rowSeparator: mutedAnsi,
truncate: true,
});
}
/** Weight assigned to each priority level for composite triage scoring. */
const PRIORITY_WEIGHTS: Record<string, number> = {
critical: 1.0,
high: 0.75,
medium: 0.5,
low: 0.25,
};
/** Default impact weight when priority is unknown. */
const DEFAULT_IMPACT_WEIGHT = 0.5;
/** How much impact (priority) contributes to the composite score. */
const IMPACT_RATIO = 0.6;
/**
* Compute composite triage score from priority and fixability.
*
* The score blends impact (from priority) and fixability (from Seer)
* using a weighted average: `impact × 0.6 + fixability × 0.4`.
* Higher scores mean "fix this first" — high impact AND easy to fix.
*
* @param priority - Priority string from the API
* @param fixabilityScore - Seer fixability score (0–1)
* @returns Composite score (0–1), or null if neither dimension is available
*/
function computeTriageScore(
priority?: string | null,
fixabilityScore?: number | null
): number | null {
const hasPriority = Boolean(priority);
const hasFix = fixabilityScore !== null && fixabilityScore !== undefined;
if (!(hasPriority || hasFix)) {
return null;
}
const impact = hasPriority
? (PRIORITY_WEIGHTS[priority?.toLowerCase() ?? ""] ?? DEFAULT_IMPACT_WEIGHT)
: DEFAULT_IMPACT_WEIGHT;
const fix = hasFix ? fixabilityScore : DEFAULT_IMPACT_WEIGHT;
return impact * IMPACT_RATIO + fix * (1 - IMPACT_RATIO);
}
/**
* Format the TRIAGE cell as a single-line composite score.
*
* Combines priority (impact) and Seer fixability into a single percentage
* that answers "should I fix this now?". The score is colored by tier:
* green (≥67%), yellow (34–66%), red (≤33%).
*
* Displays:
* - Both available: `"High 82%"` — priority label + composite score
* - Priority only: `"High"` — just the label (no score without fixability)
* - Fixability only: `"78%"` — composite score alone
* - Neither: empty
*
* @param priority - Priority string from the API
* @param fixabilityScore - Seer AI fixability score (0–1)
* @returns Single-line cell string
*/
function formatTriageCell(
priority?: string | null,
fixabilityScore?: number | null
): string {
const hasFix = fixabilityScore !== null && fixabilityScore !== undefined;
const label = formatPriorityLabel(priority);
const score = computeTriageScore(priority, fixabilityScore);
// No data at all
if (score === null) {
return "";
}
// Priority without fixability — show label only (no fake %)
if (!hasFix) {
return label;
}
// Format the composite percentage
const pct = Math.round(score * 100);
const tier = getSeerFixabilityLabel(score);
const tag = FIXABILITY_TAGS[tier];
const pctStr = colorTag(tag, `${pct}%`);
return label ? `${label} ${pctStr}` : pctStr;
}
/**
* Format priority as a colored label.
*
* @param priority - Priority string from the API
* @returns Colored label or empty string
*/
function formatPriorityLabel(priority?: string | null): string {
if (!priority) {
return "";
}
switch (priority.toLowerCase()) {
case "critical":
return colorTag("red", "Critical");
case "high":
return colorTag("red", "High");
case "medium":
return colorTag("yellow", "Med ");
case "low":
return colorTag("muted", "Low ");
default:
return priority;
}
}
/**
* Format detailed issue information as rendered markdown.
*
* @param issue - The Sentry issue to format
* @returns Rendered terminal string
*/
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: issue formatting logic
export function formatIssueDetails(issue: SentryIssue): string {
const lines: string[] = [];
lines.push(`## ${issue.shortId}: ${escapeMarkdownInline(issue.title ?? "")}`);
lines.push("");
// Key-value details as a table
const kvRows: [string, string][] = [];
kvRows.push([
"Status",
`${formatStatusLabel(issue.status)}${issue.substatus ? ` (${capitalize(issue.substatus)})` : ""}`,
]);
if (issue.priority) {
kvRows.push(["Priority", capitalize(issue.priority)]);
}
if (
issue.seerFixabilityScore !== null &&
issue.seerFixabilityScore !== undefined
) {
const tier = getSeerFixabilityLabel(issue.seerFixabilityScore);
const fixDetail = formatFixabilityDetail(issue.seerFixabilityScore);
kvRows.push(["Fixability", colorTag(FIXABILITY_TAGS[tier], fixDetail)]);
}
let levelLine = issue.level ?? "unknown";
if (issue.isUnhandled) {
levelLine += " (unhandled)";
}
kvRows.push(["Level", levelLine]);
kvRows.push(["Platform", issue.platform ?? "unknown"]);
kvRows.push(["Type", issue.type ?? "unknown"]);
kvRows.push([
"Assignee",
escapeMarkdownInline(String(issue.assignedTo?.name ?? "Unassigned")),
]);
if (issue.project) {
kvRows.push([
"Project",
`${escapeMarkdownInline(issue.project.name ?? "(unknown)")} (${safeCodeSpan(issue.project.slug ?? "")})`,
]);
}
const firstReleaseVersion = issue.firstRelease?.shortVersion;
const lastReleaseVersion = issue.lastRelease?.shortVersion;
if (firstReleaseVersion || lastReleaseVersion) {
const first = escapeMarkdownInline(String(firstReleaseVersion ?? ""));
const last = escapeMarkdownInline(String(lastReleaseVersion ?? ""));
if (firstReleaseVersion && lastReleaseVersion) {
if (firstReleaseVersion === lastReleaseVersion) {
kvRows.push(["Release", first]);
} else {
kvRows.push(["Releases", `${first} → ${last}`]);
}
} else Eif (lastReleaseVersion) {
kvRows.push(["Release", last]);
} else if (firstReleaseVersion) {
kvRows.push(["Release", first]);
}
}
kvRows.push(["Events", String(issue.count ?? 0)]);
kvRows.push(["Users", String(issue.userCount ?? 0)]);
if (issue.firstSeen) {
let firstSeenLine = new Date(issue.firstSeen).toLocaleString();
if (firstReleaseVersion) {
firstSeenLine += ` (in ${escapeMarkdownCell(String(firstReleaseVersion))})`;
}
kvRows.push(["First seen", firstSeenLine]);
}
if (issue.lastSeen) {
let lastSeenLine = new Date(issue.lastSeen).toLocaleString();
if (lastReleaseVersion && lastReleaseVersion !== firstReleaseVersion) {
lastSeenLine += ` (in ${escapeMarkdownCell(String(lastReleaseVersion))})`;
}
kvRows.push(["Last seen", lastSeenLine]);
}
if (issue.culprit) {
kvRows.push(["Culprit", safeCodeSpan(issue.culprit)]);
}
kvRows.push(["Link", issue.permalink ?? ""]);
lines.push(mdKvTable(kvRows));
if (issue.metadata?.value) {
lines.push("");
lines.push("**Message:**");
lines.push("");
lines.push(
`> ${escapeMarkdownInline(issue.metadata.value).replace(/\n/g, "\n> ")}`
);
}
if (issue.metadata?.filename) {
lines.push("");
lines.push(`**File:** \`${issue.metadata.filename}\``);
}
if (issue.metadata?.function) {
lines.push(`**Function:** \`${issue.metadata.function}\``);
}
return renderMarkdown(lines.join("\n"));
}
// Stack Trace Formatting
/**
* Format a single stack frame as markdown.
*/
function formatStackFrameMarkdown(frame: StackFrame): string {
const lines: string[] = [];
const fn = frame.function || "<anonymous>";
const file = frame.filename || frame.absPath || "<unknown>";
const line = frame.lineNo ?? "?";
const col = frame.colNo ?? "?";
const inAppTag = frame.inApp ? " `[in-app]`" : "";
lines.push(`${safeCodeSpan(`at ${fn} (${file}:${line}:${col})`)}${inAppTag}`);
if (frame.context && frame.context.length > 0) {
lines.push("");
lines.push("```");
for (const [lineNo, code] of frame.context) {
const isCurrentLine = lineNo === frame.lineNo;
const prefix = isCurrentLine ? ">" : " ";
lines.push(`${prefix} ${String(lineNo).padStart(6)} | ${code}`);
}
lines.push("```");
lines.push("");
}
return lines.join("\n");
}
/**
* Format an exception value (type, message, stack trace) as markdown.
*/
function formatExceptionValueMarkdown(exception: ExceptionValue): string {
const lines: string[] = [];
const type = exception.type || "Error";
const value = exception.value || "";
lines.push(`**${safeCodeSpan(`${type}: ${value}`)}**`);
if (exception.mechanism) {
const handled = exception.mechanism.handled ? "handled" : "unhandled";
const mechType = exception.mechanism.type || "unknown";
lines.push(`*mechanism: ${mechType} (${handled})*`);
}
lines.push("");
const frames = exception.stacktrace?.frames ?? [];
const reversedFrames = [...frames].reverse();
for (const frame of reversedFrames) {
lines.push(formatStackFrameMarkdown(frame));
}
return lines.join("\n");
}
/**
* Build the stack trace section as markdown.
*/
function buildStackTraceMarkdown(exceptionEntry: ExceptionEntry): string {
const lines: string[] = [];
lines.push("### Stack Trace");
lines.push("");
const values = exceptionEntry.data.values ?? [];
for (const exception of values) {
lines.push(formatExceptionValueMarkdown(exception));
}
return lines.join("\n");
}
// Breadcrumbs Formatting
/**
* Build the breadcrumbs section as a markdown table.
*/
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: breadcrumb formatting logic
function buildBreadcrumbsMarkdown(breadcrumbsEntry: BreadcrumbsEntry): string {
const breadcrumbs = breadcrumbsEntry.data.values ?? [];
if (breadcrumbs.length === 0) {
return "";
}
const lines: string[] = [];
lines.push("### Breadcrumbs");
lines.push("");
lines.push(mdTableHeader(["Time", "Level", "Category", "Message"]).trimEnd());
for (const breadcrumb of breadcrumbs) {
const timestamp = breadcrumb.timestamp
? new Date(breadcrumb.timestamp).toLocaleTimeString()
: "??:??:??";
const level = breadcrumb.level ?? "info";
let message = breadcrumb.message ?? "";
if (!message && breadcrumb.data) {
const data = breadcrumb.data as Record<string, unknown>;
if (data.url && data.method) {
const status = data.status_code ? ` → ${data.status_code}` : "";
message = `${data.method} ${data.url}${status}`;
} else if (data.from && data.to) {
message = `${data.from} → ${data.to}`;
} else Eif (data.arguments && Array.isArray(data.arguments)) {
message = String(data.arguments[0] || "").slice(0, 60);
}
}
if (message.length > 80) {
message = `${message.slice(0, 77)}...`;
}
// Escape special markdown characters that would break the table cell
const safeMessage = escapeMarkdownCell(message);
const safeCategory = escapeMarkdownCell(breadcrumb.category ?? "default");
lines.push(mdRow([timestamp, level, safeCategory, safeMessage]).trimEnd());
}
return lines.join("\n");
}
// Request Formatting
/**
* Build the HTTP request section as markdown.
*/
function buildRequestMarkdown(requestEntry: RequestEntry): string {
const data = requestEntry.data;
if (!data.url) {
return "";
}
const lines: string[] = [];
lines.push("### Request");
lines.push("");
const method = data.method || "GET";
lines.push(`\`${method} ${data.url}\``);
if (data.headers) {
for (const [key, value] of data.headers) {
Eif (key.toLowerCase() === "user-agent") {
const truncatedUA =
value.length > 100 ? `${value.slice(0, 97)}...` : value;
lines.push(`**User-Agent:** ${truncatedUA}`);
break;
}
}
}
return lines.join("\n");
}
// Span Tree Formatting
/**
* Apply muted styling only in TTY/colored mode.
*
* Tree output uses box-drawing characters and indentation that can't go
* through full `renderMarkdown()`. This helper ensures no raw ANSI escapes
* leak when `NO_COLOR` is set, output is piped, or `isPlainOutput()` is true.
*/
export function plainSafeMuted(text: string): string {
return isPlainOutput() ? text : muted(text);
}
type FormatSpanOptions = {
lines: string[];
prefix: string;
isLast: boolean;
currentDepth: number;
maxDepth: number;
};
/**
* Recursively format a span and its children as simple tree lines.
* Uses "op — description (duration)" format.
* Duration is omitted when unavailable.
*/
function formatSpanSimple(span: TraceSpan, opts: FormatSpanOptions): void {
const { lines, prefix, isLast, currentDepth, maxDepth } = opts;
const op = span.op || span["transaction.op"] || "unknown";
const desc = span.description || span.transaction || "(no description)";
const branch = isLast ? "└─" : "├─";
const childPrefix = prefix + (isLast ? " " : "│ ");
const colorizedDesc = isDbSpanOp(op) ? colorizeSql(desc) : desc;
let line = `${prefix}${branch} ${plainSafeMuted(op)} — ${colorizedDesc}`;
const durationMs = computeSpanDurationMs(span);
if (durationMs !== undefined) {
line += ` ${plainSafeMuted(`(${prettyMs(durationMs)})`)}`;
}
line += ` ${plainSafeMuted(span.span_id ?? "")}`;
lines.push(line);
if (currentDepth < maxDepth) {
const children = span.children ?? [];
const childCount = children.length;
children.forEach((child, i) => {
formatSpanSimple(child, {
lines,
prefix: childPrefix,
isLast: i === childCount - 1,
currentDepth: currentDepth + 1,
maxDepth,
});
});
}
}
/**
* Maximum number of root-level spans to display before truncating.
* Prevents overwhelming output when traces have thousands of flat root spans
* (common in projects with very high span volume or flat hierarchies).
*/
const MAX_ROOT_SPANS = 50;
/** Options for {@link formatSimpleSpanTree}. */
type SpanTreeOptions = {
/**
* When true, the tree was produced by a project-filtered API call.
* Root spans with `parent_span_id` are annotated as having a parent
* in another project. Without this flag the annotation is suppressed
* because root spans in unfiltered traces can legitimately have
* `parent_span_id` at service boundaries.
*/
projectFiltered?: boolean;
};
/**
* Format trace as a simple tree with "op — description (duration)" per span.
* Durations are shown when available, omitted otherwise.
*
* Root spans are capped at {@link MAX_ROOT_SPANS} to prevent terminal flooding
* when traces contain thousands of flat spans.
*
* @param traceId - The trace ID for the header
* @param spans - Root-level spans from the /trace/ API
* @param maxDepth - Maximum nesting depth to display (default: unlimited). 0 = disabled, Infinity = unlimited.
* @param options - Optional display options (e.g., project filter indicator)
* @returns Array of formatted lines ready for display
*/
export function formatSimpleSpanTree(
traceId: string,
spans: TraceSpan[],
maxDepth = Number.MAX_SAFE_INTEGER,
options: SpanTreeOptions = {}
): string[] {
return withSerializeSpan("formatSimpleSpanTree", () => {
// maxDepth = 0 means disabled (caller should skip, but handle gracefully)
if (maxDepth === 0 || spans.length === 0) {
return [];
}
// Infinity or large numbers = unlimited depth
const effectiveMaxDepth = Number.isFinite(maxDepth)
? maxDepth
: Number.MAX_SAFE_INTEGER;
const lines: string[] = [];
lines.push("");
lines.push(plainSafeMuted("─── Span Tree ───"));
lines.push("");
lines.push(`${plainSafeMuted("Trace —")} ${traceId}`);
// When API filters by project, root spans may have a parent_span_id
// pointing to a span in another project that wasn't returned.
// Only show this annotation when a project filter is active — in
// unfiltered traces, root spans at service boundaries legitimately
// have parent_span_id without implying missing data.
Iif (options.projectFiltered && spans.some((s) => s.parent_span_id)) {
lines.push(plainSafeMuted("⤴ parent span in another project"));
}
const totalRootSpans = spans.length;
const truncated = totalRootSpans > MAX_ROOT_SPANS;
const displaySpans = truncated ? spans.slice(0, MAX_ROOT_SPANS) : spans;
const displayCount = displaySpans.length;
displaySpans.forEach((span, i) => {
formatSpanSimple(span, {
lines,
prefix: "",
isLast: !truncated && i === displayCount - 1,
currentDepth: 1,
maxDepth: effectiveMaxDepth,
});
});
Iif (truncated) {
const remaining = totalRootSpans - MAX_ROOT_SPANS;
lines.push(
`└─ ${plainSafeMuted(`... ${remaining} more root span${remaining === 1 ? "" : "s"} (${totalRootSpans} total). Use --json to see all.`)}`
);
}
return lines;
});
}
// Environment Context Formatting
/**
* Build environment context section (browser, OS, device) as markdown.
*/
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: context formatting logic
function buildEnvironmentMarkdown(event: SentryEvent): string {
const contexts = event.contexts;
if (!contexts) {
return "";
}
const kvRows: [string, string][] = [];
if (contexts.browser) {
const name = contexts.browser.name || "Unknown Browser";
const version = contexts.browser.version || "";
kvRows.push(["Browser", `${name}${version ? ` ${version}` : ""}`]);
}
if (contexts.os) {
const name = contexts.os.name || "Unknown OS";
const version = contexts.os.version || "";
kvRows.push(["OS", `${name}${version ? ` ${version}` : ""}`]);
}
if (contexts.device) {
const family = contexts.device.family || contexts.device.model || "";
const brand = contexts.device.brand || "";
Eif (family || brand) {
const device = brand ? `${family} (${brand})` : family;
kvRows.push(["Device", device]);
}
}
if (kvRows.length === 0) {
return "";
}
return mdKvTable(kvRows, "Environment");
}
/**
* Build user information section as markdown.
*/
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: user formatting logic
function buildUserMarkdown(event: SentryEvent): string {
const user = event.user;
if (!user) {
return "";
}
const hasUserData =
user.email ||
user.username ||
user.id ||
user.ip_address ||
user.name ||
user.geo;
if (!hasUserData) {
return "";
}
const kvRows: [string, string][] = [];
if (user.name) {
kvRows.push(["Name", user.name]);
}
if (user.email) {
kvRows.push(["Email", user.email]);
}
if (user.username) {
kvRows.push(["Username", user.username]);
}
if (user.id) {
kvRows.push(["ID", user.id]);
}
if (user.ip_address) {
kvRows.push(["IP", user.ip_address]);
}
if (user.geo) {
const geo = user.geo;
const parts: string[] = [];
Eif (geo.city) {
parts.push(geo.city);
}
Iif (geo.region && geo.region !== geo.city) {
parts.push(geo.region);
}
Eif (geo.country_code) {
parts.push(`(${geo.country_code})`);
}
Eif (parts.length > 0) {
kvRows.push(["Location", parts.join(", ")]);
}
}
return mdKvTable(kvRows, "User");
}
/**
* Build replay link section as markdown.
*/
function buildReplayMarkdown(
event: SentryEvent,
issuePermalink?: string
): string {
const replayId = getReplayIdFromEvent(event);
if (!replayId) {
return "";
}
const lines: string[] = [];
lines.push("### Replay");
lines.push("");
lines.push(`**ID:** \`${replayId}\``);
Eif (issuePermalink) {
const match = BASE_URL_REGEX.exec(issuePermalink);
Eif (match?.[1]) {
lines.push(`**Link:** ${match[1]}/explore/replays/${replayId}/`);
}
}
return lines.join("\n");
}
// Event Formatting
/**
* Format event details for display as rendered markdown.
*
* @param event - The Sentry event to format
* @param header - Optional header text (defaults to "Latest Event")
* @param issuePermalink - Optional issue permalink for constructing replay links
* @returns Rendered terminal string
*/
export function formatEventDetails(
event: SentryEvent,
header = "Latest Event",
issuePermalink?: string
): string {
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Event formatting requires multiple conditional sections
return withSerializeSpan("formatEventDetails", () => {
const sections: string[] = [];
sections.push(
`## ${escapeMarkdownInline(header)} (\`${event.eventID.slice(0, 8)}\`)`
);
sections.push("");
// Basic info table
const infoKvRows: [string, string][] = [];
infoKvRows.push(["Event ID", `\`${event.eventID}\``]);
if (event.dateReceived) {
infoKvRows.push([
"Received",
new Date(event.dateReceived).toLocaleString(),
]);
}
if (event.location) {
infoKvRows.push(["Location", safeCodeSpan(event.location)]);
}
const traceCtx = event.contexts?.trace;
if (traceCtx?.trace_id) {
infoKvRows.push(["Trace", safeCodeSpan(traceCtx.trace_id)]);
}
if (event.sdk?.name || event.sdk?.version) {
// Wrap in backtick code span — SDK names like sentry.python.aws_lambda
// contain underscores that markdown would otherwise render as emphasis.
const sdkName = event.sdk.name ?? "unknown";
const sdkVersion = event.sdk.version ?? "";
const sdkInfo = `${sdkName}${sdkVersion ? ` ${sdkVersion}` : ""}`;
infoKvRows.push(["SDK", `\`${sdkInfo}\``]);
}
if (event.release?.shortVersion) {
infoKvRows.push(["Release", String(event.release.shortVersion)]);
}
Eif (infoKvRows.length > 0) {
sections.push(mdKvTable(infoKvRows));
}
// User section
const userSection = buildUserMarkdown(event);
if (userSection) {
sections.push("");
sections.push(userSection);
}
// Environment section
const envSection = buildEnvironmentMarkdown(event);
if (envSection) {
sections.push("");
sections.push(envSection);
}
// HTTP Request section
const requestEntry = extractEntry(event, "request");
if (requestEntry) {
const requestSection = buildRequestMarkdown(requestEntry);
if (requestSection) {
sections.push("");
sections.push(requestSection);
}
}
// Stack Trace
const exceptionEntry = extractEntry(event, "exception");
if (exceptionEntry) {
sections.push("");
sections.push(buildStackTraceMarkdown(exceptionEntry));
}
// Breadcrumbs
const breadcrumbsEntry = extractEntry(event, "breadcrumbs");
if (breadcrumbsEntry) {
const breadcrumbSection = buildBreadcrumbsMarkdown(breadcrumbsEntry);
if (breadcrumbSection) {
sections.push("");
sections.push(breadcrumbSection);
}
}
// Replay link
const replaySection = buildReplayMarkdown(event, issuePermalink);
if (replaySection) {
sections.push("");
sections.push(replaySection);
}
// Tags
if (event.tags?.length) {
sections.push("");
sections.push("### Tags");
sections.push("");
sections.push(mdTableHeader(["Key", "Value"]).trimEnd());
for (const tag of event.tags) {
sections.push(
mdRow([
`\`${tag.key}\``,
escapeMarkdownCell(String(tag.value)),
]).trimEnd()
);
}
}
return renderMarkdown(sections.join("\n"));
});
}
// Organization Formatting
/**
* Format detailed organization information as rendered markdown.
*
* @param org - The Sentry organization to format
* @returns Rendered terminal string
*/
export function formatOrgDetails(org: SentryOrganization): string {
const lines: string[] = [];
lines.push(
`## ${escapeMarkdownInline(org.slug)}: ${escapeMarkdownInline(org.name || "(unnamed)")}`
);
lines.push("");
const kvRows: [string, string][] = [];
kvRows.push(["Slug", `\`${org.slug || "(none)"}\``]);
kvRows.push(["Name", escapeMarkdownInline(org.name || "(unnamed)")]);
kvRows.push(["ID", String(org.id)]);
if (org.dateCreated) {
kvRows.push(["Created", new Date(org.dateCreated).toLocaleString()]);
}
kvRows.push(["2FA", org.require2FA ? "Required" : "Not required"]);
kvRows.push(["Early Adopter", org.isEarlyAdopter ? "Yes" : "No"]);
// orgRole is returned by the detail API but not yet typed in the SDK
const orgRole = (org as Record<string, unknown>).orgRole as
| string
| undefined;
Iif (orgRole) {
kvRows.push(["Your Role", orgRole]);
}
lines.push(mdKvTable(kvRows));
const featuresSection = formatFeaturesMarkdown(org.features);
if (featuresSection) {
lines.push(featuresSection);
}
return renderMarkdown(lines.join("\n"));
}
/**
* Format detailed project information as rendered markdown.
*
* @param project - The Sentry project to format
* @param dsn - Optional DSN string to display
* @returns Rendered terminal string
*/
export function formatProjectDetails(
project: SentryProject,
dsn?: string | null
): string {
const lines: string[] = [];
lines.push(
`## ${escapeMarkdownInline(project.slug)}: ${escapeMarkdownInline(project.name || "(unnamed)")}`
);
lines.push("");
const kvRows: [string, string][] = [];
kvRows.push(["Slug", `\`${project.slug || "(none)"}\``]);
kvRows.push(["Name", escapeMarkdownInline(project.name || "(unnamed)")]);
kvRows.push(["ID", String(project.id)]);
kvRows.push(["Platform", project.platform || "Not set"]);
kvRows.push(["DSN", `\`${dsn || "No DSN available"}\``]);
kvRows.push(["Status", project.status ?? "unknown"]);
Eif (project.dateCreated) {
kvRows.push(["Created", new Date(project.dateCreated).toLocaleString()]);
}
if (project.organization) {
const orgName = resolveOrgDisplayName(
project.organization.slug,
project.organization.name
);
kvRows.push([
"Organization",
`${escapeMarkdownInline(orgName)} (${safeCodeSpan(project.organization.slug)})`,
]);
}
if (project.firstEvent) {
kvRows.push(["First Event", new Date(project.firstEvent).toLocaleString()]);
} else {
kvRows.push(["First Event", "No events yet"]);
}
kvRows.push(["Sessions", project.hasSessions ? "Yes" : "No"]);
kvRows.push(["Replays", project.hasReplays ? "Yes" : "No"]);
kvRows.push(["Profiles", project.hasProfiles ? "Yes" : "No"]);
kvRows.push(["Monitors", project.hasMonitors ? "Yes" : "No"]);
lines.push(mdKvTable(kvRows));
const featuresSection = formatFeaturesMarkdown(project.features);
Iif (featuresSection) {
lines.push(featuresSection);
}
return renderMarkdown(lines.join("\n"));
}
// User Identity Formatting
/**
* User identity fields for display formatting.
* Accepts both UserInfo (userId) and token response user (id) shapes.
*/
type UserIdentityInput = {
/** User ID (from token response) */
id?: string;
/** User ID (from stored UserInfo) */
userId?: string;
email?: string;
username?: string;
/** Display name (different from username) */
name?: string;
};
/**
* Format user identity for display.
* Prefers name over username, handles missing fields gracefully.
*
* @param user - User identity object (supports both id and userId fields)
* @returns Formatted string like "Name <email>" or fallback to available fields
*/
export function formatUserIdentity(user: UserIdentityInput): string {
const { name, username, email, id, userId } = user;
const displayName = name ?? username;
const finalId = id ?? userId;
if (displayName && email) {
return `${displayName} <${email}>`;
}
if (displayName) {
return displayName;
}
if (email) {
return email;
}
// Fallback to user ID if no name/username/email
return `user ${finalId}`;
}
/** Data shape yielded by `whoami` for `sntrys_` org auth tokens. */
export type OrgTokenIdentity = {
type: "org-auth-token";
organization?: string;
url: string;
regionUrl?: string;
};
/**
* Format org-auth-token identity for `sentry auth whoami`.
* Renders "Organization: <slug> (<url>)" or just the URL when slug is unknown.
*/
export function formatOrgTokenIdentity(data: OrgTokenIdentity): string {
const rows: Array<readonly [string, string]> = [];
rows.push(["Token type", "Organization auth token"]);
if (data.organization) {
rows.push(["Organization", data.organization]);
}
rows.push(["Instance", data.url]);
Eif (data.regionUrl) {
rows.push(["Region", data.regionUrl]);
}
return renderMarkdown(mdKvTable(rows));
}
// Token Formatting
/**
* Mask a token for display
*/
export function maskToken(token: string): string {
if (token.length <= 12) {
return "****";
}
return `${token.substring(0, 8)}...${token.substring(token.length - 4)}`;
}
/**
* Format a duration in seconds as a human-readable string.
*
* @param seconds - Duration in seconds
* @returns Human-readable duration (e.g., "5 minutes", "2 hours", "1 hour and 30 minutes")
*/
/** Format a count with its unit, handling singular/plural */
function pluralUnit(count: number, unit: string): string {
return `${count} ${unit}${count !== 1 ? "s" : ""}`;
}
/** Format a major + minor unit pair, omitting minor when zero */
function durationPair(
major: number,
majorUnit: string,
minor: number,
minorUnit: string
): string {
if (minor === 0) {
return pluralUnit(major, majorUnit);
}
return `${pluralUnit(major, majorUnit)} and ${pluralUnit(minor, minorUnit)}`;
}
export function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60);
if (minutes < 60) {
return pluralUnit(minutes, "minute");
}
const hours = Math.floor(minutes / 60);
if (hours < 24) {
return durationPair(hours, "hour", minutes % 60, "minute");
}
const days = Math.floor(hours / 24);
if (days < 7) {
return durationPair(days, "day", hours % 24, "hour");
}
return durationPair(Math.floor(days / 7), "week", days % 7, "day");
}
/**
* Format token expiration info
*/
export function formatExpiration(expiresAt: number): string {
const expiresDate = new Date(expiresAt);
const now = new Date();
if (expiresDate <= now) {
return "Expired";
}
const secondsRemaining = Math.round(
(expiresDate.getTime() - now.getTime()) / 1000
);
return `${expiresDate.toLocaleString()} (${formatDuration(secondsRemaining)} remaining)`;
}
// Feedback Formatting
/** Structured feedback result (imported from the command module) */
type FeedbackResult = import("../../commands/cli/feedback.js").FeedbackResult;
/**
* Format feedback submission result as rendered markdown.
*
* @param data - Structured feedback result from the command
* @returns Rendered terminal string
*/
export function formatFeedbackResult(data: FeedbackResult): string {
if (data.sent) {
return renderMarkdown(
`${colorTag("green", "✓")} Feedback submitted. Thank you!`
);
}
return renderMarkdown(
`${colorTag("yellow", "⚠")} Feedback may not have been sent (network timeout).`
);
}
// Auth Logout Formatting
/** Structured logout result data (imported from the command module) */
type LogoutResult = import("../../commands/auth/logout.js").LogoutResult;
/**
* Format logout result as rendered markdown.
*
* @param data - Structured logout result from the command
* @returns Rendered terminal string
*/
export function formatLogoutResult(data: LogoutResult): string {
if (!data.loggedOut) {
return renderMarkdown(data.message ?? "Not currently authenticated.");
}
const lines: string[] = [];
lines.push(`${colorTag("green", "✓")} Logged out successfully.`);
Eif (data.configPath) {
lines.push(`Credentials removed from: ${safeCodeSpan(data.configPath)}`);
}
return renderMarkdown(lines.join("\n\n"));
}
// Auth Status Formatting
/** Structured auth status data shape (re-imported from the command module) */
type AuthStatusData = import("../../commands/auth/status.js").AuthStatusData;
/**
* Build the markdown header line based on auth source.
*/
function formatAuthHeader(source: string): string {
if (source.startsWith("env:")) {
const varName = source.slice("env:".length);
return `## ${colorTag("green", "✓")} Authenticated via ${escapeMarkdownInline(varName)} environment variable`;
}
return `## ${colorTag("green", "✓")} Authenticated`;
}
/**
* Build the key-value rows for the main auth details section.
*/
function buildAuthDetailRows(data: AuthStatusData): [string, string][] {
const rows: [string, string][] = [];
const isEnv = data.source.startsWith("env:");
if (data.configPath) {
rows.push(["Config", safeCodeSpan(data.configPath)]);
}
if (data.user) {
rows.push(["User", formatUserIdentity(data.user)]);
}
Eif (data.token) {
rows.push(["Token", safeCodeSpan(data.token.display)]);
if (data.token.expiresAt) {
rows.push(["Expires", formatExpiration(data.token.expiresAt)]);
}
// Only show auto-refresh for non-env tokens
if (!isEnv) {
rows.push([
"Auto-refresh",
data.token.refreshEnabled ? "enabled" : "disabled (no refresh token)",
]);
}
}
return rows;
}
/**
* Build the defaults section markdown (heading + kv table).
* Returns empty string when no defaults are set.
*/
function formatDefaultsSection(
defaults: NonNullable<AuthStatusData["defaults"]>
): string {
const rows: [string, string][] = [];
Eif (defaults.organization) {
rows.push(["Organization", safeCodeSpan(defaults.organization)]);
}
Eif (defaults.project) {
rows.push(["Project", safeCodeSpan(defaults.project)]);
}
Iif (rows.length === 0) {
return "";
}
return `\n${mdKvTable(rows, "Defaults")}`;
}
/** Maximum orgs to display in the verification list before truncating */
const MAX_VERIFY_DISPLAY = 5;
/**
* Build the credential verification section markdown.
*/
function formatVerificationSection(
verification: NonNullable<AuthStatusData["verification"]>
): string {
const lines: string[] = [""];
if (verification.success) {
const orgs = verification.organizations ?? [];
lines.push(
`### ${colorTag("green", "✓")} Access verified — ${orgs.length} organization(s)`
);
if (orgs.length > 0) {
lines.push("");
for (const org of orgs.slice(0, MAX_VERIFY_DISPLAY)) {
lines.push(
`- ${escapeMarkdownInline(org.name)} (${safeCodeSpan(org.slug)})`
);
}
Iif (orgs.length > MAX_VERIFY_DISPLAY) {
lines.push(`- *… and ${orgs.length - MAX_VERIFY_DISPLAY} more*`);
}
}
} else {
lines.push(`### ${colorTag("red", "✗")} Could not verify credentials`);
Eif (verification.error) {
lines.push("");
lines.push(escapeMarkdownInline(verification.error));
}
}
return lines.join("\n");
}
/**
* Format auth status data as rendered markdown.
*
* Produces sections for authentication source, user identity, token info,
* defaults, and credential verification. Designed as the `human` formatter
* for the `auth status` command's {@link OutputConfig}.
*
* @param data - Structured auth status data collected by the command
* @returns Rendered terminal string
*/
export function formatAuthStatus(data: AuthStatusData): string {
const lines: string[] = [];
lines.push(formatAuthHeader(data.source));
lines.push("");
const authRows = buildAuthDetailRows(data);
Eif (authRows.length > 0) {
lines.push(mdKvTable(authRows));
}
Eif (data.envToken) {
lines.push(formatEnvTokenSection(data.envToken));
}
if (data.defaults) {
lines.push(formatDefaultsSection(data.defaults));
}
Eif (data.verification) {
lines.push(formatVerificationSection(data.verification));
}
return renderMarkdown(lines.join("\n"));
}
/**
* Format the env token status section.
* Shows whether the env token is active or bypassed, and how many endpoints
* have been marked insufficient.
*/
function formatEnvTokenSection(
envToken: NonNullable<AuthStatusData["envToken"]>
): string {
const status = envToken.active
? "active"
: "set but not used (using OAuth credentials)";
const rows: [string, string][] = [
["Env var", safeCodeSpan(envToken.envVar)],
["Status", status],
];
return `\n${mdKvTable(rows, "Environment Token")}`;
}
// Project Creation Formatting
/** Input for the project-created success formatter */
export type ProjectCreatedResult = {
/** The created project */
project: SentryProject;
/** Organization slug the project was created in */
orgSlug: string;
/** Team slug the project was assigned to */
teamSlug: string;
/** How the team was resolved */
teamSource: "explicit" | "auto-selected" | "auto-created";
/** The platform the user requested via CLI argument (used as fallback display) */
requestedPlatform: string;
/** Primary DSN, if fetched successfully */
dsn: string | null;
/** Sentry web URL for the project settings page */
url: string;
/** Whether Sentry assigned a different slug than expected */
slugDiverged: boolean;
/** The slug the user expected (derived from the project name) */
expectedSlug: string;
/** When true, nothing was actually created — output uses tentative wording */
dryRun?: boolean;
};
/**
* Format a successful project creation as rendered markdown.
*
* Includes a heading, contextual notes (slug divergence, team auto-selection),
* a key-value detail table, and a tip footer.
*
* @param result - Project creation context
* @returns Rendered terminal string
*/
export function formatProjectCreated(result: ProjectCreatedResult): string {
const lines: string[] = [];
const dry = result.dryRun === true;
const nameEsc = escapeMarkdownInline(result.project.name);
const orgEsc = escapeMarkdownInline(result.orgSlug);
// Heading
if (dry) {
lines.push(`## <muted>Dry run</muted> — project '${nameEsc}' in ${orgEsc}`);
} else {
lines.push(`## Created project '${nameEsc}' in ${orgEsc}`);
}
lines.push("");
// Slug divergence note (never applies in dry-run — we can't predict server renames)
if (result.slugDiverged) {
lines.push(
`> **Note:** Slug \`${result.project.slug}\` was assigned because \`${result.expectedSlug}\` is already taken.`
);
lines.push("");
}
// Team source notes — tentative wording in dry-run
if (result.teamSource === "auto-created") {
lines.push(
dry
? `> **Note:** Would create team '${escapeMarkdownInline(result.teamSlug)}' (org has no teams).`
: `> **Note:** Created team '${escapeMarkdownInline(result.teamSlug)}' (org had no teams).`
);
lines.push("");
} else if (result.teamSource === "auto-selected") {
lines.push(
dry
? `> **Note:** Would use team '${escapeMarkdownInline(result.teamSlug)}'. See all teams: \`sentry team list\``
: `> **Note:** Using team '${escapeMarkdownInline(result.teamSlug)}'. See all teams: \`sentry team list\``
);
lines.push("");
}
const kvRows: [string, string][] = [
["Project", nameEsc],
["Slug", safeCodeSpan(result.project.slug)],
["Org", safeCodeSpan(result.orgSlug)],
["Team", safeCodeSpan(result.teamSlug)],
["Platform", result.project.platform || result.requestedPlatform],
];
if (result.dsn) {
kvRows.push(["DSN", safeCodeSpan(result.dsn)]);
}
if (result.url) {
kvRows.push(["URL", result.url]);
}
lines.push(mdKvTable(kvRows));
// Tip footer — only when a real project exists to view
if (!dry) {
lines.push("");
lines.push(
`*Tip: Use \`sentry project view ${result.orgSlug}/${result.project.slug}\` for details*`
);
}
return renderMarkdown(lines.join("\n"));
}
// Project Deletion Formatting
/**
* Result of a project deletion (or dry-run).
*
* Contains the minimum context needed for both human and JSON output.
* When `dryRun` is true, no deletion occurred — output uses tentative wording.
*/
export type ProjectDeleteResult = {
/** Organization slug */
orgSlug: string;
/** Project slug */
projectSlug: string;
/** Human-readable project name */
projectName: string;
/** Sentry web URL for the project */
url: string;
/** When true, nothing was actually deleted — output uses tentative wording */
dryRun?: boolean;
};
/**
* Format a project deletion result as rendered markdown.
*
* @param result - Deletion context
* @returns Rendered terminal string
*/
export function formatProjectDeleted(result: ProjectDeleteResult): string {
const nameEsc = escapeMarkdownInline(result.projectName);
const qualifiedSlug = `${result.orgSlug}/${result.projectSlug}`;
if (result.dryRun) {
return renderMarkdown(
`Would delete project '${nameEsc}' (${safeCodeSpan(qualifiedSlug)}).\n\n` +
`URL: ${result.url}`
);
}
return renderMarkdown(
`Deleted project '${nameEsc}' (${safeCodeSpan(qualifiedSlug)}).`
);
}
// CLI Fix Formatting
/** Structured fix result (imported from the command module) */
type FixResult = import("../../commands/cli/fix.js").FixResult;
/** Structured fix issue (imported from the command module) */
type FixIssue = import("../../commands/cli/fix.js").FixIssue;
/** Status marker for a fix issue bullet point */
function issueMarker(issue: FixIssue): string {
if (issue.repaired === true) {
return colorTag("green", "✓");
}
if (issue.repaired === false) {
return colorTag("red", "✗");
}
return "•";
}
/**
* Build a section for a specific issue category.
* Returns empty string if there are no issues in this category.
*/
function formatFixCategory(issues: FixIssue[], heading: string): string {
if (issues.length === 0) {
return "";
}
const lines: string[] = [];
lines.push(`### ${heading}`);
lines.push("");
lines.push(`Found ${issues.length} issue(s):`);
lines.push("");
for (const issue of issues) {
const marker = issueMarker(issue);
const desc = escapeMarkdownInline(issue.description);
if (issue.repairMessage && issue.repaired !== undefined) {
lines.push(`- ${marker} ${escapeMarkdownInline(issue.repairMessage)}`);
} else {
lines.push(`- ${marker} ${desc}`);
}
}
return lines.join("\n");
}
/**
* Format fix command result as rendered markdown.
*
* Produces sections for each issue category (ownership, permissions, schema)
* with status markers for each issue. Designed as the `human` formatter
* for the `cli fix` command's {@link OutputConfig}.
*
* @param data - Structured fix result collected by the command
* @returns Rendered terminal string
*/
export function formatFixResult(data: FixResult): string {
const lines: string[] = [];
// Header
lines.push(`## Database: ${safeCodeSpan(data.dbPath)}`);
lines.push("");
lines.push(`Schema version: ${data.schemaVersion}`);
if (data.dryRun) {
lines.push("");
lines.push(`*${colorTag("muted", "Dry run — no changes will be made")}*`);
}
// Category sections
const ownershipIssues = data.issues.filter((i) => i.category === "ownership");
const permissionIssues = data.issues.filter(
(i) => i.category === "permission"
);
const schemaIssues = data.issues.filter((i) => i.category === "schema");
const ownershipSection = formatFixCategory(ownershipIssues, "Ownership");
const permissionSection = formatFixCategory(permissionIssues, "Permissions");
const schemaSection = formatFixCategory(schemaIssues, "Schema");
if (ownershipSection) {
lines.push("");
lines.push(ownershipSection);
}
if (permissionSection) {
lines.push("");
lines.push(permissionSection);
}
if (schemaSection) {
lines.push("");
lines.push(schemaSection);
}
// Instructions block (manual steps when automatic repair isn't possible)
if (data.instructions) {
lines.push("");
lines.push("---");
lines.push("");
lines.push(escapeMarkdownInline(data.instructions));
}
// Summary
lines.push("");
if (data.issues.length === 0 && !data.repairFailed) {
lines.push(
`${colorTag("green", "✓")} No issues found. Database schema and permissions are correct.`
);
} else if (data.dryRun && data.issues.length > 0 && !data.repairFailed) {
lines.push("Run `sentry cli fix` to apply fixes.");
} else if (!data.repairFailed) {
lines.push(`${colorTag("green", "✓")} All issues repaired successfully.`);
}
return renderMarkdown(lines.join("\n"));
}
// CLI Upgrade Formatting
/** Structured upgrade result (imported from the command module) */
type UpgradeResult = import("../../commands/cli/upgrade.js").UpgradeResult;
/** Category → markdown heading for changelog sections */
type ChangeCategory = import("../release-notes.js").ChangeCategory;
/** Heading text for each changelog category */
const CATEGORY_HEADINGS: Record<ChangeCategory, string> = {
features: "#### New Features ✨",
fixes: "#### Bug Fixes 🐛",
performance: "#### Performance ⚡",
};
/**
* Max terminal height multiplier for changelog clamping.
*
* When the total rendered changelog would exceed this fraction of the
* terminal height, items are truncated to keep output scannable.
*/
const CHANGELOG_HEIGHT_FACTOR = 1.3;
/** Lines consumed by the upgrade status header/metadata above the changelog */
const CHANGELOG_HEADER_OVERHEAD = 6;
/** Minimum rendered changelog lines to show even on tiny terminals */
const MIN_CHANGELOG_LINES = 5;
/** Default max rendered lines for non-TTY output (no terminal height available) */
const DEFAULT_MAX_CHANGELOG_LINES = 30;
/**
* Compute the maximum number of changelog lines based on terminal height.
*
* Uses ~1.3x the terminal height minus header overhead. Returns a generous
* default for non-TTY output where terminal height is unknown.
*/
function getMaxChangelogLines(): number {
// process.stdout.rows is allowed in formatters (not in command files)
const termHeight = process.stdout.rows;
Eif (!termHeight) {
return DEFAULT_MAX_CHANGELOG_LINES;
}
return Math.max(
MIN_CHANGELOG_LINES,
Math.floor(termHeight * CHANGELOG_HEIGHT_FACTOR) - CHANGELOG_HEADER_OVERHEAD
);
}
/**
* Format the changelog section as markdown for rendering.
*
* Re-serializes the filtered section markdown with category headings so
* that `renderMarkdown()` applies consistent heading/list styling.
* Clamps the rendered output to fit ~1.3x the terminal height.
*
* @param data - Upgrade result with changelog
* @returns Rendered changelog string, or empty string if no changelog
*/
function formatChangelog(data: UpgradeResult): string {
if (!data.changelog || data.changelog.sections.length === 0) {
return "";
}
const { changelog } = data;
const lines: string[] = [""];
for (const section of changelog.sections) {
lines.push(CATEGORY_HEADINGS[section.category]);
lines.push(section.markdown);
}
Iif (changelog.truncated) {
const more = changelog.originalCount - changelog.totalItems;
lines.push(
`<muted>...and ${more} more changes — https://github.com/getsentry/cli/releases</muted>`
);
}
// Render through the markdown pipeline, then clamp to terminal height
const rendered = renderMarkdown(lines.join("\n"));
const renderedLines = rendered.split("\n");
const maxLines = getMaxChangelogLines();
Eif (renderedLines.length <= maxLines) {
return rendered;
}
// Truncate and add a "more" indicator
const clamped = renderedLines.slice(0, maxLines);
const remaining = changelog.originalCount - changelog.totalItems;
const moreText =
remaining > 0
? "...and more — https://github.com/getsentry/cli/releases"
: "...truncated — https://github.com/getsentry/cli/releases";
clamped.push(isPlainOutput() ? moreText : muted(moreText));
return clamped.join("\n");
}
/** Action descriptions for human-readable output */
const ACTION_DESCRIPTIONS: Record<UpgradeResult["action"], string> = {
upgraded: "Upgraded",
downgraded: "Downgraded",
"up-to-date": "Already up to date",
checked: "Update check complete",
};
/**
* Format upgrade result as rendered markdown.
*
* Produces a concise summary: action line, compact metadata, and any
* warnings (e.g., PATH shadowing from old package manager install).
* Designed as the `human` formatter for the `cli upgrade` command's
* {@link OutputConfig}.
*
* @param data - Structured upgrade result collected by the command
* @returns Rendered terminal string
*/
export function formatUpgradeResult(data: UpgradeResult): string {
const lines: string[] = [];
switch (data.action) {
case "upgraded":
case "downgraded": {
const verb = ACTION_DESCRIPTIONS[data.action];
if (data.offline) {
lines.push(
`${colorTag("green", "✓")} ${verb} to ${safeCodeSpan(data.targetVersion)}${escapeMarkdownInline(" (offline, from cache)")}`
);
} else if (data.currentVersion !== data.targetVersion) {
lines.push(
`${colorTag("green", "✓")} ${verb} to ${safeCodeSpan(data.targetVersion)} ${escapeMarkdownInline(`(from ${data.currentVersion})`)}`
);
} else {
lines.push(
`${colorTag("green", "✓")} ${verb} to ${safeCodeSpan(data.targetVersion)}`
);
}
break;
}
case "up-to-date":
lines.push(
`${colorTag("green", "✓")} Already up to date (${safeCodeSpan(data.currentVersion)})`
);
break;
case "checked": {
if (data.currentVersion === data.targetVersion) {
lines.push(
`${colorTag("green", "✓")} You are already on the target version (${safeCodeSpan(data.currentVersion)})`
);
} else {
lines.push(
`Latest: ${safeCodeSpan(data.targetVersion)} (current: ${safeCodeSpan(data.currentVersion)})`
);
}
break;
}
default: {
// Exhaustive check — all action types should be handled above
const _: never = data.action;
lines.push(
`${ACTION_DESCRIPTIONS[_ as UpgradeResult["action"]] ?? "Done"}`
);
}
}
// Compact metadata line instead of a full table — method and channel
// are lightweight diagnostics that don't warrant box-drawing borders.
const meta = `Method: ${data.method} · Channel: ${data.channel}`;
lines.push(` ${colorTag("muted", escapeMarkdownInline(meta))}`);
// Append warnings with ⚠ markers
if (data.warnings && data.warnings.length > 0) {
for (const warning of data.warnings) {
lines.push(`${colorTag("yellow", "⚠")} ${escapeMarkdownInline(warning)}`);
}
}
const result = renderMarkdown(lines.join("\n"));
// Append changelog if available
const changelogOutput = formatChangelog(data);
if (changelogOutput) {
return `${result}\n\n${changelogOutput}\n`;
}
return result;
}
// Dashboard formatters
/**
* Format a created dashboard for human-readable output.
*/
export function formatDashboardCreated(result: {
id: string;
title: string;
url: string;
}): string {
const lines: string[] = [
`Created dashboard '${escapeMarkdownInline(result.title)}' (ID: ${result.id})`,
"",
`URL: ${result.url}`,
];
return renderMarkdown(lines.join("\n"));
}
/**
* Format a widget add result for human-readable output.
*/
export function formatWidgetAdded(result: {
dashboard: DashboardDetail;
widget: DashboardWidget;
url: string;
}): string {
const widgetCount = result.dashboard.widgets?.length ?? 0;
const lines: string[] = [
`Added widget '${escapeMarkdownInline(result.widget.title)}' to dashboard (now ${widgetCount} widgets)`,
];
const layoutLine = formatWidgetLayoutLine(result.widget);
Eif (layoutLine) {
lines.push("", layoutLine);
}
lines.push("", `URL: ${result.url}`);
return renderMarkdown(lines.join("\n"));
}
/**
* Format a widget deletion result for human-readable output.
* Supports dry-run mode — shows what would be removed without removing it.
*/
export function formatWidgetDeleted(result: {
dashboard: DashboardDetail;
widgetTitle: string;
url: string;
dryRun?: boolean;
}): string {
const widgetCount = result.dashboard.widgets?.length ?? 0;
Iif (result.dryRun) {
const lines: string[] = [
`Would remove widget '${escapeMarkdownInline(result.widgetTitle)}' from dashboard (currently ${widgetCount} widgets)`,
"",
`URL: ${result.url}`,
];
return renderMarkdown(lines.join("\n"));
}
const lines: string[] = [
`Removed widget '${escapeMarkdownInline(result.widgetTitle)}' from dashboard (now ${widgetCount} widgets)`,
"",
`URL: ${result.url}`,
];
return renderMarkdown(lines.join("\n"));
}
/**
* Format widget layout as a compact "position (x,y) size w×h" string.
* Returns empty string if the widget has no layout.
*/
function formatWidgetLayoutLine(widget: DashboardWidget): string {
Iif (!widget.layout) {
return "";
}
const { x, y, w, h } = widget.layout;
return `Layout: position (${x},${y}), size ${w}×${h}`;
}
/**
* Format a widget edit result for human-readable output.
*/
export function formatWidgetEdited(result: {
dashboard: DashboardDetail;
widget: DashboardWidget;
url: string;
}): string {
const lines: string[] = [
`Updated widget '${escapeMarkdownInline(result.widget.title)}' in dashboard ${result.dashboard.id}`,
];
const layoutLine = formatWidgetLayoutLine(result.widget);
Eif (layoutLine) {
lines.push("", layoutLine);
}
lines.push("", `URL: ${result.url}`);
return renderMarkdown(lines.join("\n"));
}
// ---------------------------------------------------------------------------
// CLI Defaults Formatting
// ---------------------------------------------------------------------------
/** Structured defaults command result (imported from the command module) */
type DefaultsResult = import("../../commands/cli/defaults.js").DefaultsResult;
/** Display labels for each default key */
const DEFAULT_LABELS: Record<string, string> = {
organization: "Organization",
project: "Project",
telemetry: "Telemetry",
url: "URL",
headers: "Headers",
"ca-cert": "CA Certificate",
};
/**
* Describe the effective telemetry source for display.
* Shows when an env var overrides the stored preference.
*/
function telemetryOverrideNote(
effective: DefaultsResult["telemetryEffective"]
): string {
if (!effective?.source.startsWith("env:")) {
return "";
}
const envVar = effective.source.slice("env:".length);
return ` ${colorTag("muted", `(overridden: disabled via ${envVar})`)}`;
}
/** Build the rows for the "show" mode of the defaults command. */
function buildDefaultsShowRows(data: DefaultsResult): [string, string][] {
const d = data.defaults;
const notSet = colorTag("muted", "not set");
const telLabel = d.telemetry ?? "on (default)";
return [
["Organization", d.organization ? safeCodeSpan(d.organization) : notSet],
["Project", d.project ? safeCodeSpan(d.project) : notSet],
[
"Telemetry",
`${escapeMarkdownInline(String(telLabel))}${telemetryOverrideNote(data.telemetryEffective)}`,
],
["URL", d.url ? safeCodeSpan(d.url) : notSet],
["Headers", d.headers ? safeCodeSpan(d.headers) : notSet],
["CA Certificate", d["ca-cert"] ? safeCodeSpan(d["ca-cert"]) : notSet],
];
}
/**
* Format defaults command result as rendered markdown.
*/
export function formatDefaultsResult(data: DefaultsResult): string {
switch (data.action) {
case "show":
return renderMarkdown(mdKvTable(buildDefaultsShowRows(data), "Defaults"));
case "set": {
const label =
DEFAULT_LABELS[data.changed?.key ?? ""] ?? data.changed?.key;
return renderMarkdown(
`${colorTag("green", "✓")} Default ${escapeMarkdownInline(label ?? "setting")} set to ${safeCodeSpan(String(data.changed?.newValue))}`
);
}
case "clear": {
const label =
DEFAULT_LABELS[data.changed?.key ?? ""] ?? data.changed?.key;
return renderMarkdown(
`${colorTag("green", "✓")} Default ${escapeMarkdownInline(label ?? "setting")} cleared`
);
}
case "clear-all":
return renderMarkdown(`${colorTag("green", "✓")} All defaults cleared`);
default:
return "";
}
}
|