All files / src/plugins/dev page-check.ts

40.55% Statements 232/572
33.48% Branches 146/436
34.69% Functions 51/147
41.04% Lines 213/519

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                                                                                                                            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 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       20x       1x           1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           5x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   3x 1x     2x   3x 1x     2x                     63x   2x 63x     1x                       15x   15x 2x   2x 1x 1x 1x       15x 2x         15x 3x 2x       15x           15x 2x 2x       15x 2x 1x       15x 1x 1x       15x 2x 1x 1x 1x       30x 2x   2x 1x 1x 1x       15x 15x   15x                   15x 1x     15x 2x   2x 1x 1x     1x 1x     15x                                                             6x   6x       6x 1x     6x 7x   6x 1x 1x     5x 5x 10x   10x         5x 10x 10x 10x 10x   10x       10x 2x     10x 1x         5x       1x                       3x 1x     2x 2x   2x   1x           2x   2x                       4x 2x   2x     4x 2x   2x 1x     1x   1x           1x                           6x 6x   6x 4x     6x 1x     6x       1x     1x                       1x                 1x   1x       1x   1x                                                                                               11x   11x 2x     11x 1x     11x 23x 3x     7x     12x   4x 1x     4x   5x 1x     12x 1x     4x                                             5x 2x                                               3x 1x                     189x                                                                             1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1x                                                                                                                                                                                                                               1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1x      
/**
 * Checks the real Clay settings page in a headless browser.
 *
 * The specs check each piece of the settings page on its own. This is the one check that builds the
 * whole page the way the phone does, with the face's features started and their page hooks run, and
 * then opens it in Chromium through Playwright. A page hook mistake that every spec misses shows here
 * as a page that throws, a row that never hides, or a save that loses a value.
 *
 * It builds each fixture face under fixtures/ once, then gives each scenario in SCENARIOS its own
 * copy of its face's build with the scenario's defines and providers list, and previews it through
 * clay-preview with the scenario's --plugins and --settings files. The providers list goes through
 * the build's own check, so a scenario the build would refuse stops before its page is built. Each
 * page fails on:
 *
 *   - any uncaught error, console.error, or dialog, which on a phone is a settings screen that never
 *     opens or a plugin's name running as code
 *   - Clay leaving any row of the page undrawn
 *   - a location search drawn without the look of Clay's text box, or a theme picker drawn without
 *     the look of Clay's select
 *   - the framework's row rules missing or there twice, Clay's base sheet not found, the rules moving
 *     a row's padding in the usual order, or a row sitting differently on a page laid out the way the
 *     Pebble Android app leaves it
 *   - a card that shows holding nothing but headings, on load and after each select change
 *   - a row expected to show that is hidden, or the other way round, on load and after each select change
 *   - rows that run down the page in another order than expected, or a text row on the wrong side of one
 *   - a plugin note, found by the note component's class and read by its text, that shows when it
 *     should not, a warning note drawn without its badge, or a calm note drawn with one
 *   - an element the scenario says must not exist, such as an img a plugin's name tried to make, or
 *     one it says must exist that is not there, such as the mark a face's own customClay leaves
 *   - a supported plugins panel that is missing or there twice, that opens by itself or will not open
 *     and close, that lists the wrong kinds or plugins, or whose store links open the wrong listing or
 *     load it inside the page
 *   - a plugin kinds store that is missing, is not the first row Clay builds, or holds another state
 *     for a kind than the scenario expects
 *   - a save whose pebblejs://close# payload lacks a value or holds the wrong one
 *   - a custom function whose text holds a pattern Clay's string replace would read, checked on the
 *     tsc output the phone runs, or that the page does not carry whole
 *
 * npm run check:pages runs every scenario from the framework repo's root, and naming scenarios after
 * it runs just those. It needs Playwright's Chromium, which the frame plugin installs, so it stays out
 * of npm test. It is offline and waits only for the page to load and answer.
 *
 * The pages and their builds land in build/page-check/ beside this file, so a failing page can be
 * opened in a browser.
 */
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import type { Browser, Page } from 'playwright';
import { cleanEmit, compile, facePaths, writeTsconfig, type FacePaths, type FacePlace } from '../../tools/pkjs/build-pkjs.ts';
import { checkMessageKeys } from '../../tools/manifest/build-manifests.ts';
import { NO_START, fillAppinfo } from '../../tools/manifest/feature-keys.ts';
import { readProviders } from '../../tools/manifest/providers.ts';
import { ENGINE } from '../../tools/shared/paths.ts';
import { stubModuleLoad } from '../../ts/testing/module-load.ts';
import { ToolError, reportFailure } from '../../tools/shared/tool-error.ts';
import { isMainScript } from '../../tools/shared/entry.ts';
import { forgetCompiled, installHost, messageKeysOf, startFacts } from '../../tools/pkjs/settings-page.ts';
import { fillPreviewEmit, readPluginsFile, renderPage, hasPluginDefines } from './clay-preview.ts';
import { CLAY_ROW_PADDING } from '../../ts/clay/page-style-component.ts';
 
/** The folder holding the fixture faces, the plugins files, and the settings files. */
export const FIXTURES = path.join(import.meta.dirname, 'fixtures');
 
/** The fixture face a scenario previews unless it names another. */
export const FIXTURE_FACE = path.join(FIXTURES, 'face');
 
/** The --plugins files the scenarios name. */
export const PLUGIN_FILES = path.join(import.meta.dirname, 'fixtures', 'plugins');
 
/** The --settings files the scenarios name, each a returning wearer's saved values. */
export const SETTINGS_FILES = path.join(import.meta.dirname, 'fixtures', 'settings');
 
/** Where the builds and the pages go. */
const OUT_DIR = path.join(import.meta.dirname, 'build', 'page-check');
 
/** The fixture face's name, which the preview and the key check use. */
const FACE = 'page-check';
 
/** How long the page gets to load, answer, or navigate, in milliseconds. */
const PAGE_WAIT_MS = 10_000;
 
/** What a page has to show at one moment, by message key and by the words of a text or heading row. */
export interface Expectation {
  /** Rows, by message key, that have to show. */
  visible?: string[];
  /** Rows, by message key, that must not show. A row that is not on the page counts as not showing. */
  hidden?: string[];
  /** Text or heading rows, by their exact words. Every one listed has to show. */
  textsVisible?: string[];
  /** Text or heading rows, by their exact words, none of which may show. */
  textsHidden?: string[];
  /** Notes the pluginNote component draws, by their exact words as text. Every one listed has to show. */
  notesVisible?: string[];
  /** Notes, by their exact words, none of which may show. */
  notesHidden?: string[];
  /** Notes, by their exact words, that have to show with the warning's "!" badge. */
  badged?: string[];
  /** Notes, by their exact words, that have to show without the badge, in the calmer info look. */
  unbadged?: string[];
  /** Text rows, by their exact words, that have to sit above a row, by message key. */
  textsAbove?: Array<{ text: string; key: string }>;
  /** Text rows, by their exact words, that have to sit below a row, by message key. */
  textsBelow?: Array<{ text: string; key: string }>;
  /** Selects, by message key, and the option values each has to offer or leave out. */
  options?: Array<{ key: string; has?: string[]; lacks?: string[] }>;
  /** Rows, by message key, in the order they have to run down the page. Each has to be on the page. */
  order?: string[];
  /** Controls, by message key, and the value each has to hold, as Clay reads it, such as an API key row's key. */
  values?: Record<string, string>;
}
 
/** A select the wearer changes, or a text row the wearer types into, and what the page has to show after it. */
export interface Change extends Expectation {
  /** The control's message key, a select or a text input. */
  key: string;
  /** The option value picked, or the text typed. */
  value: string;
}
 
/** One plugin the supported plugins panel has to list. */
export interface PanelPlugin {
  /** Its name as the wearer reads it. */
  name: string;
  /** The word after its name, such as `Installed`. Left out, none. */
  tag?: string;
  /** Its store listing's address, for a store plugin. With `openUrl` its name has to link there. */
  listing?: string;
}
 
/** What the supported plugins panel has to list once it is opened. */
export interface PanelExpectation {
  /** Each kind's heading and the plugins under it, in the order they run down the panel. */
  kinds: Array<{ label: string; plugins: PanelPlugin[] }>;
  /** Whether the panel opens on the line saying to turn plugins on. */
  off: boolean;
}
 
/** One page to check: how the face is built, what the phone has, and what the page does. */
export interface Scenario {
  /** A short name, which the output and the build folder use. */
  name: string;
  /** The fixture face under fixtures/ the page comes from, `face` when left out. */
  face?: string;
  /** The face's defines for this build, such as `{ PLUGIN_WEATHER: 1 }`. */
  defines: Record<string, number>;
  /**
   * The providers list the face's appinfo holds for this build, such as `{ weather: ['plugin'] }`.
   * The build writes it into the phone bundle, so the page is narrowed to it and the features read it.
   * Left out, the face lists none.
   */
  providers?: Record<string, string[]>;
  /** The --plugins file in fixtures/plugins, or null for a phone that lists no plugins. */
  plugins: string | null;
  /**
   * The --settings file in fixtures/settings, for a returning wearer, such as `plugin-picked.json`
   * holding `{ "WEATHER_PROVIDER": "plugin" }`. Left out, a fresh install.
   */
  settings?: string;
  /**
   * A file in fixtures/settings holding the API key the phone keeps for each provider, as it sits in
   * localStorage under `pf-provider-keys` after an earlier save. Left out, the phone keeps none.
   */
  providerKeys?: string;
  /**
   * Whether starting the features and running their hooks, as the phone does on every open, must give
   * byte for byte the page the face builds with no features started.
   */
  unchanged?: boolean;
  /** What the page shows once it has loaded. */
  load: Expectation;
  /** Select changes, made in order, and what the page shows after each. */
  changes?: Change[];
  /** CSS selectors no element on the page may match, checked after the changes. */
  absent?: string[];
  /** CSS selectors some element on the page has to match, checked after the changes. */
  present?: string[];
  /**
   * Whether the settings page gets `Pebble.openUrl`, as the Pebble app hands it while plugins are on.
   * The check's stand-in records each address it is asked to open and opens nothing.
   */
  openUrl?: boolean;
  /** What the supported plugins panel lists, checked once on load by opening and closing it. */
  panel?: PanelExpectation;
  /**
   * Each kind's state in the plugin kinds store, read the way a face's component reads it, such as
   * `{ music: 'off', phone: 'off' }`. The store also has to be the first row Clay builds. Left out,
   * the store is not checked.
   */
  pluginKinds?: Record<string, string>;
  /**
   * Whether the page opens laid out the way the Pebble Android app leaves it while plugins are on,
   * with a head of its own ahead of the page's, so every component's style lands ahead of Clay's base
   * sheet. The phone's plugins list has nothing to do with it, since the app does this on any face.
   */
  androidHead?: boolean;
  /** The values the save has to carry, by message key, after the changes. With neither this nor saveNot, nothing is saved. */
  save?: Record<string, unknown>;
  /** Values the save must not carry, by message key, checked on the same save. */
  saveNot?: Record<string, unknown[]>;
}
 
// the location rows, which the location section marks to hide while the weather comes from a plugin
const LOCATION_MARKED = ['LOCATION_USE_GPS', 'LOCATION_GPS_FALLBACK', 'LOCATION_NAME'];
 
// the unit row, which the weather section marks to hide while the weather comes in the plugin's units
const UNIT_MARKED = ['WEATHER_TEMPERATURE_UNIT'];
 
// the rows the location and weather sections mark to hide while the weather comes from a plugin. the
// key row also hides for a provider that needs no key, such as Open-Meteo
const WEATHER_MARKED = ['WEATHER_API_KEY', ...UNIT_MARKED, ...LOCATION_MARKED];
 
// rows the weather hook never hides, which every weather scenario on the fixture face expects on the page
const ALWAYS_SHOWN = ['WEATHER_PROVIDER', 'CALENDAR_ICS_URL', 'CALENDAR_POLL'];
 
// what shows while Open-Meteo is picked on the fixture face, every row but the key row
const OPEN_METEO_ROWS = { visible: [...ALWAYS_SHOWN, ...UNIT_MARKED, ...LOCATION_MARKED], hidden: ['WEATHER_API_KEY'] };
 
// the builder's lead line, the select's own lead line above it, which stays showing while the plugin
// is picked so the select never moves under the wearer's finger
const LEAD_LINE = 'Choose where your watch pulls its weather data. Open-Meteo works right out of the box with no setup required.';
 
// the order the builder lays its rows in, and the order the weather hook puts them in while a plugin
// choice is on offer. the select comes first in its section with the key row it hides under it and
// the unit after, and the location section moves below
const BUILDER_ORDER = ['LOCATION_USE_GPS', 'WEATHER_TEMPERATURE_UNIT', 'WEATHER_PROVIDER', 'WEATHER_API_KEY'];
const SELECT_FIRST = ['WEATHER_PROVIDER', 'WEATHER_API_KEY', 'WEATHER_TEMPERATURE_UNIT', 'LOCATION_USE_GPS'];
 
// the page and the save on a phone with no plugin to offer, which plugins off and an older Pebble app
// both are. with no plugin choice only the key row hides, for Open-Meteo, so the sections keep the
// order the face gave them
const NO_PLUGIN_PAGE = {
  load: {
    ...OPEN_METEO_ROWS,
    textsVisible: ['Location Settings', LEAD_LINE],
    options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm', 'weatherapi'], lacks: ['plugin'] }],
    order: BUILDER_ORDER,
  },
  save: { WEATHER_PROVIDER: 'openmeteo' },
};
 
// options found by their value, which show whether a provider select is on the page and what it offers
const DATA_SOURCE_OPTION = 'option[value="openmeteo"]';
const OWM_OPTION = 'option[value="owm"]';
const FINNHUB_OPTION = 'option[value="finnhub"]';
const ICAL_OPTION = 'option[value="ical"]';
 
// the stock fixture's lead line, which carries no mark and stays whatever the providers list says
const STOCK_LEAD = 'Pick where your quotes come from.';
 
// the one-source fixture's line shown only for Open-Meteo, which no option on its select offers
const OPEN_METEO_LINE = 'Open-Meteo needs no key, so this face asks for none.';
 
// the weather feature's own words for its rows, from WEATHER_TEXTS in ts/plugin-sources/weather.ts
// and PLUGINS_OFF_TEXT in ts/plugin-sources/page.ts. the check runs under plain node, which cannot
// load those files, so they are copied here and the spec beside this file checks the copies match
export const NOT_STANDARD_TEXT = '<img src=x onerror=alert(1)> sends weather this face cannot read. Pick another weather plugin under Preferred Sources in the Pebble app, or another data source here.';
 
// a plugin name holding the dollar sign patterns Clay's plain string replace reads, and the
// not-standard note it gets
export const DOLLAR_NAME = 'Rain$\'Check $$SETTINGS$$';
export const DOLLAR_NOT_STANDARD_TEXT = 'Rain$\'Check $$SETTINGS$$ sends weather this face cannot read. Pick another weather plugin under Preferred Sources in the Pebble app, or another data source here.';
export const PERMISSION_TEXT = 'This face needs Location to read the Pebble app\'s weather. Allow it for this face in the Pebble app.';
export const SOURCE_TEXT = 'Your watch shows the weather for the first location in the Pebble app\'s weather settings.';
export const COORDS_TEXT = 'The coordinates show only from a weather plugin that serves them.';
export const PLUGINS_OFF_TEXT = 'The Pebble app is not offering this source right now. Turn on plugins in the Pebble app under Settings, Plugins, or update the Pebble app.';
 
// the supported plugins panel's own words, from ts/plugin-sources/panel.ts, copied for the same
// reason and checked by the same spec
export const PANEL_TITLE = 'Plugins This Face Supports';
export const PANEL_OFF_TEXT = 'The Pebble app is not offering any plugins right now. Turn on plugins in the Pebble app under Settings, Plugins, or update the Pebble app.';
export const BUILT_IN_TAG = 'Built Into the Pebble App';
export const INSTALLED_TAG = 'Installed';
export const OFF_TAG = 'Off';
 
// the store listings of the plugins the panel knows, from src/known-plugins.json
export const MET_NORWAY_LISTING = 'https://apps.repebble.com/met-norway-weather_6972cb1f33e343d69e5b788e';
export const WEATHER_PLUS_LISTING = 'https://apps.repebble.com/weather_48e0d519c06b49e284612dc5';
export const WEATHER_ENHANCED_LISTING = 'https://apps.repebble.com/weather-enhanced_f62c8e74dd3c4157abf09a49';
export const PEBBLE_STOCKS_LISTING = 'https://apps.repebble.com/stocks_730a1d95229d42e9b66098cb';
export const STOCKS_CRYPTO_LISTING = 'https://apps.repebble.com/stocks-crypto_aabbca2fe4f441deb2b5ace7';
export const CALENDAR_ICAL_LISTING = 'https://apps.repebble.com/calendar-ical_22c2e12ca01244bfac7e2660';
 
// the panel's weather plugins on a phone that lists the built-in ones, and its calendar plugins
const PANEL_WEATHER = { label: 'Weather', plugins: [{ name: 'Weather', tag: BUILT_IN_TAG }, { name: 'MET Norway Weather', tag: 'v1.0.5', listing: MET_NORWAY_LISTING }, { name: 'Weather+', tag: 'v1.0.0', listing: WEATHER_PLUS_LISTING }, { name: 'Weather Enhanced', tag: 'v1.0.0', listing: WEATHER_ENHANCED_LISTING }] };
const PANEL_CALENDAR = { label: 'Calendar', plugins: [{ name: 'Calendar', tag: BUILT_IN_TAG }, { name: 'Calendar Enhanced + iCal', tag: 'v1.1.0', listing: CALENDAR_ICAL_LISTING }] };
 
// the same on a phone whose list leaves the built-in ones out, which the panel marks off
const BUILT_IN_OFF = `${BUILT_IN_TAG}, ${OFF_TAG}`;
const PANEL_WEATHER_OFF = { label: 'Weather', plugins: [{ name: 'Weather', tag: BUILT_IN_OFF }, { name: 'MET Norway Weather', tag: 'v1.0.5', listing: MET_NORWAY_LISTING }, { name: 'Weather+', tag: 'v1.0.0', listing: WEATHER_PLUS_LISTING }, { name: 'Weather Enhanced', tag: 'v1.0.0', listing: WEATHER_ENHANCED_LISTING }] };
const PANEL_CALENDAR_OFF = { label: 'Calendar', plugins: [{ name: 'Calendar', tag: BUILT_IN_OFF }, { name: 'Calendar Enhanced + iCal', tag: 'v1.1.0', listing: CALENDAR_ICAL_LISTING }] };
 
// what marks the supported plugins panel on the page
const PANEL_SELECTOR = '.pf-plugins';
 
// the class of the plugin kinds row holding each kind's state, from PLUGIN_KINDS_CLASS in
// ts/plugin-sources/kinds-component.ts, copied for the same reason as the words below and checked by the same spec
export const PLUGIN_KINDS_CLASS = 'pf-plugin-kinds';
 
// the mark the custom-clay fixture face's own customClay leaves on the page once Clay has built it,
// saying the framework's show and hide had already hidden the weather key row when it ran
export const FACE_CODE_MARK = 'body[data-face-page-code="after"]';
 
// the calendar feature's own words for its rows, from CALENDAR_TEXTS in ts/plugin-sources/calendar.ts,
// copied for the same reason and checked by the same spec
export const CALENDAR_NOT_STANDARD_TEXT = 'Odd Calendar sends events this face cannot read. Pick another calendar plugin under Preferred Sources in the Pebble app, or use an iCal link here.';
export const CALENDAR_PERMISSION_TEXT = 'This face needs Calendar to read the Pebble app\'s events. Allow it for this face in the Pebble app.';
export const CALENDAR_EMPTY_TEXT = 'If events are missing, the Pebble app may need permission to read your phone\'s calendars, or those calendars may be switched off in the Pebble app\'s calendar settings.';
export const CALENDAR_SOURCE_TEXT = 'Your watch shows the events from the calendars on your phone, the ones switched on in the Pebble app\'s calendar settings.';
 
// the fixture's calendar section, laid out as a face with calendar controls of its own builds it.
// its lead line has no mark and stays above the select. the iCal sentence, the link, and the refresh
// interval are marked, and hide while the events come from a plugin
const CALENDAR_LEAD = 'Add a Calendar panel to your layout to see your next events.';
const ICAL_LINE = 'Paste your private iCal link below.';
const CALENDAR_MARKED = ['CALENDAR_ICS_URL', 'CALENDAR_POLL'];
 
// where the calendar hook puts its select, under the section's heading and lead line and above the
// rows it hides
const SELECT_PLACE = { textsAbove: [{ text: CALENDAR_LEAD, key: 'CALENDAR_SOURCE' }], textsBelow: [{ text: ICAL_LINE, key: 'CALENDAR_SOURCE' }], order: ['CALENDAR_SOURCE', 'CALENDAR_ICS_URL', 'CALENDAR_POLL'] };
 
// the now playing and phone battery notes, from MUSIC_TEXTS in ts/plugin-sources/music.ts and
// PHONE_TEXTS in ts/plugin-sources/phone.ts, copied for the same reason and checked by the same spec
export const MUSIC_NO_PLUGIN_TEXT = 'Now playing needs a music plugin. The Pebble app has one built in on Android. Turn on plugins in the Pebble app under Settings, Plugins, or update the Pebble app.';
export const MUSIC_PERMISSION_TEXT = 'This face needs Music to show what your phone is playing. Allow it for this face in the Pebble app.';
export const MUSIC_NOT_STANDARD_TEXT = 'Odd Music sends music this face cannot read. Pick another music plugin under Preferred Sources in the Pebble app.';
export const PHONE_NO_PLUGIN_TEXT = 'Phone battery comes from the Phone plugin built into the Pebble app. Turn on plugins in the Pebble app under Settings, Plugins, or update the Pebble app.';
 
// the stock notes, from STOCK_TEXTS in ts/plugin-sources/stocks.ts, copied for the same reason and
// checked by the same spec
export const STOCK_SOURCE_TEXT = 'Your watch shows the first 4 tickers your stock plugin sends, the ones set up in that plugin\'s own settings in the Pebble app.';
export const STOCK_NO_PLUGIN_TEXT = 'This face needs a stock plugin, and the Pebble app has none built in. Get one from the Pebble app store, such as those listed under Plugins This Face Supports, then pick it under Preferred Sources in the Pebble app.';
 
// the panel's stock plugins on a phone that lists the stock fixture plugin
const PANEL_STOCKS = { label: 'Stocks', plugins: [{ name: 'Stocks', tag: 'v1.0.4', listing: PEBBLE_STOCKS_LISTING }, { name: 'Stocks + Crypto', tag: 'v1.0.1', listing: STOCKS_CRYPTO_LISTING }, { name: 'My Stocks', tag: 'Installed' }] };
 
// where the Pebble app's music plugin runs, from the plugin directory in ts/plugin-sources/directory.ts
export const ANDROID_ONLY = 'Android Only';
 
// the panel's now playing and phone battery plugins on an Android phone that lists the built-in ones,
// and the same on a phone whose list leaves them out
const PANEL_MUSIC = { label: 'Now Playing', plugins: [{ name: 'Music', tag: `${BUILT_IN_TAG}, ${ANDROID_ONLY}` }] };
const PANEL_PHONE = { label: 'Phone Battery', plugins: [{ name: 'Phone', tag: BUILT_IN_TAG }] };
const PANEL_MUSIC_OFF = { label: 'Now Playing', plugins: [{ name: 'Music', tag: `${BUILT_IN_TAG}, ${ANDROID_ONLY}, ${OFF_TAG}` }] };
const PANEL_PHONE_OFF = { label: 'Phone Battery', plugins: [{ name: 'Phone', tag: BUILT_IN_OFF }] };
 
// every note the now playing and phone battery hooks can add
const MUSIC_PHONE_NOTES = [MUSIC_NO_PLUGIN_TEXT, MUSIC_PERMISSION_TEXT, MUSIC_NOT_STANDARD_TEXT, PHONE_NO_PLUGIN_TEXT];
 
/** The music and phone notes a scenario expects to show, and every other one hidden. */
function musicPhoneNotes(shown: string[]): Expectation {
  return { notesVisible: shown, badged: shown, notesHidden: MUSIC_PHONE_NOTES.filter((note) => !shown.includes(note)) };
}
 
// the rows of rows-face that carry a key, one of every kind Clay draws in a card that saves a value
const EVERY_ROW = ['ROW_PICK', 'ROW_WORDS', 'ROW_SWITCH', 'ROW_LEVEL', 'ROW_INK', 'ROW_ONE', 'ROW_SOME'];
 
/**
 * Every scenario the check runs, in order. Adding a scenario is adding a row: a plugins file in
 * fixtures/plugins when the phone needs one, and what the page has to show.
 */
export const SCENARIOS: Scenario[] = [
  {
    name: 'no-defines',
    defines: {},
    plugins: null,
    unchanged: true,
    load: {
      ...OPEN_METEO_ROWS,
      textsVisible: ['Location Settings', LEAD_LINE],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm', 'weatherapi'], lacks: ['plugin'] }],
      order: BUILDER_ORDER,
    },
    // the key row shows only for a provider that needs a key
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'owm', visible: [...ALWAYS_SHOWN, ...WEATHER_MARKED] },
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', ...OPEN_METEO_ROWS },
    ],
    absent: [PANEL_SELECTOR],
    save: { WEATHER_PROVIDER: 'openmeteo' },
  },
  {
    // a wearer who saved the plugin on a build that offered it, on a build without the define. the
    // select has no option for the saved value and opens blank, and the key row hides only for a
    // provider known to need no key, so it shows rather than hiding the box a keyed pick needs
    name: 'saved-plugin-no-defines',
    defines: {},
    plugins: null,
    settings: 'plugin-picked.json',
    load: {
      visible: [...ALWAYS_SHOWN, ...WEATHER_MARKED],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm', 'weatherapi'], lacks: ['plugin'] }],
    },
  },
  {
    name: 'built-in-weather',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'built-in.json',
    // a fresh install opens on the plugin, since the feature reads a provider never saved as a plugin
    // that serves the weather. the location section moves below the weather one, so picking the plugin
    // folds rows away under the select rather than above it
    load: {
      visible: ALWAYS_SHOWN,
      hidden: WEATHER_MARKED,
      textsVisible: [LEAD_LINE],
      textsHidden: ['Location Settings'],
      notesVisible: [SOURCE_TEXT],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm', 'weatherapi', 'plugin'] }],
      order: SELECT_FIRST,
    },
    // the key row's own condition for the keyed providers and the plugin's both have to hold, so it
    // shows for OpenWeatherMap and hides again for the plugin
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', ...OPEN_METEO_ROWS, textsVisible: ['Location Settings', LEAD_LINE], notesHidden: [SOURCE_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'owm', visible: [...ALWAYS_SHOWN, ...WEATHER_MARKED], notesHidden: [SOURCE_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', hidden: WEATHER_MARKED, notesVisible: [SOURCE_TEXT] },
    ],
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    name: 'html-name',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'html-name.json',
    load: {
      notesVisible: [NOT_STANDARD_TEXT],
      badged: [NOT_STANDARD_TEXT],
      options: [{ key: 'WEATHER_PROVIDER', has: ['plugin'] }],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', notesHidden: [NOT_STANDARD_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', notesVisible: [NOT_STANDARD_TEXT], badged: [NOT_STANDARD_TEXT] },
    ],
    // the panel lists the plugin by its own name, as text. the phone lists no built-in plugin, so the
    // panel marks it off
    panel: {
      kinds: [{ label: 'Weather', plugins: [...PANEL_WEATHER_OFF.plugins, { name: '<img src=x onerror=alert(1)>', tag: INSTALLED_TAG }] }],
      off: false,
    },
    absent: ['img'],
  },
  {
    // Clay puts the page in with a plain string replace, so a name holding $' or $$ has to reach the
    // page escaped, or the page script breaks and the settings never open. the note and the panel
    // show the name as written, and the page still saves
    name: 'dollar-name',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'dollar-name.json',
    load: {
      notesVisible: [DOLLAR_NOT_STANDARD_TEXT],
      badged: [DOLLAR_NOT_STANDARD_TEXT],
      options: [{ key: 'WEATHER_PROVIDER', has: ['plugin'] }],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', notesHidden: [DOLLAR_NOT_STANDARD_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', notesVisible: [DOLLAR_NOT_STANDARD_TEXT], badged: [DOLLAR_NOT_STANDARD_TEXT] },
    ],
    panel: {
      kinds: [{ label: 'Weather', plugins: [...PANEL_WEATHER_OFF.plugins, { name: DOLLAR_NAME, tag: INSTALLED_TAG }] }],
      off: false,
    },
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    name: 'empty-plugin-list',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'empty.json',
    load: {
      ...OPEN_METEO_ROWS,
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm', 'weatherapi'], lacks: ['plugin'] }],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'owm', visible: [...ALWAYS_SHOWN, ...WEATHER_MARKED], textsVisible: ['Location Settings'] },
    ],
    save: { WEATHER_PROVIDER: 'owm' },
  },
  {
    name: 'permission-denied',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'permission-denied.json',
    load: {
      notesVisible: [PERMISSION_TEXT],
      badged: [PERMISSION_TEXT],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', notesHidden: [PERMISSION_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', notesVisible: [PERMISSION_TEXT], badged: [PERMISSION_TEXT] },
    ],
  },
  {
    name: 'plugins-off',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'plugins-off.json',
    ...NO_PLUGIN_PAGE,
  },
  {
    // a Pebble app from before plugins has no plugin calls at all, and the page opens as it does with
    // plugins off
    name: 'older-app',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'older-app.json',
    ...NO_PLUGIN_PAGE,
  },
  {
    name: 'saved-plugin-plugins-off',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'plugins-off.json',
    settings: 'plugin-picked.json',
    // the saved plugin keeps its option, labelled as plugins off, so the page opens on it and a save
    // keeps it
    load: {
      visible: ALWAYS_SHOWN,
      hidden: WEATHER_MARKED,
      notesVisible: [PLUGINS_OFF_TEXT, SOURCE_TEXT],
      badged: [PLUGINS_OFF_TEXT],
      textsVisible: [LEAD_LINE],
      textsHidden: ['Location Settings'],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm', 'weatherapi', 'plugin'] }],
      order: SELECT_FIRST,
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', ...OPEN_METEO_ROWS, textsVisible: ['Location Settings'], notesHidden: [PLUGINS_OFF_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', hidden: WEATHER_MARKED, notesVisible: [PLUGINS_OFF_TEXT] },
    ],
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    // a weather section laid out the way a family core builds it, whose select carries no mark. the
    // weather hook finds it by its key, and the builder's location rows still hide under it
    name: 'core-select',
    face: 'core-face',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'built-in.json',
    // the select comes up to sit under its heading, ahead of the two unit selects, and the core's
    // unmarked key row, which sat under it, stays next to it. a fresh install opens on the plugin, and
    // the core's key row carries no mark, so it stays as the face wrote it
    load: {
      visible: ['WEATHER_PROVIDER', 'WEATHER_API_KEY'],
      hidden: LOCATION_MARKED,
      notesVisible: [SOURCE_TEXT],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm', 'weatherapi', 'plugin'] }],
      order: ['WEATHER_PROVIDER', 'WEATHER_API_KEY', 'WEATHER_TEMPERATURE_UNIT', 'WEATHER_WIND_UNIT', 'LOCATION_USE_GPS'],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', visible: ['WEATHER_PROVIDER', 'WEATHER_API_KEY', ...WEATHER_MARKED], notesHidden: [SOURCE_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', visible: ['WEATHER_API_KEY'], hidden: LOCATION_MARKED, notesVisible: [SOURCE_TEXT] },
    ],
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    // a face's own select offering one keyed provider. with plugins off it drops to its one option,
    // so the face's key row, shown for keyed providers, shows, and its Open-Meteo line stays hidden
    name: 'one-source-dropped',
    face: 'one-source-face',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'plugins-off.json',
    load: {
      visible: ['WEATHER_API_KEY'],
      hidden: ['WEATHER_PROVIDER'],
      textsHidden: [OPEN_METEO_LINE],
    },
  },
  {
    // the same face with Open-Meteo saved. the feature fetches with the saved provider, so the face's
    // conditions settle against it rather than the one option left, and the key row stays hidden
    name: 'one-source-dropped-saved',
    face: 'one-source-face',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'plugins-off.json',
    settings: 'openmeteo-picked.json',
    load: {
      hidden: ['WEATHER_PROVIDER', 'WEATHER_API_KEY'],
      textsVisible: [OPEN_METEO_LINE],
    },
  },
  {
    // the same face with a plugin on the phone keeps its select and opens on the plugin, and its own
    // key row hides by its own condition while the plugin is picked
    name: 'one-source-with-plugin',
    face: 'one-source-face',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'built-in.json',
    load: {
      visible: ['WEATHER_PROVIDER'],
      hidden: ['WEATHER_API_KEY'],
      textsHidden: [OPEN_METEO_LINE],
      options: [{ key: 'WEATHER_PROVIDER', has: ['owm', 'plugin'] }],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'owm', visible: ['WEATHER_PROVIDER', 'WEATHER_API_KEY'], textsHidden: [OPEN_METEO_LINE] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', hidden: ['WEATHER_API_KEY'], textsHidden: [OPEN_METEO_LINE] },
    ],
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    // a phone whose plugin list cannot be read may still route to a plugin, so a saved plugin keeps
    // the plain choice, with no plugins off note, rather than reading as plugins off
    name: 'plugins-unreadable',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'unreadable.json',
    settings: 'plugin-picked.json',
    load: {
      visible: ALWAYS_SHOWN,
      hidden: WEATHER_MARKED,
      notesVisible: [SOURCE_TEXT],
      notesHidden: [PLUGINS_OFF_TEXT],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm', 'weatherapi', 'plugin'] }],
      order: SELECT_FIRST,
    },
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    // a face listing the plugin alone runs its weather from it whatever is saved, and offers no
    // choice on the page. the Data Source select, its lead line, the key row, the unit row, and the
    // location rows are gone. the page says where the weather comes from, a plugin serves it so no other note
    // shows, and the panel lists the weather plugins
    name: 'plugin-only-weather',
    face: 'plugin-weather-face',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin'] },
    plugins: 'built-in.json',
    openUrl: true,
    load: {
      visible: ['CALENDAR_ICS_URL'],
      hidden: WEATHER_MARKED,
      textsHidden: [LEAD_LINE, 'Location Settings'],
      notesVisible: [SOURCE_TEXT],
      unbadged: [SOURCE_TEXT],
      notesHidden: [PLUGINS_OFF_TEXT],
    },
    absent: [DATA_SOURCE_OPTION],
    panel: { kinds: [PANEL_WEATHER], off: false },
  },
  {
    // the same face with plugins off. the panel opens on the line to turn them on, so the page does
    // not say it a second time, and with nothing serving the weather it says nothing on where it comes from
    name: 'plugin-only-weather-plugins-off',
    face: 'plugin-weather-face',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin'] },
    plugins: 'plugins-off.json',
    load: {
      hidden: WEATHER_MARKED,
      notesHidden: [SOURCE_TEXT, PLUGINS_OFF_TEXT],
    },
    absent: [DATA_SOURCE_OPTION],
    panel: { kinds: [PANEL_WEATHER_OFF], off: true },
  },
  {
    // the same face on a phone whose plugins are on but serve no weather. the panel has no line about
    // plugins being off, so the note to turn plugins on, or update the Pebble app, shows alone
    name: 'plugin-only-weather-no-weather-plugin',
    face: 'plugin-weather-face',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin'] },
    plugins: 'phone-only.json',
    load: {
      hidden: WEATHER_MARKED,
      notesVisible: [PLUGINS_OFF_TEXT],
      badged: [PLUGINS_OFF_TEXT],
      notesHidden: [SOURCE_TEXT],
    },
    panel: { kinds: [PANEL_WEATHER_OFF], off: false },
  },
  {
    // the fixture's own calendar section, laid out as a face with calendar controls of its own builds
    // it. the calendar hook adds its select under the heading and the unmarked lead line. a fresh
    // install opens on the plugin, which hides the iCal sentence, the link, and the refresh interval
    // under it
    name: 'built-in-calendar',
    defines: { PLUGIN_CALENDAR: 1 },
    plugins: 'built-in.json',
    load: {
      ...SELECT_PLACE,
      visible: ['CALENDAR_SOURCE'],
      hidden: CALENDAR_MARKED,
      textsVisible: [CALENDAR_LEAD],
      textsHidden: [ICAL_LINE],
      unbadged: [CALENDAR_SOURCE_TEXT],
      options: [{ key: 'CALENDAR_SOURCE', has: ['ical', 'plugin'] }, { key: 'WEATHER_PROVIDER', lacks: ['plugin'] }],
    },
    changes: [
      { key: 'CALENDAR_SOURCE', value: 'ical', visible: CALENDAR_MARKED, textsVisible: [CALENDAR_LEAD, ICAL_LINE], notesHidden: [CALENDAR_SOURCE_TEXT] },
      { key: 'CALENDAR_SOURCE', value: 'plugin', hidden: CALENDAR_MARKED, notesVisible: [CALENDAR_SOURCE_TEXT] },
    ],
    save: { CALENDAR_SOURCE: 'plugin' },
  },
  {
    // a calendar plugin whose manifest names its readings its own way, so the face cannot read it
    name: 'calendar-not-standard',
    defines: { PLUGIN_CALENDAR: 1 },
    plugins: 'calendar-not-standard.json',
    load: {
      notesVisible: [CALENDAR_NOT_STANDARD_TEXT],
      badged: [CALENDAR_NOT_STANDARD_TEXT],
      options: [{ key: 'CALENDAR_SOURCE', has: ['ical', 'plugin'] }],
    },
    changes: [
      { key: 'CALENDAR_SOURCE', value: 'ical', notesHidden: [CALENDAR_NOT_STANDARD_TEXT] },
      { key: 'CALENDAR_SOURCE', value: 'plugin', notesVisible: [CALENDAR_NOT_STANDARD_TEXT], badged: [CALENDAR_NOT_STANDARD_TEXT] },
    ],
  },
  {
    // the calendar has no status line on the watch, so the page is the only place a denied permission shows
    name: 'calendar-permission-denied',
    defines: { PLUGIN_CALENDAR: 1 },
    plugins: 'calendar-permission-denied.json',
    load: {
      notesVisible: [CALENDAR_PERMISSION_TEXT],
      badged: [CALENDAR_PERMISSION_TEXT],
    },
    changes: [
      { key: 'CALENDAR_SOURCE', value: 'ical', notesHidden: [CALENDAR_PERMISSION_TEXT] },
      { key: 'CALENDAR_SOURCE', value: 'plugin', notesVisible: [CALENDAR_PERMISSION_TEXT], badged: [CALENDAR_PERMISSION_TEXT] },
    ],
  },
  {
    // an empty week and a missing permission look the same from the phone, so the empty update gets
    // the calmer note that says what may be wrong
    name: 'calendar-empty',
    defines: { PLUGIN_CALENDAR: 1 },
    plugins: 'calendar-empty.json',
    load: {
      unbadged: [CALENDAR_EMPTY_TEXT, CALENDAR_SOURCE_TEXT],
    },
    changes: [
      { key: 'CALENDAR_SOURCE', value: 'ical', notesHidden: [CALENDAR_EMPTY_TEXT] },
      { key: 'CALENDAR_SOURCE', value: 'plugin', unbadged: [CALENDAR_EMPTY_TEXT, CALENDAR_SOURCE_TEXT] },
    ],
  },
  {
    // with plugins off the select would offer iCal Link alone, so it is dropped and the iCal rows show
    // as they do on a face without the define
    name: 'calendar-plugins-off',
    defines: { PLUGIN_CALENDAR: 1 },
    plugins: 'plugins-off.json',
    load: {
      visible: CALENDAR_MARKED,
      hidden: ['CALENDAR_SOURCE'],
      textsVisible: [CALENDAR_LEAD, ICAL_LINE],
      notesHidden: [CALENDAR_SOURCE_TEXT],
    },
    saveNot: { CALENDAR_SOURCE: ['plugin', 'ical'] },
  },
  {
    // the saved plugin keeps its option, labelled as plugins off, so the select stays, the page opens
    // on it, and a save keeps it rather than dropping to iCal and clearing the agenda
    name: 'calendar-saved-plugin-plugins-off',
    defines: { PLUGIN_CALENDAR: 1 },
    plugins: 'plugins-off.json',
    settings: 'calendar-plugin-picked.json',
    load: {
      ...SELECT_PLACE,
      visible: ['CALENDAR_SOURCE'],
      hidden: CALENDAR_MARKED,
      textsVisible: [CALENDAR_LEAD],
      textsHidden: [ICAL_LINE],
      notesVisible: [PLUGINS_OFF_TEXT, CALENDAR_SOURCE_TEXT],
      badged: [PLUGINS_OFF_TEXT],
      options: [{ key: 'CALENDAR_SOURCE', has: ['ical', 'plugin'] }],
    },
    changes: [
      { key: 'CALENDAR_SOURCE', value: 'ical', visible: CALENDAR_MARKED, textsVisible: [ICAL_LINE], notesHidden: [PLUGINS_OFF_TEXT] },
      { key: 'CALENDAR_SOURCE', value: 'plugin', hidden: CALENDAR_MARKED, notesVisible: [PLUGINS_OFF_TEXT] },
    ],
    save: { CALENDAR_SOURCE: 'plugin' },
  },
  {
    // a phone whose plugin list cannot be read may still route to a plugin, so a saved plugin keeps
    // the plain choice, with no plugins off note
    name: 'calendar-unreadable',
    defines: { PLUGIN_CALENDAR: 1 },
    plugins: 'unreadable.json',
    settings: 'calendar-plugin-picked.json',
    load: {
      visible: ['CALENDAR_SOURCE'],
      hidden: CALENDAR_MARKED,
      notesVisible: [CALENDAR_SOURCE_TEXT],
      notesHidden: [PLUGINS_OFF_TEXT],
      options: [{ key: 'CALENDAR_SOURCE', has: ['ical', 'plugin'] }],
    },
    save: { CALENDAR_SOURCE: 'plugin' },
  },
  {
    // both kinds on, so the weather and calendar hooks fold one page between them and neither undoes
    // the other's rows. a fresh install opens both on the plugin
    name: 'built-in-weather-and-calendar',
    defines: { PLUGIN_WEATHER: 1, PLUGIN_CALENDAR: 1 },
    plugins: 'built-in.json',
    load: {
      ...SELECT_PLACE,
      visible: ['WEATHER_PROVIDER', 'CALENDAR_SOURCE'],
      hidden: [...WEATHER_MARKED, ...CALENDAR_MARKED],
      notesVisible: [SOURCE_TEXT, CALENDAR_SOURCE_TEXT],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'plugin'] }, { key: 'CALENDAR_SOURCE', has: ['ical', 'plugin'] }],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', visible: LOCATION_MARKED, hidden: ['WEATHER_API_KEY', ...CALENDAR_MARKED], notesVisible: [CALENDAR_SOURCE_TEXT], notesHidden: [SOURCE_TEXT] },
      { key: 'CALENDAR_SOURCE', value: 'ical', visible: [...LOCATION_MARKED, ...CALENDAR_MARKED], notesHidden: [SOURCE_TEXT, CALENDAR_SOURCE_TEXT] },
    ],
    pluginKinds: { weather: 'served', calendar: 'served' },
    save: { WEATHER_PROVIDER: 'openmeteo', CALENDAR_SOURCE: 'ical' },
  },
  {
    // a face listing the plugin alone for the calendar runs its events from it whatever is saved, and
    // offers no choice on the page. the iCal sentence, the link, and the refresh interval are gone,
    // and the face's unmarked lead line stays. the page says where the events come from, and a
    // plugin serves them, so no other note shows
    name: 'plugin-only-calendar',
    face: 'plugin-calendar-face',
    defines: { PLUGIN_CALENDAR: 1 },
    providers: { calendar: ['plugin'] },
    plugins: 'built-in.json',
    load: {
      visible: ['WEATHER_PROVIDER'],
      hidden: CALENDAR_MARKED,
      textsVisible: [CALENDAR_LEAD],
      textsHidden: [ICAL_LINE],
      notesVisible: [CALENDAR_SOURCE_TEXT],
      unbadged: [CALENDAR_SOURCE_TEXT],
      notesHidden: [PLUGINS_OFF_TEXT],
    },
    absent: [ICAL_OPTION],
    panel: { kinds: [PANEL_CALENDAR], off: false },
  },
  {
    // the same face with plugins off, where the panel's own line says to turn them on, once, and the
    // page says nothing on where the events come from while nothing serves them
    name: 'plugin-only-calendar-plugins-off',
    face: 'plugin-calendar-face',
    defines: { PLUGIN_CALENDAR: 1 },
    providers: { calendar: ['plugin'] },
    plugins: 'plugins-off.json',
    load: {
      hidden: CALENDAR_MARKED,
      notesHidden: [CALENDAR_SOURCE_TEXT, PLUGINS_OFF_TEXT],
    },
    absent: [ICAL_OPTION],
    panel: { kinds: [PANEL_CALENDAR_OFF], off: true },
  },
  {
    // a face listing two weather providers and no plugin. the Data Source select offers those two,
    // the key row stays since OpenWeatherMap needs a key, and the page is otherwise the builder's
    name: 'narrowed-weather',
    defines: {},
    providers: { weather: ['openmeteo', 'owm'] },
    plugins: null,
    load: {
      ...OPEN_METEO_ROWS,
      textsVisible: [LEAD_LINE],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'owm'], lacks: ['weatherapi', 'plugin'] }],
      order: BUILDER_ORDER,
    },
    // the key row stays on the page, since OpenWeatherMap needs a key, and shows once it is picked
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'owm', visible: ['WEATHER_API_KEY'] },
    ],
    save: { WEATHER_PROVIDER: 'owm' },
  },
  {
    // a face listing Open-Meteo alone. a dropdown with one provider is no choice, so it goes with its
    // lead line, and Open-Meteo needs no key, so the key row goes too. the location rows stay
    name: 'one-provider-weather',
    defines: {},
    providers: { weather: ['openmeteo'] },
    plugins: null,
    load: {
      visible: ['WEATHER_TEMPERATURE_UNIT', 'LOCATION_USE_GPS', 'LOCATION_GPS_FALLBACK', 'LOCATION_NAME'],
      hidden: ['WEATHER_PROVIDER', 'WEATHER_API_KEY'],
      textsVisible: ['Location Settings'],
      textsHidden: [LEAD_LINE],
    },
    absent: [OWM_OPTION],
    saveNot: { WEATHER_PROVIDER: ['owm', 'weatherapi'] },
  },
  {
    // a returning wearer who picked OpenWeatherMap, on a face that no longer offers it. the phone
    // moves the saved provider to the face's first, so the select shows it rather than a blank, and
    // a save carries it
    name: 'saved-provider-dropped',
    defines: {},
    providers: { weather: ['openmeteo', 'weatherapi'] },
    plugins: null,
    settings: 'owm-picked.json',
    // OpenWeatherMap's key stays OpenWeatherMap's, so neither Open-Meteo nor WeatherAPI is handed it
    load: {
      visible: ['WEATHER_PROVIDER'],
      hidden: ['WEATHER_API_KEY'],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'weatherapi'], lacks: ['owm'] }],
      values: { WEATHER_API_KEY: '' },
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'weatherapi', visible: ['WEATHER_API_KEY'], values: { WEATHER_API_KEY: '' } },
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', hidden: ['WEATHER_API_KEY'] },
    ],
    save: { WEATHER_PROVIDER: 'openmeteo', WEATHER_API_KEY: '' },
  },
  {
    // a face offering Open-Meteo and the Pebble app's weather. the select offers the two, with no key
    // row, since Open-Meteo needs none. a fresh install opens on the plugin, which hides the location rows
    name: 'mixed-weather',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin', 'openmeteo'] },
    plugins: 'built-in.json',
    load: {
      visible: ['WEATHER_PROVIDER'],
      hidden: ['WEATHER_API_KEY', ...LOCATION_MARKED],
      notesVisible: [SOURCE_TEXT],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'plugin'], lacks: ['owm', 'weatherapi'] }],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', visible: ['WEATHER_PROVIDER', ...LOCATION_MARKED], hidden: ['WEATHER_API_KEY'], notesHidden: [SOURCE_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', hidden: LOCATION_MARKED, notesVisible: [SOURCE_TEXT] },
    ],
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    // the same face showing coordinates. it is offered the plugin too, and the source note adds that
    // the coordinates show only from a plugin that serves them
    name: 'mixed-weather-coords',
    face: 'coords-face',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin', 'openmeteo'] },
    plugins: 'built-in.json',
    load: {
      visible: ['WEATHER_PROVIDER'],
      hidden: LOCATION_MARKED,
      notesVisible: [`${SOURCE_TEXT} ${COORDS_TEXT}`],
      options: [{ key: 'WEATHER_PROVIDER', has: ['openmeteo', 'plugin'], lacks: ['owm', 'weatherapi'] }],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', visible: ['WEATHER_PROVIDER', ...LOCATION_MARKED], notesHidden: [`${SOURCE_TEXT} ${COORDS_TEXT}`] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', hidden: LOCATION_MARKED, notesVisible: [`${SOURCE_TEXT} ${COORDS_TEXT}`] },
    ],
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    // the same face with plugins off. Open-Meteo is the one choice left, so the select and its lead
    // line go, and the location rows show for it
    name: 'mixed-weather-plugins-off',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin', 'openmeteo'] },
    plugins: 'plugins-off.json',
    load: {
      visible: ['WEATHER_TEMPERATURE_UNIT', 'LOCATION_USE_GPS', 'LOCATION_GPS_FALLBACK', 'LOCATION_NAME'],
      hidden: ['WEATHER_PROVIDER', 'WEATHER_API_KEY'],
      textsVisible: ['Location Settings'],
      textsHidden: [LEAD_LINE],
    },
    saveNot: { WEATHER_PROVIDER: ['plugin', 'owm', 'weatherapi'] },
  },
  {
    // a face with no temperature unit listing Open-Meteo alone. the select and its lead line go, and
    // the key row with them, which leaves the Weather card nothing to hold, so it goes too
    name: 'one-provider-weather-no-unit',
    face: 'no-unit-face',
    defines: {},
    providers: { weather: ['openmeteo'] },
    plugins: null,
    load: {
      visible: ['LOCATION_USE_GPS', 'LOCATION_GPS_FALLBACK', 'LOCATION_NAME'],
      hidden: ['WEATHER_PROVIDER', 'WEATHER_API_KEY'],
      textsVisible: ['Location Settings'],
      textsHidden: [LEAD_LINE, 'Weather'],
    },
  },
  {
    // the same page the way the Pebble Android app leaves it. the location search, with no text box
    // of Clay's own on the page, has to sit as it does in the usual order and keep the text box look
    name: 'one-provider-weather-no-unit-android-head',
    face: 'no-unit-face',
    defines: {},
    providers: { weather: ['openmeteo'] },
    plugins: null,
    androidHead: true,
    load: {
      visible: ['LOCATION_USE_GPS', 'LOCATION_GPS_FALLBACK', 'LOCATION_NAME'],
      hidden: ['WEATHER_PROVIDER', 'WEATHER_API_KEY'],
    },
  },
  {
    // the same page on a face offering Open-Meteo and the Pebble app's weather, on a phone whose
    // plugins serve no weather. the plugin hook drops the select to Open-Meteo alone with its lead
    // line, and the Weather card goes with them
    name: 'mixed-weather-no-unit-no-weather-plugin',
    face: 'no-unit-face',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin', 'openmeteo'] },
    plugins: 'phone-only.json',
    load: {
      visible: ['LOCATION_USE_GPS', 'LOCATION_GPS_FALLBACK', 'LOCATION_NAME'],
      hidden: ['WEATHER_PROVIDER', 'WEATHER_API_KEY'],
      textsVisible: ['Location Settings'],
      textsHidden: [LEAD_LINE, 'Weather'],
    },
    panel: { kinds: [PANEL_WEATHER_OFF], off: false },
  },
  {
    // the same page on a face taking its weather from a plugin alone, with plugins off. the panel
    // says to turn them on, so no note follows the anchor the first pass left, and the Weather card
    // that held it goes with it
    name: 'plugin-only-weather-no-unit-plugins-off',
    face: 'plugin-no-unit-face',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin'] },
    plugins: 'plugins-off.json',
    load: {
      // the face has no unit row to hide
      hidden: WEATHER_MARKED.filter((key) => !UNIT_MARKED.includes(key)),
      textsHidden: [LEAD_LINE, 'Weather', 'Location Settings'],
      notesHidden: [SOURCE_TEXT, PLUGINS_OFF_TEXT],
    },
    panel: { kinds: [PANEL_WEATHER_OFF], off: true },
  },
  {
    // a face of its own stock section listing Yahoo alone. the select goes, with one provider left,
    // and so does the key row, since Yahoo needs no key. the tickers stay
    name: 'one-provider-stocks',
    face: 'stock-face',
    defines: {},
    providers: { stocks: ['yahoo'] },
    plugins: null,
    load: {
      visible: ['STOCK_SYMBOLS'],
      hidden: ['STOCK_PROVIDER', 'STOCK_API_KEY'],
      textsVisible: [STOCK_LEAD],
    },
    absent: [FINNHUB_OPTION],
  },
  {
    // the same face listing Finnhub alone. the select goes, and the face's own condition on its key
    // row is settled against Finnhub, which needs a key, so the row shows
    name: 'one-keyed-provider-stocks',
    face: 'stock-face',
    defines: {},
    providers: { stocks: ['finnhub'] },
    plugins: null,
    load: {
      visible: ['STOCK_API_KEY', 'STOCK_SYMBOLS'],
      hidden: ['STOCK_PROVIDER'],
    },
  },
  {
    // the same face listing Yahoo and Alpha Vantage. the select offers the two, Yahoo first as the
    // default, and the face's key row shows only once Alpha Vantage is picked
    name: 'narrowed-stocks',
    face: 'stock-face',
    defines: {},
    providers: { stocks: ['yahoo', 'alphavantage'] },
    plugins: null,
    load: {
      visible: ['STOCK_PROVIDER', 'STOCK_SYMBOLS'],
      hidden: ['STOCK_API_KEY'],
      options: [{ key: 'STOCK_PROVIDER', has: ['yahoo', 'alphavantage'], lacks: ['finnhub', 'twelvedata'] }],
    },
    changes: [
      { key: 'STOCK_PROVIDER', value: 'alphavantage', visible: ['STOCK_API_KEY'] },
    ],
    save: { STOCK_PROVIDER: 'alphavantage' },
  },
  {
    // a returning wearer on Twelve Data whose phone also keeps a Finnhub key. each switch shows that
    // provider's own key, a provider with none shows a blank row, a key typed for it stays with it,
    // and the save carries every provider's key beside the settings
    name: 'stock-key-per-provider',
    face: 'stock-face',
    defines: {},
    plugins: null,
    settings: 'stock-keys-saved.json',
    providerKeys: 'stock-keys-held.json',
    load: {
      visible: ['STOCK_API_KEY'],
      values: { STOCK_API_KEY: 'TD-SAVED' },
    },
    changes: [
      { key: 'STOCK_PROVIDER', value: 'finnhub', values: { STOCK_API_KEY: 'FH-HELD' } },
      { key: 'STOCK_PROVIDER', value: 'alphavantage', values: { STOCK_API_KEY: '' } },
      { key: 'STOCK_API_KEY', value: 'AV-TYPED', values: { STOCK_API_KEY: 'AV-TYPED' } },
      { key: 'STOCK_PROVIDER', value: 'yahoo', hidden: ['STOCK_API_KEY'] },
      { key: 'STOCK_PROVIDER', value: 'twelvedata', visible: ['STOCK_API_KEY'], values: { STOCK_API_KEY: 'TD-SAVED' } },
    ],
    save: {
      STOCK_PROVIDER: 'twelvedata',
      STOCK_API_KEY: 'TD-SAVED',
      PF_PROVIDER_KEYS: encodeURIComponent('{"STOCK_PROVIDER":{"keys":{"twelvedata":"TD-SAVED","finnhub":"FH-HELD","alphavantage":"AV-TYPED"},"spare":""}}'),
    },
  },
  {
    // the stock fixture built with PLUGIN_STOCKS on a phone with a stock plugin. a fresh install opens
    // on the plugin. its own section carries no marks, so the plugin hides nothing of its own and adds
    // the note on where the quotes come from under the select
    name: 'stock-plugin-choice',
    face: 'stock-face',
    defines: { PLUGIN_STOCKS: 1 },
    plugins: 'stock.json',
    load: {
      visible: ['STOCK_PROVIDER', 'STOCK_SYMBOLS'],
      options: [{ key: 'STOCK_PROVIDER', has: ['finnhub', 'yahoo', 'twelvedata', 'alphavantage', 'plugin'] }],
      notesVisible: [STOCK_SOURCE_TEXT],
      unbadged: [STOCK_SOURCE_TEXT],
    },
    changes: [
      { key: 'STOCK_PROVIDER', value: 'finnhub', notesHidden: [STOCK_SOURCE_TEXT] },
      { key: 'STOCK_PROVIDER', value: 'plugin', notesVisible: [STOCK_SOURCE_TEXT], unbadged: [STOCK_SOURCE_TEXT] },
    ],
    panel: { kinds: [PANEL_STOCKS], off: false },
    save: { STOCK_PROVIDER: 'plugin' },
  },
  {
    // the same face with the plugin saved on a phone whose plugins are on but hold no stock plugin,
    // which is the usual state, since the Pebble app has none of its own. the choice is kept, and the
    // note says where to get a stock plugin rather than to turn plugins on
    name: 'stock-plugin-saved-none-installed',
    face: 'stock-face',
    defines: { PLUGIN_STOCKS: 1 },
    plugins: 'phone-only.json',
    settings: 'stock-plugin-picked.json',
    load: {
      options: [{ key: 'STOCK_PROVIDER', has: ['plugin'] }],
      notesVisible: [STOCK_NO_PLUGIN_TEXT],
      badged: [STOCK_NO_PLUGIN_TEXT],
      notesHidden: [PLUGINS_OFF_TEXT],
    },
    panel: { kinds: [{ label: 'Stocks', plugins: [{ name: 'Stocks', tag: 'v1.0.4', listing: PEBBLE_STOCKS_LISTING }, { name: 'Stocks + Crypto', tag: 'v1.0.1', listing: STOCKS_CRYPTO_LISTING }] }], off: false },
    pluginKinds: { stocks: 'missing' },
  },
  {
    // a face whose quotes come from a plugin alone. the Data Source, the key, and the tickers come
    // off the page, and the note on where the quotes come from stays in the Stock Preferences card,
    // in the place the select held
    name: 'plugin-only-stocks',
    face: 'plugin-stock-face',
    defines: { PLUGIN_STOCKS: 1 },
    providers: { stocks: ['plugin'] },
    plugins: 'stock.json',
    load: {
      hidden: ['STOCK_API_KEY', 'STOCK_SYMBOLS'],
      textsVisible: ['Stock Preferences'],
      notesVisible: [STOCK_SOURCE_TEXT],
      notesHidden: [STOCK_NO_PLUGIN_TEXT],
    },
    absent: [FINNHUB_OPTION],
    panel: { kinds: [PANEL_STOCKS], off: false },
  },
  {
    // the same face on a phone with plugins on and no stock plugin. the card says where to get one
    name: 'plugin-only-stocks-none-installed',
    face: 'plugin-stock-face',
    defines: { PLUGIN_STOCKS: 1 },
    providers: { stocks: ['plugin'] },
    plugins: 'phone-only.json',
    load: {
      textsVisible: ['Stock Preferences'],
      notesVisible: [STOCK_NO_PLUGIN_TEXT],
      badged: [STOCK_NO_PLUGIN_TEXT],
      notesHidden: [STOCK_SOURCE_TEXT, PLUGINS_OFF_TEXT],
    },
    panel: { kinds: [{ label: 'Stocks', plugins: [{ name: 'Stocks', tag: 'v1.0.4', listing: PEBBLE_STOCKS_LISTING }, { name: 'Stocks + Crypto', tag: 'v1.0.1', listing: STOCKS_CRYPTO_LISTING }] }], off: false },
  },
  {
    // a face with no settings page of its own, taking its weather from a plugin alone. the page holds
    // only what the weather adds: where the weather comes from, and the supported plugins panel
    name: 'no-page-plugin-weather',
    face: 'no-page-face',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin'] },
    plugins: 'built-in.json',
    load: {
      notesVisible: [SOURCE_TEXT],
      notesHidden: [PLUGINS_OFF_TEXT],
    },
    panel: { kinds: [PANEL_WEATHER], off: false },
  },
  {
    // the same face with plugins off, where the panel's own line says to turn them on, and nothing
    // else on the page needs saying
    name: 'no-page-plugin-weather-plugins-off',
    face: 'no-page-face',
    defines: { PLUGIN_WEATHER: 1 },
    providers: { weather: ['plugin'] },
    plugins: 'plugins-off.json',
    load: {
      notesHidden: [SOURCE_TEXT, PLUGINS_OFF_TEXT],
    },
    panel: { kinds: [PANEL_WEATHER_OFF], off: true },
  },
  {
    // a face with no visibleWhen row, no plugins, and no customClay of its own, opened the way the
    // Pebble Android app leaves the page while plugins are on. its selects, its key row, and its GPS
    // toggles have to keep no padding with the component styles ahead of Clay's base sheet
    name: 'android-head',
    face: 'core-face',
    defines: {},
    plugins: null,
    androidHead: true,
    load: {
      visible: ['WEATHER_TEMPERATURE_UNIT', 'WEATHER_PROVIDER', 'WEATHER_API_KEY', 'LOCATION_USE_GPS'],
    },
  },
  {
    // one row of every kind Clay draws in a card, in the usual order, where the row rules move none
    name: 'every-row',
    face: 'rows-face',
    defines: {},
    plugins: null,
    load: { visible: EVERY_ROW },
  },
  {
    // the same rows the way the Pebble Android app leaves the page, where each has to sit as it does
    // in the usual order
    name: 'every-row-android-head',
    face: 'rows-face',
    defines: {},
    plugins: null,
    androidHead: true,
    load: { visible: EVERY_ROW },
  },
  {
    // a theme picker on a page with no plain select, which takes its look from Clay's select only
    // through the framework, in the usual order
    name: 'picker-no-select',
    face: 'picker-face',
    defines: {},
    plugins: null,
    load: { visible: ['APPEARANCE_THEME', 'PICK_SWITCH'] },
  },
  {
    // the same page the way the Pebble Android app leaves it, where the picker has to keep its look
    // and sit as it does in the usual order
    name: 'picker-no-select-android-head',
    face: 'picker-face',
    defines: {},
    plugins: null,
    androidHead: true,
    load: { visible: ['APPEARANCE_THEME', 'PICK_SWITCH'] },
  },
  {
    // the panel on a weather face, listing the built-in plugin and the store's, where the settings page
    // can open a store listing outside itself
    name: 'panel-weather',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'built-in.json',
    openUrl: true,
    load: {},
    panel: { kinds: [PANEL_WEATHER], off: false },
  },
  {
    // weather and the calendar both on, so both hooks add their kind to the one panel
    name: 'panel-weather-and-calendar',
    defines: { PLUGIN_WEATHER: 1, PLUGIN_CALENDAR: 1 },
    plugins: 'built-in.json',
    openUrl: true,
    load: {},
    panel: { kinds: [PANEL_WEATHER, PANEL_CALENDAR], off: false },
  },
  {
    // with plugins off the calendar select drops to its one option, and the panel still lists both
    // kinds, opening on the line to turn plugins on, with the built-in plugins marked off. with no
    // openUrl the store plugin is plain text
    name: 'panel-plugins-off',
    defines: { PLUGIN_WEATHER: 1, PLUGIN_CALENDAR: 1 },
    plugins: 'plugins-off.json',
    load: { hidden: ['CALENDAR_SOURCE'] },
    panel: { kinds: [PANEL_WEATHER_OFF, PANEL_CALENDAR_OFF], off: true },
  },
  {
    // a face with the weather define whose page has no Data Source select never picks a plugin, so it
    // gets no panel, and its location rows show as they do without the define
    name: 'panel-no-choice',
    face: 'no-choice-face',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'built-in.json',
    load: { visible: ['LOCATION_USE_GPS', 'LOCATION_GPS_FALLBACK', 'LOCATION_NAME'] },
    absent: [PANEL_SELECTOR],
  },
  {
    // a face passing its own customClay gets the framework's show and hide first and its own code
    // after it. the page opens on the plugin, so the rows the plugin choice hides are already hidden
    // when the face's code runs, which its mark says. the face's code then shows the key row again,
    // and the later changes are the framework's alone
    name: 'face-custom-clay',
    face: 'custom-clay-face',
    defines: { PLUGIN_WEATHER: 1 },
    plugins: 'built-in.json',
    settings: 'plugin-picked.json',
    load: {
      visible: [...ALWAYS_SHOWN, 'WEATHER_API_KEY'],
      hidden: ['LOCATION_USE_GPS', 'LOCATION_GPS_FALLBACK', 'LOCATION_NAME'],
      notesVisible: [SOURCE_TEXT],
    },
    changes: [
      { key: 'WEATHER_PROVIDER', value: 'openmeteo', ...OPEN_METEO_ROWS, notesHidden: [SOURCE_TEXT] },
      { key: 'WEATHER_PROVIDER', value: 'plugin', visible: ALWAYS_SHOWN, hidden: WEATHER_MARKED, notesVisible: [SOURCE_TEXT] },
    ],
    present: [FACE_CODE_MARK],
    save: { WEATHER_PROVIDER: 'plugin' },
  },
  {
    // now playing and the phone battery on an Android phone with the built-in plugins. neither kind
    // has a select, both plugins serve, so the page needs no note, and the panel lists both kinds
    name: 'music-phone-built-in',
    face: 'music-phone-face',
    defines: { PLUGIN_MUSIC: 1, PLUGIN_PHONE: 1 },
    plugins: 'music-phone.json',
    load: musicPhoneNotes([]),
    panel: { kinds: [PANEL_MUSIC, PANEL_PHONE], off: false },
    pluginKinds: { music: 'served', phone: 'served' },
  },
  {
    // with plugins off the panel opens on its line to turn them on, so neither kind adds its own note
    // saying the same
    name: 'music-phone-plugins-off',
    face: 'music-phone-face',
    defines: { PLUGIN_MUSIC: 1, PLUGIN_PHONE: 1 },
    plugins: 'plugins-off.json',
    load: musicPhoneNotes([]),
    panel: { kinds: [PANEL_MUSIC_OFF, PANEL_PHONE_OFF], off: true },
    pluginKinds: { music: 'off', phone: 'off' },
  },
  {
    // an iPhone, where the Phone plugin serves and no music plugin does. the panel has no line about
    // plugins being off, so the music note shows, under the face's marked line
    name: 'music-phone-iphone',
    face: 'music-phone-face',
    defines: { PLUGIN_MUSIC: 1, PLUGIN_PHONE: 1 },
    plugins: 'phone-only.json',
    load: musicPhoneNotes([MUSIC_NO_PLUGIN_TEXT]),
    panel: { kinds: [PANEL_MUSIC_OFF, PANEL_PHONE], off: false },
    pluginKinds: { music: 'missing', phone: 'served' },
  },
  {
    // a wearer who has not allowed Music for the face, where the note says to
    name: 'music-permission-denied',
    face: 'music-phone-face',
    defines: { PLUGIN_MUSIC: 1, PLUGIN_PHONE: 1 },
    plugins: 'music-permission-denied.json',
    load: musicPhoneNotes([MUSIC_PERMISSION_TEXT]),
  },
  {
    // a music plugin that answered without the readings the face reads, named in its note
    name: 'music-not-standard',
    face: 'music-phone-face',
    defines: { PLUGIN_MUSIC: 1, PLUGIN_PHONE: 1 },
    plugins: 'music-not-standard.json',
    load: musicPhoneNotes([MUSIC_NOT_STANDARD_TEXT]),
    panel: { kinds: [{ label: 'Now Playing', plugins: [...PANEL_MUSIC_OFF.plugins, { name: 'Odd Music', tag: INSTALLED_TAG }] }, PANEL_PHONE], off: false },
  },
];
 
/** What a page showed at one moment, as the browser read it. */
export interface Observed {
  /** Each message key asked about, with whether its row is on the page and whether it shows. */
  keys: Record<string, { exists: boolean; visible: boolean }>;
  /** Each text asked about, with whether a row with those words shows. */
  texts: Record<string, boolean>;
  /** Each note asked about, with whether a note with those words shows and whether it carries the badge. */
  notes: Record<string, { visible: boolean; badged: boolean }>;
  /**
   * Each text asked about for its place, by its words and then by the row's message key, with whether
   * the text row sits above or below that row, or null when either is not on the page.
   */
  places: Record<string, Record<string, 'above' | 'below' | null>>;
  /** Each select asked about, with its option values, or null when it is not on the page. */
  options: Record<string, string[] | null>;
  /** The rows asked about for their order that are on the page, top to bottom, by message key. */
  order: string[];
  /** Each control asked about for its value, with the value Clay reads off it, or null when it is not on the page. */
  values?: Record<string, string | null>;
}
 
/** The plugin kinds store as the browser read it. */
export interface ObservedKinds {
  /** Whether the store is the first row Clay built, so a component anywhere on the page finds it. */
  first: boolean;
  /** The states the store holds, as a component parses them, or null when the page has no store or it does not parse. */
  states: Record<string, unknown> | null;
}
 
/**
 * Compares the plugin kinds store with what the scenario expects, and says what is wrong.
 *
 * @param observed What the browser read off the store.
 * @param expected Each kind's state.
 * @return One line per problem, empty when the store is right.
 */
export function pluginKindsProblems(observed: ObservedKinds, expected: Record<string, string>): string[] {
  if (!observed.states) {
    return ['the page holds no plugin kinds store a component can read'];
  }
 
  const problems = observed.first ? [] : ['the plugin kinds store is not the first row Clay builds, so a component above it cannot read it'];
 
  if (JSON.stringify(observed.states) !== JSON.stringify(expected)) {
    problems.push(`the plugin kinds store holds ${JSON.stringify(observed.states)}, not ${JSON.stringify(expected)}`);
  }
 
  return problems;
}
 
/**
 * Picks the scenarios to run from the check's arguments.
 *
 * @param args The scenario names given on the command line. None runs them all.
 * @param scenarios The scenario table.
 * @return The scenarios to run, in table order.
 */
export function pickScenarios(args: string[], scenarios: Scenario[]): Scenario[] {
  const unknown = args.filter((name) => !scenarios.some((scenario) => scenario.name === name));
 
  if (unknown.length) {
    throw new ToolError(`no scenario called ${unknown.join(', ')}. The scenarios are ${scenarios.map((scenario) => scenario.name).join(', ')}`);
  }
 
  return args.length ? scenarios.filter((scenario) => args.includes(scenario.name)) : scenarios;
}
 
/**
 * Compares what a page showed with what it should, and says what is wrong.
 *
 * @param observed What the browser read off the page.
 * @param expected What the page should show.
 * @param when When it was read, such as "on load", which each problem starts with.
 * @return One line per problem, empty when the page is right.
 */
export function expectationProblems(observed: Observed, expected: Expectation, when: string): string[] {
  const problems: string[] = [];
 
  (expected.visible || []).forEach((key) => {
    const row = observed.keys[key];
 
    if (!row || !row.exists) {
      problems.push(`${when}, ${key} is not on the page`);
    } else Eif (!row.visible) {
      problems.push(`${when}, ${key} is hidden but should show`);
    }
  });
 
  (expected.hidden || []).forEach((key) => {
    Iif (observed.keys[key] && observed.keys[key].visible) {
      problems.push(`${when}, ${key} shows but should be hidden`);
    }
  });
 
  (expected.textsVisible || []).forEach((text) => {
    if (!observed.texts[text]) {
      problems.push(`${when}, no row showing "${text}"`);
    }
  });
 
  (expected.textsHidden || []).forEach((text) => {
    if (observed.texts[text]) {
      problems.push(`${when}, a row shows "${text}" but should be hidden`);
    }
  });
 
  (expected.notesVisible || []).forEach((text) => {
    Eif (!observed.notes[text] || !observed.notes[text].visible) {
      problems.push(`${when}, no note showing "${text}"`);
    }
  });
 
  (expected.notesHidden || []).forEach((text) => {
    if (observed.notes[text] && observed.notes[text].visible) {
      problems.push(`${when}, a note shows "${text}" but should be hidden`);
    }
  });
 
  (expected.badged || []).forEach((text) => {
    Eif (!observed.notes[text] || !observed.notes[text].badged) {
      problems.push(`${when}, the note "${text}" carries no badge`);
    }
  });
 
  (expected.unbadged || []).forEach((text) => {
    if (!observed.notes[text] || !observed.notes[text].visible) {
      problems.push(`${when}, no note showing "${text}"`);
    } else Eif (observed.notes[text].badged) {
      problems.push(`${when}, the note "${text}" carries the warning badge but should not`);
    }
  });
 
  const placed = (wanted: 'above' | 'below') => ({ text, key }: { text: string; key: string }) => {
    const place = (observed.places[text] || {})[key];
 
    if (!place) {
      problems.push(`${when}, the row "${text}" or ${key} is not on the page to place`);
    } else Eif (place !== wanted) {
      problems.push(`${when}, the row "${text}" sits ${place} ${key}, not ${wanted} it`);
    }
  };
 
  (expected.textsAbove || []).forEach(placed('above'));
  (expected.textsBelow || []).forEach(placed('below'));
 
  Object.entries(expected.values || {}).forEach(([key, value]) => {
    const held = observed.values ? observed.values[key] : undefined;
 
    if (held === null || held === undefined) {
      problems.push(`${when}, ${key} is not on the page to read`);
    } else if (held !== value) {
      problems.push(`${when}, ${key} holds ${JSON.stringify(held)}, not ${JSON.stringify(value)}`);
    }
  });
 
  if (expected.order && JSON.stringify(observed.order) !== JSON.stringify(expected.order)) {
    problems.push(`${when}, the rows run ${observed.order.join(' then ') || 'nowhere'}, not ${expected.order.join(' then ')}`);
  }
 
  (expected.options || []).forEach(({ key, has = [], lacks = [] }) => {
    const values = observed.options[key];
 
    if (!values) {
      problems.push(`${when}, the ${key} select is not on the page`);
      return;
    }
 
    has.filter((value) => !values.includes(value)).forEach((value) => problems.push(`${when}, ${key} has no ${value} option`));
    lacks.filter((value) => values.includes(value)).forEach((value) => problems.push(`${when}, ${key} offers ${value} but should not`));
  });
 
  return problems;
}
 
/** What the supported plugins panel showed, as the browser read it. */
export interface ObservedPanel {
  /** How many panels are on the page. */
  count: number;
  /** Whether the panel is open. */
  open: boolean;
  /** Whether what the panel holds shows, which it only does while the panel is open. */
  bodyShows: boolean;
  /** The words the panel shows while it is closed. */
  title: string;
  /** Whether the line saying to turn plugins on is there. */
  off: boolean;
  /** Each kind's heading and its plugins, in the order they run down the panel. */
  kinds: Array<{ label: string; plugins: Array<{ name: string; tag: string; href: string | null; address: string }> }>;
}
 
/**
 * Compares what the open panel lists with what it should, and says what is wrong.
 *
 * A store plugin's name has to link to its listing where the page has `Pebble.openUrl`, and has to be
 * plain text with the listing's address under it where it has not.
 *
 * @param observed What the browser read off the open panel.
 * @param expected What the panel should list.
 * @param openUrl Whether the page has `Pebble.openUrl`.
 * @return One line per problem, empty when the panel is right.
 */
export function panelProblems(observed: ObservedPanel, expected: PanelExpectation, openUrl: boolean): string[] {
  const problems: string[] = [];
 
  Iif (observed.title !== PANEL_TITLE) {
    problems.push(`the panel's title reads "${observed.title}", not "${PANEL_TITLE}"`);
  }
 
  if (observed.off !== expected.off) {
    problems.push(expected.off ? 'the panel does not open on the line to turn plugins on' : 'the panel tells the wearer to turn plugins on, but should not');
  }
 
  const labels = observed.kinds.map((kind) => kind.label);
  const wanted = expected.kinds.map((kind) => kind.label);
 
  if (JSON.stringify(labels) !== JSON.stringify(wanted)) {
    problems.push(`the panel lists ${labels.join(', ') || 'no kinds'}, not ${wanted.join(', ')}`);
    return problems;
  }
 
  expected.kinds.forEach((kind, index) => {
    const shown = observed.kinds[index].plugins;
    const names = shown.map((plugin) => plugin.name);
 
    Iif (JSON.stringify(names) !== JSON.stringify(kind.plugins.map((plugin) => plugin.name))) {
      problems.push(`the panel lists ${names.join(', ') || 'nothing'} under ${kind.label}, not ${kind.plugins.map((plugin) => plugin.name).join(', ')}`);
      return;
    }
 
    kind.plugins.forEach((plugin, at) => {
      const seen = shown[at];
      const listing = plugin.listing || '';
      const href = openUrl && listing ? listing : null;
      const address = !openUrl && listing ? listing.replace(/^https:\/\//, '') : '';
 
      Iif (seen.tag !== (plugin.tag || '')) {
        problems.push(`the panel tags ${plugin.name} "${seen.tag}", not "${plugin.tag || ''}"`);
      }
 
      if (seen.href !== href) {
        problems.push(href ? `the panel links ${plugin.name} to ${seen.href || 'nothing'}, not ${href}` : `the panel links ${plugin.name} to ${seen.href}, but should not link it`);
      }
 
      if (seen.address !== address) {
        problems.push(`the panel shows the address of ${plugin.name} as "${seen.address}", not "${address}"`);
      }
    });
  });
 
  return problems;
}
 
/** What starts the address the settings page goes to on a save. */
const CLOSE_PREFIX = 'pebblejs://close#';
 
/**
 * Reads the settings a save sends, out of the address the page navigates to.
 *
 * Clay ends the page by going to pebblejs://close# with the settings as URI-encoded JSON, each
 * message key holding an object with the value in it.
 *
 * @param url The address the page navigated to.
 * @return The settings by message key, or null when the address is not a save.
 */
export function savedPayload(url: string): Record<string, unknown> | null {
  if (!url.startsWith(CLOSE_PREFIX)) {
    return null;
  }
 
  try {
    const parsed = JSON.parse(decodeURIComponent(url.slice(CLOSE_PREFIX.length)));
 
    return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
  } catch {
    return null;
  }
}
 
/** A saved value as the save carries it, or undefined when the save leaves the key out. */
function savedValue(payload: Record<string, unknown>, key: string): { value: unknown } | undefined {
  const entry = payload[key];
 
  return entry && typeof entry === 'object' && 'value' in entry ? (entry as { value: unknown }) : undefined;
}
 
/**
 * Compares a save with the values it should carry and the ones it must not.
 *
 * @param payload The settings the save sent, from savedPayload.
 * @param expected The values it has to carry, by message key.
 * @param forbidden The values it must not carry, by message key. A key the save leaves out carries none of them.
 * @return One line per key that is missing or wrong, empty when the save is right.
 */
export function saveProblems(payload: Record<string, unknown>, expected: Record<string, unknown>, forbidden: Record<string, unknown[]> = {}): string[] {
  const refused = Object.keys(forbidden).flatMap((key) => {
    const saved = savedValue(payload, key);
 
    return saved && forbidden[key].some((value) => JSON.stringify(value) === JSON.stringify(saved.value)) ? [`the save carries ${key} as ${JSON.stringify(saved.value)}, which it must not`] : [];
  });
 
  return Object.keys(expected).flatMap((key) => {
    const entry = payload[key];
 
    if (!entry || typeof entry !== 'object' || !('value' in entry)) {
      return [`the save carries no ${key}`];
    }
 
    const value = (entry as { value: unknown }).value;
 
    return JSON.stringify(value) === JSON.stringify(expected[key]) ? [] : [`the save carries ${key} as ${JSON.stringify(value)}, not ${JSON.stringify(expected[key])}`];
  }).concat(refused);
}
 
// the patterns a plain string replace reads in the text it puts in, which Clay's replace of
// $$CUSTOM_FN$$ would turn into something else
const REPLACE_PATTERNS = /\$[$&`']/g;
 
/**
 * Checks the custom function's text on one page, as the build the phone runs writes it.
 *
 * Clay pastes the text into the page with a plain string replace, so a replacement pattern in it is
 * read rather than copied and the page script breaks. The text has to hold none, and the page has to
 * carry it exactly as Clay was handed it, which also catches a later replace landing inside it.
 *
 * @param html The page as the browser opens it.
 * @param source The custom function's text, as Clay writes it into the page.
 * @return One line per problem, empty when the text is clean and on the page whole.
 */
export function customFnProblems(html: string, source: string): string[] {
  const problems: string[] = [];
  const patterns = source.match(REPLACE_PATTERNS) || [];
 
  if (patterns.length) {
    problems.push(`the custom function's text holds ${[...new Set(patterns)].join(', ')}, which Clay's string replace reads as a pattern`);
  }
 
  if (!html.includes(`window.customFn=${source},window.clayComponents=`)) {
    problems.push('the page does not carry the custom function text exactly as Clay was handed it');
  }
 
  return problems;
}
 
/** What marks the framework's row rules among the page's style rules, from ts/clay/page-style-component.ts. */
const ROW_RULE_MARK = '.component.component-select';
 
/** The rows Clay takes some padding off inside a card, which the framework's row rules repeat, by the class Clay gives each. */
const CLAY_ROWS = Object.keys(CLAY_ROW_PADDING);
 
/**
 * The script that lays a page out the way the Pebble Android app leaves it while plugins are on.
 *
 * The app runs a script at the very start of the page. With no head there yet, it makes one and puts
 * it first in the page, and the parser then opens the page's own head after it. `document.head` names
 * the first head, so every style Clay adds for a component lands ahead of Clay's base sheet.
 * Playwright runs its start script before the page has an html element, so that script would have
 * nowhere to put its head. This one goes just inside the page's own head instead, ahead of the base
 * sheet, and puts an empty head in front of it. That leaves the same two heads in the same order.
 */
const ANDROID_HEAD = '<script>document.documentElement.insertBefore(document.createElement(\'head\'), document.head);</script>';
 
/**
 * Lays a Clay page out the way the Pebble Android app leaves it while plugins are on.
 *
 * @param html The page as Clay writes it.
 * @return The page with the script just inside its own head, ahead of Clay's base sheet.
 */
export function withAndroidHead(html: string): string {
  const at = html.indexOf('<head>');
 
  Iif (at === -1) {
    throw new ToolError('the settings page has no <head> to put the Android app\'s head in front of');
  }
 
  const inside = at + '<head>'.length;
 
  return html.slice(0, inside) + ANDROID_HEAD + html.slice(inside);
}
 
/** One row in a card, as the browser read it. */
export interface PaddingRow {
  /** Its kind, by the class Clay gives it, such as `component-select`. */
  kind: string;
  /** Every class it carries. */
  classes: string[];
  /** Its padding, top, right, bottom, and left, as the page has it. */
  padding: string;
  /** Its padding with the framework's row rules turned off. */
  without: string;
  /** Its padding with Clay's base sheet moved ahead of every other sheet, the usual order. */
  usual: string;
}
 
/** The rows' padding on a page, as the browser read it with the framework's row rules on and off. */
export interface ObservedPadding {
  /** How many style sheets hold the row rules. */
  ruleSheets: number;
  /** Whether the check found Clay's base sheet, by the `.section > .component` rule it holds. */
  baseFound: boolean;
  /** Whether Clay's base sheet is the first style sheet in the page, as it is everywhere but the Android app. */
  baseFirst: boolean;
  /** Every row in a card, top to bottom. */
  rows: PaddingRow[];
}
 
/**
 * Checks the rows' padding on one page against the framework's row rules.
 *
 * Every page has to hold the rules once, and Clay's base sheet has to be found, since every other
 * check here leans on it. In the usual order the rules set what Clay's own rules already set, so
 * turning them off has to leave every row's padding as it was. That holds for the location search and
 * the theme picker too, since createClay registers the Clay component each borrows its class from,
 * unless the face passes its own.
 *
 * On a page laid out the way the Android app leaves it, every row has to sit as it does once the base
 * sheet is moved back ahead of the rest. The base sheet must not come first, and with the rules off it
 * has to move some row Clay takes padding off. Those two keep the check from passing on a page that
 * never showed the bug.
 *
 * @param observed The padding the browser read.
 * @param android Whether the page was laid out the way the Android app leaves it.
 * @return One line per problem, empty when the rows sit as they should.
 */
export function paddingProblems(observed: ObservedPadding, android: boolean): string[] {
  const problems: string[] = [];
 
  if (observed.ruleSheets !== 1) {
    problems.push(`the page holds the framework's row rules in ${observed.ruleSheets} style sheets, which should be one`);
  }
 
  if (!observed.baseFound) {
    problems.push('the check finds no style sheet holding Clay\'s .section > .component rule, so it cannot tell where Clay\'s base sheet sits');
  }
 
  if (!android) {
    observed.rows.filter((row) => row.padding !== row.without).forEach((row) => {
      problems.push(`the row rules move a ${row.kind} row's padding from ${row.without} to ${row.padding}`);
    });
 
    return [...new Set(problems)];
  }
 
  const clayRows = observed.rows.filter((row) => CLAY_ROWS.includes(row.kind));
 
  if (observed.baseFirst) {
    problems.push('the component styles sit behind Clay\'s base sheet, so the page is not laid out the way the Android app leaves it');
  }
 
  Iif (!clayRows.length) {
    problems.push('the page holds no row Clay takes padding off in a card to check');
  } else if (clayRows.every((row) => row.without === row.usual)) {
    problems.push('with the row rules off no row Clay takes padding off picks up the base sheet\'s padding, so the page shows nothing');
  }
 
  observed.rows.filter((row) => row.padding !== row.usual).forEach((row) => {
    problems.push(`a ${row.kind} row has ${row.padding} of padding with the component styles ahead of Clay's base sheet, and ${row.usual} in the usual order`);
  });
 
  return [...new Set(problems)];
}
 
/** A location search on the page, as the browser laid it out. */
export interface LocationField {
  /** How its label is laid out, the computed `display`. */
  label: string;
  /** How its text field is laid out, the computed `display`. */
  field: string;
}
 
/**
 * Checks each location search on a page carries the look of Clay's text box.
 *
 * The search draws the text box's markup and takes its look from Clay's text box style. Without that
 * style its label is laid out as a row, with the name beside a plain white field, rather than as a
 * block over a dark one. Both laid out as blocks is what the style alone gives them, so the check reads
 * that rather than a colour a face's own page style could change.
 *
 * @param fields Every location search on the page, top to bottom.
 * @return One line per search drawn without the style, empty when every one has it.
 */
export function locationFieldProblems(fields: LocationField[]): string[] {
  return fields.filter((field) => field.label !== 'block' || field.field !== 'block').map((field) => {
    return `a location search draws without Clay's text box style, with its label laid out as ${field.label} and its field as ${field.field}`;
  });
}
 
/** A theme picker on the page, as the browser laid it out. */
export interface ThemePicker {
  /** How the chosen theme's name is laid out, the computed `display` of its `.value`. */
  value: string;
  /** How see-through the native dropdown is, its computed `opacity`. */
  dropdown: string;
}
 
/**
 * Checks each theme picker on a page carries the look of Clay's select.
 *
 * The picker draws the select's markup and takes its look from Clay's select style, which lays the
 * chosen name out as a block with an arrow beside it and hides the native dropdown over it. Without
 * that style the bare dropdown shows on top of the name. The check reads those two rather than a
 * colour a face's own page style could change.
 *
 * @param pickers Every theme picker on the page, top to bottom.
 * @return One line per picker drawn without the style, empty when every one has it.
 */
export function themePickerProblems(pickers: ThemePicker[]): string[] {
  return pickers.filter((picker) => picker.value !== 'block' || picker.dropdown !== '0').map((picker) => {
    return `a theme picker draws without Clay's select style, with its name laid out as ${picker.value} and its dropdown at opacity ${picker.dropdown}`;
  });
}
 
/**
 * The folder of the fixture face a scenario previews.
 *
 * @param scenario The scenario, read for the face it names.
 * @return The face's folder under fixtures/.
 */
export function scenarioFace(scenario: Scenario): string {
  return path.join(FIXTURES, scenario.face ?? 'face');
}
 
/**
 * Where a fixture face sits for a build in one sandbox.
 *
 * A fixture is not a face in any unit, so it has no name the build can look up. It is built from the
 * framework's own folder, so the emit tree keeps the source's shape from there.
 *
 * @param sandbox The folder the build goes in.
 * @param faceDir The fixture face's folder.
 * @return The place facePaths and writeTsconfig take.
 */
export function fixturePlace(sandbox: string, faceDir: string = FIXTURE_FACE): FacePlace {
  return { root: ENGINE, rel: path.relative(ENGINE, faceDir).split(path.sep).join('/'), sandbox };
}
 
/** The paths a build of a fixture face reads and writes in one sandbox, laid out by facePaths. */
function fixturePaths(sandbox: string, faceDir: string): FacePaths {
  return facePaths(FACE, FACE, fixturePlace(sandbox, faceDir));
}
 
/** Compiles a fixture face and the framework's ts/ once, with the tsconfig the build writes, for every scenario to copy. */
function compileFixture(sandbox: string, faceDir: string): FacePaths {
  const paths = fixturePaths(sandbox, faceDir);
 
  cleanEmit(paths);
  writeTsconfig(FACE, paths, fixturePlace(sandbox, faceDir));
  compile(paths);
  return paths;
}
 
/**
 * Wraps the page's custom function so the check can reach Clay's page object.
 *
 * Clay calls the custom function with its page as this, and keeps it nowhere else the window can
 * see. The wrapper keeps it and then runs the page's own function, so the page builds exactly as it
 * would. It is a string, since it runs in the browser.
 */
const CAPTURE_CLAY = `(() => {
  let wrapped = function () { window.__pageCheckClay = this; };
  Object.defineProperty(window, 'customFn', {
    configurable: true,
    get: function () { return wrapped; },
    set: function (customFn) {
      wrapped = function () {
        window.__pageCheckClay = this;
        if (typeof customFn === 'function') {
          return customFn.apply(this, arguments);
        }
      };
    },
  });
})();`;
 
/** The keys, texts, notes, selects, and places one expectation asks about, so the browser reads only those. */
function askedAbout(expected: Expectation): { keys: string[]; texts: string[]; notes: string[]; selects: string[]; order: string[]; places: Array<{ text: string; key: string }>; values: string[] } {
  return {
    values: Object.keys(expected.values || {}),
    order: expected.order || [],
    keys: [...(expected.visible || []), ...(expected.hidden || [])],
    texts: [...(expected.textsVisible || []), ...(expected.textsHidden || [])],
    notes: [...(expected.notesVisible || []), ...(expected.notesHidden || []), ...(expected.badged || []), ...(expected.unbadged || [])],
    selects: (expected.options || []).map((option) => option.key),
    places: [...(expected.textsAbove || []), ...(expected.textsBelow || [])],
  };
}
 
/** Reads off the page what one expectation asks about. */
async function observe(page: Page, expected: Expectation): Promise<Observed> {
  return page.evaluate(({ keys, texts, notes, selects, order, places, values }) => {
    type Item = { $element?: HTMLElement[]; $manipulatorTarget?: HTMLSelectElement[]; get?: () => unknown };
    const clay = (window as unknown as { __pageCheckClay: { getItemByMessageKey(key: string): Item | undefined } }).__pageCheckClay;
    const shows = (element: Element | undefined): boolean => Boolean(element) && (element as Element).isConnected && (element as Element).checkVisibility();
    const observed: Observed = { keys: {}, texts: {}, notes: {}, options: {}, order: [], places: {} };
 
    keys.forEach((key) => {
      const item = clay.getItemByMessageKey(key);
      const element = item && item.$element ? item.$element[0] : undefined;
 
      observed.keys[key] = { exists: Boolean(element), visible: shows(element) };
    });
 
    const rows = Array.from(document.querySelectorAll('.component-text, .component-heading'));
 
    texts.forEach((text) => {
      observed.texts[text] = rows.some((row) => (row.textContent || '').trim() === text && shows(row));
    });
 
    // a note is read by its words as text, so a name escaped twice or turned into markup does not match.
    // the badge is the warning's :before
    const drawn = Array.from(document.querySelectorAll('.pf-note'));
 
    notes.forEach((text) => {
      const note = drawn.find((element) => {
        const words = element.querySelector('.pf-note-text');
 
        return Boolean(words) && (words as Element).textContent === text;
      });
 
      observed.notes[text] = {
        visible: shows(note),
        badged: Boolean(note) && window.getComputedStyle(note as Element, '::before').content === '"!"',
      };
    });
 
    // each asked row that is on the page, sorted by where it sits in the document
    const placed = order.map((key) => {
      const item = clay.getItemByMessageKey(key);
 
      return { key, element: item && item.$element ? item.$element[0] : undefined };
    }).filter((row) => row.element && row.element.isConnected) as Array<{ key: string; element: HTMLElement }>;
 
    placed.sort((first, second) => (first.element.compareDocumentPosition(second.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));
    observed.order = placed.map((row) => row.key);
 
    // a text row is placed against a keyed row by where the two sit in the document, shown or not
    places.forEach(({ text, key }) => {
      const words = rows.find((row) => (row.textContent || '').trim() === text);
      const item = clay.getItemByMessageKey(key);
      const element = item && item.$element ? item.$element[0] : undefined;
      const place = !words || !element || !element.isConnected ? null : words.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_FOLLOWING ? 'above' : 'below';
 
      observed.places[text] = { ...(observed.places[text] || {}), [key]: place };
    });
 
    selects.forEach((key) => {
      const item = clay.getItemByMessageKey(key);
      const select = item && item.$manipulatorTarget ? item.$manipulatorTarget[0] : undefined;
 
      observed.options[key] = select && select.options ? Array.from(select.options).map((option) => option.value) : null;
    });
 
    observed.values = {};
 
    values.forEach((key) => {
      const item = clay.getItemByMessageKey(key);
 
      (observed.values as Record<string, string | null>)[key] = item && item.get ? String(item.get()) : null;
    });
 
    return observed;
  }, askedAbout(expected));
}
 
/** Reads the plugin kinds store the way a face's component does, and whether Clay built it first. */
async function observeKinds(page: Page): Promise<ObservedKinds> {
  return page.evaluate((storeClass) => {
    const clay = (window as unknown as { __pageCheckClay: { getAllItems(): Array<{ $element?: HTMLElement[] }> } }).__pageCheckClay;
    const store = document.querySelector(`.${storeClass}`) as HTMLInputElement | null;
    const firstItem = clay.getAllItems()[0];
    const first = Boolean(store) && Boolean(firstItem && firstItem.$element && firstItem.$element[0] === store);
    let states: Record<string, unknown> | null;
 
    try {
      states = store ? JSON.parse(store.value) : null;
    } catch {
      states = null;
    }
 
    return { first, states };
  }, PLUGIN_KINDS_CLASS);
}
 
/**
 * Every row of the page that Clay left undrawn, by message key.
 *
 * A row naming capabilities is skipped along with every row inside it, since Clay leaves the whole of
 * it out on a watch that lacks them, which is the page working rather than failing.
 */
async function undrawnRows(page: Page): Promise<string[]> {
  return page.evaluate(() => {
    type Row = { messageKey?: string; capabilities?: unknown; items?: Row[] };
    const clay = (window as unknown as { __pageCheckClay: { getItemByMessageKey(key: string): { $element?: HTMLElement[] } | undefined } }).__pageCheckClay;
    const config = (window as unknown as { clayConfig: Row[] }).clayConfig || [];
    const keys: string[] = [];
    const walk = (rows: Row[]) => rows.forEach((row) => {
      if (row.capabilities !== undefined) {
        return;
      }
 
      if (row.messageKey) {
        keys.push(row.messageKey);
      }
 
      walk(row.items || []);
    });
 
    walk(config);
 
    return keys.filter((key) => {
      const item = clay.getItemByMessageKey(key);
 
      return !item || !item.$element || !item.$element[0] || !item.$element[0].isConnected;
    });
  });
}
 
/**
 * Reads every row's padding off the page with the framework's row rules on, with every sheet holding
 * them turned off, and with Clay's base sheet moved ahead of every other sheet, which is the usual
 * order. Selectors are compared with their spaces put in one agreed form, so a Clay that writes
 * `.section>.component` and one that writes `.section > .component` are read the same.
 */
async function observePadding(page: Page): Promise<ObservedPadding> {
  return page.evaluate((mark) => {
    const agreed = (text: string): string => text.replace(/\s*([>+~,])\s*/g, '$1').replace(/\s+/g, ' ').trim();
    const holds = (sheet: CSSStyleSheet, test: (selector: string) => boolean): boolean => Array.from(sheet.cssRules).some((rule) => rule instanceof CSSStyleRule && test(agreed(rule.selectorText)));
    const sheets = Array.from(document.styleSheets);
    const ruleSheets = sheets.filter((sheet) => holds(sheet, (selector) => selector.includes(mark)));
    const base = sheets.find((sheet) => holds(sheet, (selector) => selector === '.section>.component'));
    const rows = Array.from(document.querySelectorAll('.section > .component'));
    const read = (): string[] => rows.map((row) => {
      const style = window.getComputedStyle(row);
 
      return [style.paddingTop, style.paddingRight, style.paddingBottom, style.paddingLeft].join(' ');
    });
 
    const on = read();
 
    ruleSheets.forEach((sheet) => {
      sheet.disabled = true;
    });
 
    const off = read();
 
    ruleSheets.forEach((sheet) => {
      sheet.disabled = false;
    });
 
    // the base sheet goes first in the first head and then back where it was
    const baseNode = base ? base.ownerNode : null;
    let usual = on;
 
    if (baseNode && baseNode.parentNode && document.head) {
      const home = baseNode.parentNode;
      const next = baseNode.nextSibling;
 
      document.head.insertBefore(baseNode, document.head.firstChild);
      usual = read();
      home.insertBefore(baseNode, next);
    }
 
    return {
      ruleSheets: ruleSheets.length,
      baseFound: Boolean(base),
      baseFirst: Boolean(base) && sheets[0] === base,
      rows: rows.map((row, index) => {
        const classes = Array.from(row.classList);
        const kind = classes.find((name) => name.startsWith('component-')) || row.className;
 
        return { kind, classes, padding: on[index], without: off[index], usual: usual[index] };
      }),
    };
  }, ROW_RULE_MARK);
}
 
/** How the browser laid out each location search on the page, hidden or not, top to bottom. */
async function observeLocationFields(page: Page): Promise<LocationField[]> {
  return page.evaluate(() => Array.from(document.querySelectorAll('.pf-loc-search')).map((row) => {
    const display = (selector: string): string => {
      const found = row.querySelector(selector);
 
      return found ? window.getComputedStyle(found).display : 'missing';
    };
 
    return { label: display('label'), field: display('.pf-loc-query') };
  }));
}
 
/** How the browser laid out each theme picker on the page, hidden or not, top to bottom. */
async function observeThemePickers(page: Page): Promise<ThemePicker[]> {
  return page.evaluate(() => Array.from(document.querySelectorAll('.pf-theme')).map((row) => {
    const style = (selector: string): CSSStyleDeclaration | null => {
      const found = row.querySelector(selector);
 
      return found ? window.getComputedStyle(found) : null;
    };
    const value = style('.value');
    const dropdown = style('.pf-theme-select');
 
    return { value: value ? value.display : 'missing', dropdown: dropdown ? dropdown.opacity : 'missing' };
  }));
}
 
/**
 * Each card on the page that shows while every row in it but its headings is hidden or gone, by its
 * first heading, or empty text for a card with none. Clay draws a section as a card, so such a section
 * reads as a heading over nothing. A text row with no words counts as nothing too, so an anchor row
 * the page left behind does not keep a card looking full.
 */
async function emptyCards(page: Page): Promise<string[]> {
  return page.evaluate(() => {
    const shows = (element: Element): boolean => element.isConnected && element.checkVisibility();
    const empty = (row: Element): boolean => row.classList.contains('component-text') && (row.textContent || '').trim() === '';
    const counts = (row: Element): boolean => !row.classList.contains('component-heading') && !empty(row) && shows(row);
 
    return Array.from(document.querySelectorAll('.section'))
      .filter((card) => shows(card) && !Array.from(card.children).some(counts))
      .map((card) => (card.querySelector('.component-heading')?.textContent || '').trim());
  });
}
 
/** A problem for each card that shows with nothing in it but headings. */
function emptyCardProblems(cards: string[], when: string): string[] {
  return cards.map((card) => `${when}, ${card ? `the ${card} card` : 'a card with no heading'} shows with nothing in it`);
}
 
/**
 * The Pebble app's openUrl, as a scenario with `openUrl` hands it to the page. It records each address
 * and opens nothing, so the check can tell which listing a link asked for. It is a string, since it
 * runs in the browser.
 */
const FAKE_OPEN_URL = `(() => {
  window.__pageCheckOpened = [];
  window.Pebble = { openUrl: function (url) { window.__pageCheckOpened.push(String(url)); return Promise.resolve(true); } };
})();`;
 
/** Reads the supported plugins panel off the page. */
async function observePanel(page: Page): Promise<ObservedPanel> {
  return page.evaluate((selector) => {
    const panels = document.querySelectorAll(selector);
    const panel = panels[0] as HTMLDetailsElement | undefined;
    const body = panel ? panel.querySelector('.pf-plugins-body') : null;
    const textOf = (element: Element | null): string => (element ? element.textContent || '' : '');
    const kinds: ObservedPanel['kinds'] = [];
 
    // each heading is followed by the list of its plugins
    Array.from(panel ? panel.querySelectorAll('.pf-plugins-kind') : []).forEach((heading) => {
      const list = heading.nextElementSibling;
      const plugins = Array.from(list ? list.querySelectorAll('.pf-plugins-entry') : []).map((entry) => {
        const link = entry.querySelector('.pf-plugins-link');
 
        return {
          name: textOf(link || entry.querySelector('.pf-plugins-name')),
          tag: textOf(entry.querySelector('.pf-plugins-tag')),
          href: link ? link.getAttribute('href') : null,
          address: textOf(entry.querySelector('.pf-plugins-address')),
        };
      });
 
      kinds.push({ label: textOf(heading), plugins });
    });
 
    return {
      count: panels.length,
      open: Boolean(panel && panel.open),
      bodyShows: Boolean(body && body.checkVisibility()),
      title: panel ? textOf(panel.querySelector('.pf-plugins-title')) : '',
      off: Boolean(panel && panel.querySelector('.pf-plugins-off')),
      kinds,
    };
  }, PANEL_SELECTOR);
}
 
/**
 * Checks the supported plugins panel: there once, closed on load, opening on a tap of its title to
 * list what it should, each store link asking openUrl for its listing with the page staying where it
 * is, and closing again on a second tap.
 */
async function checkPanel(page: Page, expected: PanelExpectation, openUrl: boolean): Promise<string[]> {
  const before = await observePanel(page);
 
  if (before.count !== 1) {
    return [`the page holds ${before.count} supported plugins panels, not one`];
  }
 
  const problems: string[] = [];
 
  if (before.open || before.bodyShows) {
    problems.push('the panel is open on load');
  }
 
  await page.locator('.pf-plugins-title').click({ timeout: PAGE_WAIT_MS });
 
  const opened = await observePanel(page);
 
  if (!opened.open || !opened.bodyShows) {
    problems.push('the panel does not open on a tap of its title');
  }
 
  problems.push(...panelProblems(opened, expected, openUrl));
 
  if (openUrl) {
    const address = page.url();
 
    for (const plugin of expected.kinds.flatMap((kind) => kind.plugins).filter((listed) => listed.listing)) {
      const link = page.locator('.pf-plugins-link', { hasText: plugin.name });
 
      // a missing link is already a problem from panelProblems
      if (!(await link.count())) {
        continue;
      }
 
      await link.first().click({ timeout: PAGE_WAIT_MS });
 
      const asked = await page.evaluate(() => (window as unknown as { __pageCheckOpened: string[] }).__pageCheckOpened.slice(-1)[0]);
 
      if (asked !== plugin.listing) {
        problems.push(`a tap on ${plugin.name} asks to open ${asked || 'nothing'}, not ${plugin.listing}`);
      }
 
      if (page.url() !== address) {
        problems.push(`a tap on ${plugin.name} loads ${page.url()} inside the settings page`);
      }
    }
  }
 
  await page.locator('.pf-plugins-title').click({ timeout: PAGE_WAIT_MS });
 
  const closed = await observePanel(page);
 
  if (closed.open || closed.bodyShows) {
    problems.push('the panel does not close on a second tap of its title');
  }
 
  return problems;
}
 
/**
 * What Chromium logs when the save goes to pebblejs://close#, a scheme only the phone app opens. That
 * one message is the phone's job and not an error in the page. Headless Chromium leaves it out today,
 * and a headed run or another version may log it. The address part matches anything, since
 * encodeURIComponent leaves a quote in a saved value such as St. John's as it is.
 */
const FAILED_LAUNCH = /^Failed to launch 'pebblejs:\/\/close#.*' because the scheme does not have a registered handler\.$/;
 
/** Opens one built page and runs its scenario's checks, giving back every problem found. */
async function checkPage(browser: Browser, scenario: Scenario, html: string): Promise<string[]> {
  const problems: string[] = [];
  const context = await browser.newContext();
  const page = await context.newPage();
 
  page.on('pageerror', (error) => problems.push(`the page threw: ${error.message}`));
  page.on('console', (message) => {
    if (message.type() === 'error' && !FAILED_LAUNCH.test(message.text())) {
      problems.push(`the page logged an error: ${message.text()}`);
    }
  });
  page.on('dialog', (dialog) => {
    problems.push(`the page opened a dialog (${dialog.type()}) saying ${dialog.message()}`);
    dialog.dismiss().catch(() => {});
  });
 
  // Playwright's own request event drops everything after the #, where the save's settings are, so
  // the navigation the page asks for is read from Chromium itself
  const devtools = await context.newCDPSession(page);
  const saved: { url: string | null; landed: () => void } = { url: null, landed: () => {} };
 
  await devtools.send('Page.enable');
  devtools.on('Page.frameRequestedNavigation', (event) => {
    if (saved.url === null && event.url.startsWith(CLOSE_PREFIX)) {
      saved.url = event.url;
      saved.landed();
    }
  });
 
  try {
    await page.addInitScript(CAPTURE_CLAY);
 
    if (scenario.openUrl) {
      await page.addInitScript(FAKE_OPEN_URL);
    }
 
    await page.goto(pathToFileURL(html).href);
    await page.waitForFunction(() => {
      const clay = (window as unknown as { __pageCheckClay?: { getAllItems(): unknown[] } }).__pageCheckClay;
 
      try {
        return Boolean(clay) && (clay as { getAllItems(): unknown[] }).getAllItems().length > 0;
      } catch {
        return false;
      }
    }, undefined, { timeout: PAGE_WAIT_MS });
 
    const undrawn = await undrawnRows(page);
 
    if (undrawn.length) {
      problems.push(`Clay left ${undrawn.join(', ')} undrawn`);
    }
 
    problems.push(...paddingProblems(await observePadding(page), Boolean(scenario.androidHead)));
    problems.push(...locationFieldProblems(await observeLocationFields(page)));
    problems.push(...themePickerProblems(await observeThemePickers(page)));
    problems.push(...expectationProblems(await observe(page, scenario.load), scenario.load, 'on load'));
    problems.push(...emptyCardProblems(await emptyCards(page), 'on load'));
 
    if (scenario.panel) {
      problems.push(...(await checkPanel(page, scenario.panel, Boolean(scenario.openUrl))));
    }
 
    if (scenario.pluginKinds) {
      problems.push(...pluginKindsProblems(await observeKinds(page), scenario.pluginKinds));
    }
 
    for (const change of scenario.changes || []) {
      const select = await page.evaluateHandle((key) => {
        const clay = (window as unknown as { __pageCheckClay: { getItemByMessageKey(name: string): { $manipulatorTarget?: HTMLSelectElement[] } | undefined } }).__pageCheckClay;
        const item = clay.getItemByMessageKey(key);
 
        return item && item.$manipulatorTarget ? item.$manipulatorTarget[0] : null;
      }, change.key);
      const element = select.asElement();
 
      if (!element) {
        problems.push(`the ${change.key} control is not on the page to change`);
        break;
      }
 
      // a select takes the option picked, and a text row takes the words typed and then a change, as a
      // phone's keyboard gives one when the row loses focus
      if (await element.evaluate((target) => target.tagName === 'SELECT')) {
        await element.selectOption(change.value, { timeout: PAGE_WAIT_MS });
      } else {
        await element.fill(change.value, { timeout: PAGE_WAIT_MS });
        await element.dispatchEvent('change');
      }
 
      problems.push(...expectationProblems(await observe(page, change), change, `after picking ${change.value} for ${change.key}`));
      problems.push(...emptyCardProblems(await emptyCards(page), `after picking ${change.value} for ${change.key}`));
    }
 
    const selectors = [
      ...(scenario.absent || []).map((selector) => ({ selector, wanted: false })),
      ...(scenario.present || []).map((selector) => ({ selector, wanted: true })),
    ];
 
    for (const { selector, wanted } of selectors) {
      const found = await page.locator(selector).count();
 
      if (wanted && !found) {
        problems.push(`the page holds no ${selector} element, which it should`);
      } else if (!wanted && found) {
        problems.push(`the page holds ${found} ${selector} element${found === 1 ? '' : 's'} it should not`);
      }
    }
 
    if (scenario.save || scenario.saveNot) {
      // settles as soon as the page asks to close, and gives up once the page has had its time
      const closing = new Promise<void>((resolve) => {
        const timer = setTimeout(resolve, PAGE_WAIT_MS);
 
        saved.landed = () => {
          clearTimeout(timer);
          resolve();
        };
      });
 
      await page.locator('button[type="submit"]').click({ timeout: PAGE_WAIT_MS });
      await closing;
 
      const payload = saved.url === null ? null : savedPayload(saved.url);
 
      if (!payload) {
        problems.push(`the save never went to ${CLOSE_PREFIX} with settings in it`);
      } else {
        problems.push(...saveProblems(payload, scenario.save || {}, scenario.saveNot));
      }
    }
  } catch (error) {
    problems.push(`the check stopped: ${(error as Error).message.split('\n')[0]}`);
  } finally {
    await context.close();
  }
 
  return problems;
}
 
/** The keys of the scenario being rendered, which a require of message_keys gets. Each scenario fills in its own. */
let scenarioKeys: Record<string, number> | undefined;
 
/** A fixture face's appinfo, read once, and the build every scenario on it copies. */
interface Fixture {
  /** The fixture face's folder. */
  dir: string;
  /** The appinfo's messageKeys as written, which the build adds the features' and the defines' keys to before its checks. */
  declared: unknown;
  /** The build every scenario copies. */
  compiled: FacePaths;
}
 
/** Renders one scenario's page from its own copy of the build, onto a fresh phone, on the scenario's own keys. */
function renderScenario(scenario: Scenario, paths: FacePaths, messageKeys: Record<string, number>, withFeatures: boolean): ReturnType<typeof renderPage> {
  const settings = scenario.settings ? path.join(SETTINGS_FILES, scenario.settings) : null;
 
  forgetCompiled(paths);
  installHost({ platform: 'emery', settings, providerKeys: scenario.providerKeys ? path.join(SETTINGS_FILES, scenario.providerKeys) : null }, scenario.plugins === null ? null : readPluginsFile(path.join(PLUGIN_FILES, scenario.plugins)));
 
  scenarioKeys = messageKeys;
 
  return renderPage({ face: FACE, platform: 'emery' }, paths, messageKeys, withFeatures);
}
 
/** Builds one scenario's page and gives back its HTML file, and any problem with the build itself. */
function buildScenario(scenario: Scenario, fixture: Fixture): { html: string; problems: string[] } {
  // a providers list or a define the face's keys cannot back is one the real build refuses, so the
  // check does too, with the same checks in the same order. the providers list is read before the
  // phone code, as the phone build reads it, and the keys are checked once the code says which
  // features it passes, with the keys those features and the defines bring added, as the build adds them
  const providers = readProviders({ providers: scenario.providers }, FACE, scenario.defines);
 
  const paths = fixturePaths(path.join(OUT_DIR, scenario.name), fixture.dir);
  const html = path.join(OUT_DIR, `${scenario.name}.html`);
 
  cleanEmit(paths);
  fs.cpSync(fixture.compiled.emit, paths.emit, { recursive: true });
  fillPreviewEmit(paths, scenario.defines, providers);
 
  const base = fillAppinfo({ messageKeys: fixture.declared }, FACE, NO_START, scenario.defines, providers).messageKeys;
  const appinfo = fillAppinfo({ messageKeys: fixture.declared }, FACE, startFacts(paths, FACE, base, ['emery']), scenario.defines, providers);
 
  checkMessageKeys(appinfo.messageKeys, FACE, scenario.defines, providers);
 
  // each render gets a map of its own, since the page load adds to the map it is given
  const keysFor = (): Record<string, number> => messageKeysOf(appinfo);
 
  // the page the preview shows, which starts the features only for a build with a plugin define
  const page = renderScenario(scenario, paths, keysFor(), hasPluginDefines(scenario.defines));
  const problems: string[] = [];
 
  fs.writeFileSync(html, scenario.androidHead ? withAndroidHead(page.html) : page.html);
  problems.push(...customFnProblems(page.html, page.customFn));
 
  // the phone starts every feature and runs its hooks on each open, plugin define or not, so that
  // path has to give the page the face builds with no features at all
  if (scenario.unchanged) {
    const phone = renderScenario(scenario, paths, keysFor(), true);
    const bare = renderScenario(scenario, paths, keysFor(), false);
 
    if (phone.html !== bare.html) {
      problems.push(phone.folded !== bare.folded
        ? 'the features changed the page config, which should match the face\'s own byte for byte'
        : 'the page config matches, but the page differs in its custom function or its components');
    }
  }
 
  return { html, problems };
}
 
async function main(): Promise<void> {
  const started = Date.now();
  const scenarios = pickScenarios(process.argv.slice(2), SCENARIOS);
  const fixtures = new Map<string, Fixture>();
 
  // each fixture face used is compiled once, before the browser starts
  scenarios.map(scenarioFace).forEach((dir) => {
    if (fixtures.has(dir)) {
      return;
    }
 
    const appinfo = path.join(dir, 'pebble.appinfo.json');
 
    fixtures.set(dir, {
      dir,
      declared: JSON.parse(fs.readFileSync(appinfo, 'utf8')).messageKeys,
      compiled: compileFixture(path.join(OUT_DIR, 'compiled', path.basename(dir)), dir),
    });
  });
 
  stubModuleLoad((id) => (id === 'message_keys' && scenarioKeys ? scenarioKeys : undefined));
 
  // loaded here rather than at the top, so the specs of the pure parts above never load Playwright
  const { chromium } = await import('playwright');
  const browser = await chromium.launch();
  let failed = 0;
 
  try {
    for (const scenario of scenarios) {
      let problems: string[];
      let html = '';
 
      try {
        const built = buildScenario(scenario, fixtures.get(scenarioFace(scenario)) as Fixture);
 
        html = built.html;
        problems = [...built.problems, ...(await checkPage(browser, scenario, built.html))];
      } catch (error) {
        problems = [`the preview did not build: ${(error as Error).message.split('\n')[0]}`];
      }
 
      if (problems.length) {
        failed++;
        console.log(`FAIL ${scenario.name}${html ? ` (${path.relative(process.cwd(), html)})` : ''}`);
        problems.forEach((problem) => console.log(`  - ${problem}`));
      } else {
        console.log(`pass ${scenario.name}`);
      }
    }
  } finally {
    await browser.close();
  }
 
  console.log(`${scenarios.length - failed} of ${scenarios.length} scenarios passed in ${((Date.now() - started) / 1000).toFixed(1)} s`);
 
  if (failed) {
    process.exitCode = 1;
  }
}
 
Iif (isMainScript(import.meta)) {
  main().catch(reportFailure);
}