All files index.ts

88.03% Statements 618/702
72.2% Branches 252/349
84.58% Functions 214/253
90.01% Lines 595/661

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 298113x                                                                                                                                                                                                                                                                                                                                                                                                                                   51x 51x                   22x 22x 22x                     3x 3x 3x                     7x 7x 7x                     2x 2x 2x                     6x 6x 6x                           1x 1x 1x                           1x 1x 1x                                       2x 2x 2x                             1x 1x 1x                             1x 1x 1x                               1x 1x 1x                   1x 1x 1x                   1x 1x 1x                           1x 1x 1x                           1x 1x 1x                                                                                                                               57x   57x               57x               57x 57x 57x                                                                             52x 1x 1x     51x 51x                                 8x                           2x 2x             1x         1x   1x 1x 1x                   52x                           51x             52x 52x 52x                                                                                                                                                                                                                                                                                                             10x 10x 10x                   7x 7x                     5x 5x                           6x 6x                       4x 4x 4x                                   1x 1x             56x           56x 54x 54x 54x           56x 50x     6x 2x         4x   4x 4x             4x         233x 4x     229x 229x   102x   15x   32x   10x   26x   4x       4x       8x 4x     4x     4x     4x     4x 4x     4x 4x     4x   4x   4x     7x     4x     5x             239x 62x     177x   177x 56x 56x 56x       177x         56x 54x 235x           49x 39x     10x 40x 40x 40x 31x             49x 49x 5x   49x 7x   49x               4x 4x 16x   4x             1x 1x   1x 4x 4x     1x   4x 2x         3x                                       51x 49x                             1x 1x                             1x 1x 4x       1x                     1x 1x       1x 4x     1x                     1x 1x       1x 3x                       1x 1x       1x 3x                                                                                                                                                                                                                             13x   13x                                                                           4x     124x 124x 124x                     2x                   5x                                                                               32x 32x       32x 32x 32x           32x       32x                                                                     2x 2x       2x                                                     20x 20x 20x 20x       20x                                                                           3x 3x 3x 3x       3x                                                               2x 2x       2x           2x                                                                                                       32x 32x       32x 1x           31x 31x 1x         30x 30x 30x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 42x 42x   42x 42x                 42x 60x 2x   40x 40x 40x   57x     57x 55x     2x                         57x                         40x 57x   40x                                                               41x 39x 39x 39x         39x 39x   39x 39x 39x 39x   39x         39x 56x       56x 56x   56x     56x 56x 56x         56x   56x 56x     56x 1x       56x   56x   79x       79x       79x 79x                                                                 39x 39x 39x 56x   39x 39x     39x                 39x 56x 56x     56x     56x                                   39x 38x     1x 1x 1x 1x 3x 3x 3x   1x     2x 1x 1x           39x 39x 38x     1x     1x 1x 6x           7x               7x 7x 7x 7x 14x   7x   7x                   14x       14x 14x 14x 14x 14x 14x   14x 28x 28x 14x     14x 14x 14x           14x 3x 3x 3x     3x   3x         3x     11x     14x 14x         14x                               73x 73x 73x 73x     73x 169x   169x 12x 12x   12x 12x         12x 4x       169x 2x           73x 9x       9x   9x   9x 1x     8x   3x   1x   4x           73x 167x 167x       167x   167x     73x       7x 7x 7x 7x       73x       160x 160x 160x 160x       73x     7x 7x     7x 7x     7x   7x 7x 7x 7x       73x       32x 32x 32x 32x         73x 17x       17x   17x   17x   2x     16x         73x 9x       9x   9x   9x 9x         73x   56x 56x 56x     161x   161x       161x       9x 9x         9x 9x 9x         161x 160x   160x       160x 160x             2x 2x 2x 5x       37x 37x       37x 37x 37x 37x 37x   37x             8x 8x   7x       7x 7x             2x 2x 2x 4x       32x 32x       32x 32x                 2x 2x 2x 2x           1x 1x 1x 1x 1x 1x 1x     1x     1x     17x 17x       17x 17x 17x 17x 17x   17x             2x 2x       2x 2x 2x 2x 2x       2x       2x   2x             11x 11x       11x 2x         9x 9x 9x 9x 9x       9x   9x                   4x 4x       4x 1x         3x 3x 3x 3x 3x       3x   3x             3x 3x       3x 3x 3x 3x 3x   3x             2x 2x       2x 2x 2x 2x 2x       2x   2x             20x 20x       20x 20x 20x 20x 20x   20x                               296x 1x     295x   295x 295x   295x               4x       4x 4x 18x 10x           10x     4x 4x   4x 4x 4x 2x 2x 2x         4x                   4x     4x 18x 10x 10x             4x 2x 2x     2x     4x 2x 2x 2x         2x     4x                                                                   2x     2x                                                             2x 6x       2x 2x 1x 1x   1x 1x                           7x 1x 1x     7x 7x 7x                   1x                   1x                     1x 1x 4x 4x   1x                   14x 5x         13x 13x 13x 13x 13x 13x 13x   13x                    
import 'reflect-metadata';
 
/**
 * Specifies the sort direction for query results.
 *
 * @remarks
 * Used with {@link QueryBuilder.orderBy} to control ascending or descending record order.
 */
type QueryDirection = 'asc' | 'desc';
 
/**
 * Logical connector used to combine adjacent query clauses.
 *
 * - `'and'` - both conditions must be satisfied (default).
 * - `'or'`  - either condition may be satisfied.
 */
type QueryConnector = 'and' | 'or';
 
/**
 * Extracts all `string`-assignable keys from type `T`.
 *
 * @typeParam T - The entity type to inspect.
 */
type QueryFieldKey<T> = Extract<keyof T, string>;
 
/**
 * Values that support comparison operators (`gt`, `gte`, `lt`, `lte`, `between`).
 */
type ComparableValue = string | number | bigint | Date;
 
/**
 * Narrows `QueryFieldKey<T>` to only those keys whose value type extends {@link ComparableValue}.
 *
 * @typeParam T - The entity type to inspect.
 */
type ComparableFieldKey<T> = {
  [K in QueryFieldKey<T>]-?: T[K] extends ComparableValue ? K : never;
}[QueryFieldKey<T>];
 
/**
 * Narrows `QueryFieldKey<T>` to only those keys whose value type is `number`.
 *
 * @typeParam T - The entity type to inspect.
 */
type NumericFieldKey<T> = {
  [K in QueryFieldKey<T>]-?: T[K] extends number ? K : never;
}[QueryFieldKey<T>];
 
/**
 * Narrows `QueryFieldKey<T>` to only those keys whose value type is `string`.
 *
 * @typeParam T - The entity type to inspect.
 */
type StringFieldKey<T> = {
  [K in QueryFieldKey<T>]-?: T[K] extends string ? K : never;
}[QueryFieldKey<T>];
 
/**
 * Narrows `QueryFieldKey<T>` to only those keys whose value type is a readonly array.
 *
 * @typeParam T - The entity type to inspect.
 */
type ArrayFieldKey<T> = {
  [K in QueryFieldKey<T>]-?: T[K] extends readonly any[] ? K : never;
}[QueryFieldKey<T>];
 
/**
 * Resolves to the element type of an array type `T`.
 *
 * @typeParam T - An array type.
 *
 * @example
 * ```ts
 * type Elem = ArrayElement<string[]>; // string
 * ```
 */
type ArrayElement<T> = T extends readonly (infer U)[] ? U : never;
 
/**
 * Resolves the value type accepted by the `contains` operator for field `T`.
 *
 * - For `string` fields, accepts a `string` substring.
 * - For array fields, accepts an element of that array.
 *
 * @typeParam T - The field value type.
 */
type ContainsValue<T> = T extends string
  ? string
  : T extends readonly (infer U)[]
    ? U
    : never;
 
/**
 * All filter operators supported by {@link FieldQueryBuilder} and {@link QueryBuilder}.
 *
 * | Operator       | Applicable field types          | Description                                      |
 * |----------------|---------------------------------|--------------------------------------------------|
 * | `equals`       | any                             | Strict equality (`===`).                         |
 * | `gt`           | {@link ComparableValue}         | Greater than.                                    |
 * | `gte`          | {@link ComparableValue}         | Greater than or equal.                           |
 * | `lt`           | {@link ComparableValue}         | Less than.                                       |
 * | `lte`          | {@link ComparableValue}         | Less than or equal.                              |
 * | `startsWith`   | `string`                        | String prefix match.                             |
 * | `endsWith`     | `string`                        | String suffix match.                             |
 * | `contains`     | `string` \| array               | Substring or array membership.                   |
 * | `matches`      | `string`                        | Regular-expression test.                         |
 * | `between`      | {@link ComparableValue}         | Inclusive range `[start, end]`.                  |
 * | `notBetween`   | {@link ComparableValue}         | Outside the range `(start, end)`.                |
 * | `in`           | any                             | Value present in a supplied list.                |
 * | `notIn`        | any                             | Value absent from a supplied list.               |
 * | `containsAny`  | array                           | Array field contains at least one supplied value.|
 * | `containsAll`  | array                           | Array field contains every supplied value.       |
 */
type QueryOperator =
  | 'equals'
  | 'gt'
  | 'gte'
  | 'lt'
  | 'lte'
  | 'startsWith'
  | 'endsWith'
  | 'contains'
  | 'matches'
  | 'between'
  | 'notBetween'
  | 'in'
  | 'notIn'
  | 'containsAny'
  | 'containsAll';
 
/**
 * Base structure shared by all query clauses.
 *
 * @internal
 */
interface QueryClauseBase {
  /** Logical connector joining this clause to its predecessor, or `null` for the first clause. */
  connector: QueryConnector | null;
}
 
/**
 * A leaf query clause that tests a single field against an operator and value.
 *
 * @internal
 */
interface QueryCondition extends QueryClauseBase {
  kind: 'condition';
  /** Name of the entity field being tested. */
  field: string;
  /** Filter operator applied to the field value. */
  op: QueryOperator;
  /** Reference value for the comparison. */
  value: any;
}
 
/**
 * A composite query clause containing a nested list of {@link QueryClause} nodes.
 * All clauses in the group are evaluated together and their combined result
 * is treated as a single boolean for the outer clause tree.
 *
 * @internal
 */
interface QueryGroup extends QueryClauseBase {
  kind: 'group';
  /** Nested clauses evaluated as a logical sub-expression. */
  clauses: QueryClause[];
}
 
/**
 * A discriminated union of all possible clause node types.
 *
 * @internal
 */
type QueryClause = QueryCondition | QueryGroup;
 
/**
 * Return type of {@link QueryBuilder.count} when `groupBy` has been called.
 *
 * Each element carries the value of the grouped field together with the
 * number of records sharing that value.
 *
 * @typeParam T - The entity type.
 * @typeParam K - The field key used as the grouping dimension.
 */
type GroupCountResult<T, K extends Extract<keyof T, string>> = Array<
  Record<K, T[K]> & { count: number }
>;
 
/**
 * A type-safe, fluent builder that appends filter conditions for a single field
 * onto the parent {@link QueryBuilder}.
 *
 * Instances are created by calling {@link QueryBuilder.where} with a field name.
 * Every terminal method (e.g., `equals`, `gt`, `contains`) appends the
 * corresponding {@link QueryCondition} to the parent builder and returns the
 * parent, enabling chained query construction.
 *
 * @typeParam T - The entity type being queried.
 * @typeParam K - The specific field key this builder targets.
 *
 * @example
 * ```ts
 * const results = await db.User.query()
 *   .where('age').gte(18)
 *   .and('status').equals('active')
 *   .execute();
 * ```
 */
class FieldQueryBuilder<T, K extends QueryFieldKey<T>> {
  constructor(
    private parent: QueryBuilder<T>,
    private field: K,
  ) {}
 
  /**
   * Filters records where `field === value`.
   *
   * @param value - The exact value to match.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  equals(value: T[K]): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'equals', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where `field > value`.
   * Only available on fields whose type extends {@link ComparableValue}.
   *
   * @param value - The exclusive lower bound.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  gt(value: T[K] extends ComparableValue ? T[K] : never): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'gt', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where `field >= value`.
   * Only available on fields whose type extends {@link ComparableValue}.
   *
   * @param value - The inclusive lower bound.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  gte(value: T[K] extends ComparableValue ? T[K] : never): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'gte', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where `field < value`.
   * Only available on fields whose type extends {@link ComparableValue}.
   *
   * @param value - The exclusive upper bound.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  lt(value: T[K] extends ComparableValue ? T[K] : never): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'lt', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where `field <= value`.
   * Only available on fields whose type extends {@link ComparableValue}.
   *
   * @param value - The inclusive upper bound.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  lte(value: T[K] extends ComparableValue ? T[K] : never): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'lte', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where the string field starts with `value`.
   * Only available on `string` fields.
   *
   * @param value - The required prefix.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  startsWith(
    this: FieldQueryBuilder<T, StringFieldKey<T>>,
    value: string,
  ): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'startsWith', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where the string field ends with `value`.
   * Only available on `string` fields.
   *
   * @param value - The required suffix.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  endsWith(
    this: FieldQueryBuilder<T, StringFieldKey<T>>,
    value: string,
  ): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'endsWith', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where the field contains `value`.
   *
   * - For `string` fields: tests substring inclusion.
   * - For array fields: tests element membership.
   *
   * Only available on `string` or array fields.
   *
   * @param value - The substring or element to search for.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  contains(
    this:
      | FieldQueryBuilder<T, StringFieldKey<T>>
      | FieldQueryBuilder<T, ArrayFieldKey<T>>,
    value: ContainsValue<T[K]>,
  ): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'contains', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where the string field matches the given regular expression.
   * Only available on `string` fields.
   *
   * @param value - A `RegExp` instance or a pattern string. When a string is
   *   provided it is passed to `new RegExp(value)`.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  matches(
    this: FieldQueryBuilder<T, StringFieldKey<T>>,
    value: RegExp | string,
  ): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'matches', value);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where `start <= field <= end` (inclusive on both bounds).
   * Only available on fields whose type extends {@link ComparableValue}.
   *
   * @param start - The inclusive lower bound.
   * @param end   - The inclusive upper bound.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  between(
    start: T[K] extends ComparableValue ? T[K] : never,
    end: T[K] extends ComparableValue ? T[K] : never,
  ): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'between', [start, end]);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where `field < start || field > end`
   * (exclusive on both bounds, i.e., outside the range).
   * Only available on fields whose type extends {@link ComparableValue}.
   *
   * @param start - The lower boundary of the excluded range.
   * @param end   - The upper boundary of the excluded range.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  notBetween(
    start: T[K] extends ComparableValue ? T[K] : never,
    end: T[K] extends ComparableValue ? T[K] : never,
  ): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'notBetween', [start, end]);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where `field` is present in `values`.
   *
   * @param values - The allowed values.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  in(values: Array<T[K]>): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'in', values);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where `field` is **not** present in `values`.
   *
   * @param values - The disallowed values.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  notIn(values: Array<T[K]>): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'notIn', values);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where the array field contains **at least one** of `values`.
   * Only available on array fields.
   *
   * @param values - One or more elements to search for.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  containsAny(
    this: FieldQueryBuilder<T, ArrayFieldKey<T>>,
    values: Array<ArrayElement<T[K]>>,
  ): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'containsAny', values);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Filters records where the array field contains **every** element in `values`.
   * Only available on array fields.
   *
   * @param values - All elements that must be present.
   * @returns The parent {@link QueryBuilder} for further chaining.
   */
  containsAll(
    this: FieldQueryBuilder<T, ArrayFieldKey<T>>,
    values: Array<ArrayElement<T[K]>>,
  ): QueryBuilder<T> {
    this.parent.appendCondition(this.field, 'containsAll', values);
    this.parent.clearCurrentField();
    return this.parent;
  }
 
  /**
   * Appends an `AND` clause for the given field and returns a new
   * {@link FieldQueryBuilder} targeting that field.
   *
   * @typeParam K2 - The key of the next field.
   * @param field  - The entity field to target.
   * @returns A new {@link FieldQueryBuilder} for `field`.
   */
  and<K2 extends QueryFieldKey<T>>(field: K2): FieldQueryBuilder<T, K2> {
    this.parent.clearCurrentField();
    return this.parent.and(field);
  }
 
  /**
   * Sets the pending logical connector to `'or'` and returns the parent
   * {@link QueryBuilder}, ready to begin the next clause.
   *
   * @returns The parent {@link QueryBuilder}.
   */
  or(): QueryBuilder<T> {
    this.parent.clearCurrentField();
    return this.parent.or();
  }
}
 
/**
 * Fluent query builder for constructing, filtering, sorting, and aggregating
 * records stored in an IndexedDB object store.
 *
 * Obtain an instance through {@link EntityRepository.query}. Do not instantiate
 * this class directly.
 *
 * @typeParam T - The entity type being queried.
 *
 * @remarks
 * The builder accumulates filter clauses, ordering directives, and pagination
 * constraints, then executes them in memory after fetching candidates from
 * IndexedDB. When an index and optional range are configured via
 * {@link QueryBuilder.useIndex} and {@link QueryBuilder.range}, the initial
 * candidate set is narrowed at the IDB layer before in-memory filtering begins.
 *
 * @example Basic filtering with chaining
 * ```ts
 * const results = await db.User.query()
 *   .where('age').gte(18)
 *   .and('status').equals('active')
 *   .orderBy('name')
 *   .limit(20)
 *   .execute();
 * ```
 *
 * @example Aggregation
 * ```ts
 * const total = await db.Order.query().where('status').equals('paid').sum('amount');
 * const grouped = await db.Order.query().groupBy('status').count();
 * ```
 */
class QueryBuilder<T> {
  private db: IDBDatabase;
  private storeName: string;
  private transaction?: IDBTransaction;
  private clauses: QueryClause[] = [];
  private orderField?: Extract<keyof T, string>;
  private orderDirection: QueryDirection = 'asc';
  private limitCount?: number;
  private offsetCount?: number;
  private indexName?: string;
  private rangeStart?: any;
  private rangeEnd?: any;
  private currentField?: string;
  private groupField?: Extract<keyof T, string>;
  private pendingConnector: QueryConnector = 'and';
 
  /** @internal */
  constructor(
    db: IDBDatabase,
    storeName: string,
    transaction?: IDBTransaction,
  ) {
    this.db = db;
    this.storeName = storeName;
    this.transaction = transaction;
  }
 
  /**
   * Begins a filter condition for the given field, or adds a nested group
   * via a builder callback.
   *
   * @overload
   * @param field - The entity field to target.
   * @returns A {@link FieldQueryBuilder} for `field`.
   *
   * @overload
   * @param builder - A callback that receives a nested {@link QueryBuilder} and
   *   appends clauses to it. The entire sub-expression is treated as a single
   *   grouped condition in the outer query.
   * @returns `this` for chaining.
   *
   * @example Field form
   * ```ts
   * query.where('age').gte(18)
   * ```
   *
   * @example Grouped form
   * ```ts
   * query
   *   .where((qb) =>
   *     qb.where('type').equals('premium').and('status').equals('active'),
   *   )
   *   .or()
   *   .where('isTrial').equals(true)
   * ```
   */
  where<K extends QueryFieldKey<T>>(field: K): FieldQueryBuilder<T, K>;
  where(builder: (query: QueryBuilder<T>) => QueryBuilder<T> | void): this;
  where(
    fieldOrBuilder:
      | QueryFieldKey<T>
      | ((query: QueryBuilder<T>) => QueryBuilder<T> | void),
  ): this | FieldQueryBuilder<T, any> {
    if (typeof fieldOrBuilder === 'function') {
      this.clearCurrentField();
      return this.addNestedGroup(fieldOrBuilder);
    }
 
    this.currentField = fieldOrBuilder;
    return new FieldQueryBuilder<T, any>(this, fieldOrBuilder);
  }
 
  /**
   * Alias for {@link QueryBuilder.where} that conveys `AND` semantics.
   * Accepts both the field-name and builder-callback overloads.
   *
   * @param fieldOrBuilder - A field key or a nested-group builder callback.
   * @returns A {@link FieldQueryBuilder} (field overload) or `this` (builder overload).
   */
  and<K extends QueryFieldKey<T>>(field: K): FieldQueryBuilder<T, K>;
  and(builder: (query: QueryBuilder<T>) => QueryBuilder<T> | void): this;
  and(
    fieldOrBuilder:
      | QueryFieldKey<T>
      | ((query: QueryBuilder<T>) => QueryBuilder<T> | void),
  ): this | FieldQueryBuilder<T, any> {
    return this.where(fieldOrBuilder as any);
  }
 
  /**
   * Sets the logical connector for the **next** clause to `'or'`.
   *
   * @returns `this` for chaining.
   *
   * @example
   * ```ts
   * query.where('age').lt(18).or().where('hasParentalConsent').equals(true)
   * ```
   */
  or(): this {
    this.pendingConnector = 'or';
    return this;
  }
 
  /** @internal */
  private addNestedGroup(
    builder: (query: QueryBuilder<T>) => QueryBuilder<T> | void,
  ): this {
    const nested = new QueryBuilder<T>(
      this.db,
      this.storeName,
      this.transaction,
    );
    const returned = builder(nested) ?? nested;
    const clauses =
      returned instanceof QueryBuilder ? returned.clauses : nested.clauses;
    this.appendClause({ kind: 'group', clauses });
    return this;
  }
 
  /**
   * Clears the internally tracked "current field" pointer.
   * Called automatically by terminal {@link FieldQueryBuilder} methods.
   *
   * @internal
   */
  clearCurrentField(): void {
    this.currentField = undefined;
  }
 
  /**
   * Appends a leaf {@link QueryCondition} to the clause list using the pending
   * connector.
   *
   * @param field - Entity field name.
   * @param op    - Filter operator.
   * @param value - Comparison value.
   *
   * @internal
   */
  appendCondition(field: string, op: QueryOperator, value: any): void {
    this.appendClause({ kind: 'condition', field, op, value });
  }
 
  /** @internal */
  private appendClause(
    clause: Omit<QueryCondition, 'connector'> | Omit<QueryGroup, 'connector'>,
  ): void {
    const connector = this.clauses.length === 0 ? null : this.pendingConnector;
    this.clauses.push({ ...clause, connector } as QueryClause);
    this.pendingConnector = 'and';
  }
 
  /** @internal */
  private requireCurrentField(operation: string): string {
    if (!this.currentField) {
      throw new Error(`No field specified for ${operation}`);
    }
 
    const field = this.currentField;
    this.currentField = undefined;
    return field;
  }
 
  /** @internal */
  private addCondition(op: QueryOperator, value: any): this {
    const field = this.requireCurrentField(op);
    this.appendCondition(field, op, value);
    return this;
  }
 
  /**
   * Filters records where the current field strictly equals `value`.
   * @param value - Expected value.
   */
  equals(value: any) {
    return this.addCondition('equals', value);
  }
 
  /**
   * Filters records where the current field is greater than `value`.
   * @param value - Exclusive lower bound.
   */
  gt(value: any) {
    return this.addCondition('gt', value);
  }
 
  /**
   * Filters records where the current field is greater than or equal to `value`.
   * @param value - Inclusive lower bound.
   */
  gte(value: any) {
    return this.addCondition('gte', value);
  }
 
  /**
   * Filters records where the current field is less than `value`.
   * @param value - Exclusive upper bound.
   */
  lt(value: any) {
    return this.addCondition('lt', value);
  }
 
  /**
   * Filters records where the current field is less than or equal to `value`.
   * @param value - Inclusive upper bound.
   */
  lte(value: any) {
    return this.addCondition('lte', value);
  }
 
  /**
   * Filters records where the current string field starts with `value`.
   * @param value - Required prefix.
   */
  startsWith(value: string) {
    return this.addCondition('startsWith', value);
  }
 
  /**
   * Filters records where the current string field ends with `value`.
   * @param value - Required suffix.
   */
  endsWith(value: string) {
    return this.addCondition('endsWith', value);
  }
 
  /**
   * Filters records where the current string or array field contains `value`.
   * @param value - Substring or array element to search for.
   */
  contains(value: any) {
    return this.addCondition('contains', value);
  }
 
  /**
   * Filters records where the current string field matches the given pattern.
   * @param value - `RegExp` instance or pattern string.
   */
  matches(value: RegExp | string) {
    return this.addCondition('matches', value);
  }
 
  /**
   * Filters records where `start <= field <= end`.
   * @param start - Inclusive lower bound.
   * @param end   - Inclusive upper bound.
   */
  between(start: any, end: any) {
    return this.addCondition('between', [start, end]);
  }
 
  /**
   * Filters records where `field < start || field > end`.
   * @param start - Lower boundary of the excluded range.
   * @param end   - Upper boundary of the excluded range.
   */
  notBetween(start: any, end: any) {
    return this.addCondition('notBetween', [start, end]);
  }
 
  /**
   * Filters records where the current field's value is in the `values` array.
   * @param values - Allowed values.
   */
  ['in'](values: any[]) {
    return this.addCondition('in', values);
  }
 
  /**
   * Filters records where the current field's value is **not** in the `values` array.
   * @param values - Disallowed values.
   */
  notIn(values: any[]) {
    return this.addCondition('notIn', values);
  }
 
  /**
   * Filters records where the array field contains at least one value from `values`.
   * @param values - Elements, at least one of which must be present.
   */
  containsAny(values: any[]) {
    return this.addCondition('containsAny', values);
  }
 
  /**
   * Filters records where the array field contains every value in `values`.
   * @param values - Elements, all of which must be present.
   */
  containsAll(values: any[]) {
    return this.addCondition('containsAll', values);
  }
 
  /**
   * Specifies the field and direction used to sort results.
   *
   * @param field     - The entity field to sort by.
   * @param direction - `'asc'` (default) or `'desc'`.
   * @returns `this` for chaining.
   */
  orderBy(field: Extract<keyof T, string>, direction: QueryDirection = 'asc') {
    this.orderField = field;
    this.orderDirection = direction;
    return this;
  }
 
  /**
   * Limits the maximum number of records returned after filtering and sorting.
   *
   * @param n - Maximum number of records.
   * @returns `this` for chaining.
   */
  limit(n: number) {
    this.limitCount = n;
    return this;
  }
 
  /**
   * Skips `n` records from the filtered, sorted result set before applying
   * any {@link QueryBuilder.limit}.
   *
   * @param n - Number of records to skip.
   * @returns `this` for chaining.
   */
  offset(n: number) {
    this.offsetCount = n;
    return this;
  }
 
  /**
   * Directs the initial candidate fetch to use the specified IDB index instead
   * of a full store scan. Combine with {@link QueryBuilder.range} to exploit
   * native key-range filtering at the IDB layer.
   *
   * @param indexName - The name of an existing index on the object store.
   * @returns `this` for chaining.
   *
   * @throws `Error` if the named index does not exist on the store at execution time.
   */
  useIndex(indexName: string) {
    this.indexName = indexName;
    return this;
  }
 
  /**
   * Constrains the IDB key range used when reading via {@link QueryBuilder.useIndex}.
   * Has no effect unless `useIndex` has been called.
   *
   * @param start - Inclusive lower bound of the key range, or `undefined` for an open lower bound.
   * @param end   - Inclusive upper bound of the key range, or `undefined` for an open upper bound.
   * @returns `this` for chaining.
   */
  range(start: any, end: any) {
    this.rangeStart = start;
    this.rangeEnd = end;
    return this;
  }
 
  /**
   * Groups results by the given field and transforms the query so that
   * {@link QueryBuilder.count} returns a {@link GroupCountResult} array.
   *
   * @typeParam K - The field key to group by.
   * @param field - The entity field to use as the grouping dimension.
   * @returns A modified `QueryBuilder` whose `count()` method returns grouped counts.
   *
   * @example
   * ```ts
   * const byStatus = await db.Order.query().groupBy('status').count();
   * // [{ status: 'paid', count: 42 }, { status: 'pending', count: 7 }]
   * ```
   */
  groupBy<K extends QueryFieldKey<T>>(field: K) {
    this.groupField = field;
    return this as unknown as QueryBuilder<T> & {
      count(): Promise<GroupCountResult<T, K>>;
    };
  }
 
  /** @internal */
  private async loadCandidates(): Promise<T[]> {
    const store = this.transaction
      ? this.transaction.objectStore(this.storeName)
      : this.db
          .transaction(this.storeName, 'readonly')
          .objectStore(this.storeName);
 
    const request = this.createReadRequest(store);
    return new Promise<T[]>((resolve, reject) => {
      request.onsuccess = () => resolve((request.result as T[]) ?? []);
      request.onerror = () => reject(request.error);
    });
  }
 
  /** @internal */
  private createReadRequest(store: IDBObjectStore): IDBRequest {
    if (!this.indexName) {
      return store.getAll();
    }
 
    if (!store.indexNames.contains(this.indexName)) {
      throw new Error(
        `Index '${this.indexName}' does not exist on ${this.storeName}`,
      );
    }
 
    const index = store.index(this.indexName);
    let keyRange: IDBKeyRange | undefined;
    if (this.rangeStart !== undefined && this.rangeEnd !== undefined) {
      keyRange = IDBKeyRange.bound(this.rangeStart, this.rangeEnd);
    } else Eif (this.rangeStart !== undefined) {
      keyRange = IDBKeyRange.lowerBound(this.rangeStart);
    } else if (this.rangeEnd !== undefined) {
      keyRange = IDBKeyRange.upperBound(this.rangeEnd);
    }
 
    return keyRange ? index.getAll(keyRange) : index.getAll();
  }
 
  /** @internal */
  private matchesClause(item: T, clause: QueryClause): boolean {
    if (clause.kind === 'group') {
      return this.evaluateClauses(item, clause.clauses);
    }
 
    const value = (item as any)[clause.field];
    switch (clause.op) {
      case 'equals':
        return value === clause.value;
      case 'gt':
        return value > clause.value;
      case 'gte':
        return value >= clause.value;
      case 'lt':
        return value < clause.value;
      case 'lte':
        return value <= clause.value;
      case 'startsWith':
        return (
          typeof value === 'string' && value.startsWith(String(clause.value))
        );
      case 'endsWith':
        return (
          typeof value === 'string' && value.endsWith(String(clause.value))
        );
      case 'contains':
        if (typeof value === 'string') {
          return value.includes(String(clause.value));
        }
 
        return Array.isArray(value) && value.includes(clause.value);
      case 'matches': {
        const pattern =
          clause.value instanceof RegExp
            ? new RegExp(clause.value.source, clause.value.flags)
            : new RegExp(String(clause.value));
        return typeof value === 'string' && pattern.test(value);
      }
      case 'between': {
        const [start, end] = clause.value as [any, any];
        return value >= start && value <= end;
      }
      case 'notBetween': {
        const [start, end] = clause.value as [any, any];
        return value < start || value > end;
      }
      case 'in':
        return Array.isArray(clause.value) && clause.value.includes(value);
      case 'notIn':
        return Array.isArray(clause.value) && !clause.value.includes(value);
      case 'containsAny':
        return (
          Array.isArray(value) &&
          Array.isArray(clause.value) &&
          clause.value.some((entry: any) => value.includes(entry))
        );
      case 'containsAll':
        return (
          Array.isArray(value) &&
          Array.isArray(clause.value) &&
          clause.value.every((entry: any) => value.includes(entry))
        );
    }
  }
 
  /** @internal */
  private evaluateClauses(item: T, clauses: QueryClause[]): boolean {
    if (!clauses.length) {
      return true;
    }
 
    let result = this.matchesClause(item, clauses[0]);
 
    for (let index = 1; index < clauses.length; index += 1) {
      const clause = clauses[index];
      const matches = this.matchesClause(item, clause);
      result =
        clause.connector === 'or' ? result || matches : result && matches;
    }
 
    return result;
  }
 
  /** @internal */
  private async collectMatches(): Promise<T[]> {
    const candidates = await this.loadCandidates();
    return candidates.filter((item) =>
      this.evaluateClauses(item, this.clauses),
    );
  }
 
  /** @internal */
  private sortResults(results: T[]): T[] {
    if (!this.orderField) {
      return results;
    }
 
    return [...results].sort((left, right) => {
      const leftValue = (left as any)[this.orderField!];
      const rightValue = (right as any)[this.orderField!];
      if (leftValue < rightValue) return this.orderDirection === 'asc' ? -1 : 1;
      Eif (leftValue > rightValue) return this.orderDirection === 'asc' ? 1 : -1;
      return 0;
    });
  }
 
  /** @internal */
  private applyPagination(results: T[]): T[] {
    let nextResults = results;
    if (this.offsetCount !== undefined) {
      nextResults = nextResults.slice(this.offsetCount);
    }
    if (this.limitCount !== undefined) {
      nextResults = nextResults.slice(0, this.limitCount);
    }
    return nextResults;
  }
 
  /** @internal */
  private async aggregateValues<R>(
    field: Extract<keyof T, string> | undefined,
    reducer: (values: Array<any>) => R,
  ): Promise<R> {
    const results = await this.collectMatches();
    const values = field
      ? results.map((item) => (item as any)[field])
      : results;
    return reducer(values);
  }
 
  /** @internal */
  private async aggregateGroupedCount<K extends Extract<keyof T, string>>(
    field: K,
  ): Promise<GroupCountResult<T, K>> {
    const results = await this.collectMatches();
    const groups = new Map<any, number>();
 
    for (const item of results) {
      const key = (item as any)[field];
      groups.set(key, (groups.get(key) ?? 0) + 1);
    }
 
    return Array.from(groups.entries())
      .sort(([left], [right]) => {
        if (left < right) return -1;
        Eif (left > right) return 1;
        return 0;
      })
      .map(
        ([key, count]) =>
          ({ [field]: key, count }) as Record<K, T[K]> & { count: number },
      );
  }
 
  /**
   * Executes the query and returns all matching records after applying
   * ordering and pagination.
   *
   * @returns A promise that resolves to an array of matching entities.
   *
   * @example
   * ```ts
   * const activeUsers = await db.User.query()
   *   .where('status').equals('active')
   *   .orderBy('createdAt', 'desc')
   *   .limit(10)
   *   .execute();
   * ```
   */
  async execute(): Promise<T[]> {
    const results = await this.collectMatches();
    return this.applyPagination(this.sortResults(results));
  }
 
  /**
   * Returns the number of records matching the current query.
   *
   * When {@link QueryBuilder.groupBy} has been called, returns a
   * {@link GroupCountResult} array instead of a plain number.
   *
   * @returns A promise that resolves to either a `number` or a
   *   `GroupCountResult` array, depending on whether `groupBy` was invoked.
   */
  async count(): Promise<
    number | GroupCountResult<T, Extract<keyof T, string>>
  > {
    Eif (this.groupField) {
      return this.aggregateGroupedCount(this.groupField);
    }
 
    const results = await this.collectMatches();
    return results.length;
  }
 
  /**
   * Computes the sum of a numeric field across all matching records.
   * Non-numeric values are treated as `0`.
   *
   * @param field - A numeric field key (enforced at compile time).
   * @returns A promise that resolves to the numeric sum.
   */
  async sum(field: NumericFieldKey<T>): Promise<number> {
    const total = await this.aggregateValues(field, (values) =>
      values.reduce(
        (accumulator, value) => accumulator + (Number(value) || 0),
        0,
      ),
    );
    return total;
  }
 
  /**
   * Computes the arithmetic mean of a numeric field across all matching records.
   * Returns `0` when no records match.
   *
   * @param field - A numeric field key (enforced at compile time).
   * @returns A promise that resolves to the average value.
   */
  async avg(field: NumericFieldKey<T>): Promise<number> {
    const values = await this.aggregateValues(field, (items) => items);
    Iif (!values.length) {
      return 0;
    }
 
    const total = values.reduce(
      (accumulator, value) => accumulator + (Number(value) || 0),
      0,
    );
    return total / values.length;
  }
 
  /**
   * Returns the minimum value of a comparable field across all matching records.
   * Returns `null` when no records match.
   *
   * @param field - A field key whose value type extends {@link ComparableValue}.
   * @returns A promise that resolves to the minimum field value, or `null`.
   */
  async min(field: ComparableFieldKey<T>): Promise<T[typeof field] | null> {
    const values = await this.aggregateValues(field, (items) => items);
    Iif (!values.length) {
      return null;
    }
 
    return values.reduce((currentMin, value) =>
      value < currentMin ? value : currentMin,
    );
  }
 
  /**
   * Returns the maximum value of a comparable field across all matching records.
   * Returns `null` when no records match.
   *
   * @param field - A field key whose value type extends {@link ComparableValue}.
   * @returns A promise that resolves to the maximum field value, or `null`.
   */
  async max(field: ComparableFieldKey<T>): Promise<T[typeof field] | null> {
    const values = await this.aggregateValues(field, (items) => items);
    Iif (!values.length) {
      return null;
    }
 
    return values.reduce((currentMax, value) =>
      value > currentMax ? value : currentMax,
    );
  }
}
 
// ─── Decorator Option Interfaces ─────────────────────────────────────────────
 
/**
 * Configuration options for the {@link KeyPath} and {@link CompositeKeyPath}
 * decorators, controlling key generation behaviour.
 */
interface KeyPathOptions {
  /**
   * When `true`, the object store is created with `autoIncrement: true` and
   * the browser assigns a monotonically increasing numeric key on each `add`.
   *
   * @default false
   */
  autoIncrement?: boolean;
 
  /**
   * Key generator to invoke when creating a record whose key field is absent
   * or empty.
   *
   * - `'uuid'`      - UUID v4 string via {@link KeyGenerators.uuid}.
   * - `'timestamp'` - `Date.now()` integer via {@link KeyGenerators.timestamp}.
   * - `'random'`    - Short random alphanumeric string via {@link KeyGenerators.random}.
   * - `function`    - Custom generator that receives the item and returns a
   *                   `string` or `number`.
   */
  generator?:
    | 'uuid'
    | 'timestamp'
    | 'random'
    | ((item?: any) => string | number);
}
 
/**
 * Describes a per-field validation rule registered via {@link Validate}.
 *
 * @typeParam T - The entity type the rule applies to.
 */
interface ValidationRule<T = any> {
  /** Name of the field being validated. */
  field: string;
  /**
   * Returns `true` when the field value is valid.
   *
   * @param value - The current field value.
   * @param item  - The full entity instance being validated.
   */
  predicate: (value: any, item: T) => boolean;
  /** Human-readable message appended to the thrown error when validation fails. */
  message: string;
}
 
/**
 * Metadata recorded for each field decorated with {@link Index}.
 *
 * @internal
 */
interface IndexMetadata {
  /** Name of the entity field that the IDB index covers. */
  field: string;
  /** Optional IDB index parameters (e.g., `unique`). */
  options?: IDBIndexParameters;
}
 
/**
 * Options accepted by the {@link RetentionPolicy} class decorator.
 */
interface RetentionPolicyOptions {
  /**
   * Duration in seconds after which records are considered expired and eligible
   * for automatic deletion. Must be a positive integer.
   */
  seconds: number;
 
  /**
   * Whether the retention cleanup job is active for this entity.
   *
   * @default true
   */
  enabled?: boolean;
 
  /**
   * The numeric timestamp field (milliseconds since Unix epoch) used to
   * determine record age. Defaults to the internally managed
   * `__idb_createdAt` field.
   *
   * @default '__idb_createdAt'
   */
  field?: string;
}
 
/**
 * Resolved and normalised form of {@link RetentionPolicyOptions} stored in
 * entity metadata after decoration.
 *
 * @internal
 */
interface RetentionPolicyMetadata {
  /** Retention duration in seconds. */
  seconds: number;
  /** Whether the cleanup job is active. */
  enabled: boolean;
  /** The timestamp field used for age calculation. */
  field: string;
}
 
/** @internal Name of the internal creation-timestamp field. */
const INTERNAL_CREATED_AT_FIELD = '__idb_createdAt';
/** @internal Name of the internal last-updated-timestamp field. */
const INTERNAL_UPDATED_AT_FIELD = '__idb_updatedAt';
 
/**
 * Metadata associated with a `@KeyPath` or `@CompositeKeyPath` decorator.
 *
 * @internal
 */
interface KeyPathMetadata {
  /** Single field name (simple key) or array of field names (composite key). */
  fields: string | string[];
  /** Key generation and auto-increment options. */
  options?: KeyPathOptions;
}
 
// ─── Key Generators ───────────────────────────────────────────────────────────
 
/**
 * Built-in key generation utilities used by the {@link KeyPath} `generator`
 * option and available for direct use in application code.
 *
 * @example
 * ```ts
 * import { KeyGenerators } from 'idb-ts';
 *
 * const id        = KeyGenerators.uuid();      // "a1b2c3d4-..."
 * const timestamp = KeyGenerators.timestamp(); // 1696118400000
 * const random    = KeyGenerators.random();    // "xyz789abc123"
 * ```
 */
class KeyGenerators {
  /**
   * Generates a RFC 4122 UUID v4 string.
   * The implementation does not rely on any external dependency.
   *
   * @returns A UUID v4 string, e.g., `"a1b2c3d4-e5f6-4789-abcd-ef1234567890"`.
   */
  static uuid(): string {
    // Simple UUID v4 implementation without external dependencies
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
      /[xy]/g,
      function (c) {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      },
    );
  }
 
  /**
   * Returns the current Unix timestamp in milliseconds (`Date.now()`).
   *
   * @returns A numeric timestamp, e.g., `1696118400000`.
   */
  static timestamp(): number {
    return Date.now();
  }
 
  /**
   * Generates a short random alphanumeric string derived from
   * `Math.random().toString(36)`.
   *
   * @returns A random string of approximately 13 characters, e.g., `"xyz789abc123"`.
   */
  static random(): string {
    return Math.random().toString(36).substring(2, 15);
  }
}
 
// ─── Decorators ──────────────────────────────────────────────────────────────
 
/**
 * Property decorator that designates the decorated field as the primary key
 * (key path) for the entity's IndexedDB object store.
 *
 * Exactly **one** property per entity class may be annotated with `@KeyPath`.
 * For composite keys spanning multiple fields, use {@link CompositeKeyPath}
 * at the class level instead.
 *
 * @param options - Optional key generation and auto-increment configuration.
 *
 * @remarks
 * The decorator stores {@link KeyPathMetadata} via `reflect-metadata` on the
 * constructor. The `@DataClass` decorator validates at class decoration time
 * that exactly one key path is present.
 *
 * @example Single UUID key
 * ```ts
 * @DataClass()
 * class Document {
 *   @KeyPath({ generator: 'uuid' })
 *   id!: string;
 * }
 * ```
 *
 * @example Auto-increment numeric key
 * ```ts
 * @DataClass()
 * class Task {
 *   @KeyPath({ autoIncrement: true })
 *   id!: number;
 * }
 * ```
 */
function KeyPath(options?: KeyPathOptions): PropertyDecorator {
  return (target: any, propertyKey: string | symbol) => {
    const constructor = target.constructor as Function;
 
    // Track individual property keypaths for validation
    const existingKeypaths =
      Reflect.getMetadata('individual_keypaths', constructor) || [];
    existingKeypaths.push(propertyKey as string);
    Reflect.defineMetadata(
      'individual_keypaths',
      existingKeypaths,
      constructor,
    );
 
    const metadata: KeyPathMetadata = {
      fields: propertyKey as string,
      options: options,
    };
    Reflect.defineMetadata('keypath', metadata, constructor);
  };
}
 
/**
 * Class decorator that defines a **composite primary key** spanning multiple
 * fields. Use this when the entity's identity is determined by a combination
 * of fields rather than a single property.
 *
 * @param fields  - An ordered array of field names that together form the key.
 * @param options - Optional key generation configuration (note: auto-generated
 *   keys are not supported for composite keys).
 *
 * @remarks
 * Apply `@CompositeKeyPath` **before** `@DataClass` (decorators execute
 * bottom-up). `@KeyPath` must **not** also be used on the same class.
 *
 * @example
 * ```ts
 * @CompositeKeyPath(['userId', 'projectId'])
 * @DataClass()
 * class UserProject {
 *   userId!: string;
 *   projectId!: string;
 *   role!: string;
 * }
 *
 * // Read by composite key:
 * const rel = await db.UserProject.read(['user1', 'proj42']);
 * ```
 */
function CompositeKeyPath(
  fields: string[],
  options?: KeyPathOptions,
): ClassDecorator {
  return (target: Function) => {
    const metadata: KeyPathMetadata = {
      fields: fields,
      options: options,
    };
    Reflect.defineMetadata('keypath', metadata, target);
  };
}
 
/**
 * Property decorator that creates an IndexedDB index on the decorated field,
 * enabling efficient lookups via {@link EntityRepository.findByIndex} and
 * {@link EntityRepository.findOneByIndex}.
 *
 * @param options - Standard `IDBIndexParameters` (e.g., `{ unique: true }`).
 *
 * @example
 * ```ts
 * @DataClass()
 * class User {
 *   @KeyPath()
 *   id!: string;
 *
 *   @Index({ unique: true })
 *   email!: string;
 *
 *   @Index()
 *   department!: string;
 * }
 * ```
 */
function Index(options?: IDBIndexParameters): PropertyDecorator {
  return (target: Object, propertyKey: string | symbol) => {
    const constructor = target.constructor as Function;
    const existing = Reflect.getMetadata('indexes', constructor) || [];
    const nextIndexes = [
      ...existing,
      { field: propertyKey as string, options } as IndexMetadata,
    ];
    Reflect.defineMetadata('indexes', nextIndexes, constructor);
  };
}
 
/**
 * Property decorator that attaches a validation rule to the decorated field.
 * The rule is enforced on every {@link EntityRepository.create} and
 * {@link EntityRepository.update} call.
 *
 * @typeParam T - The entity class to which this rule belongs.
 * @param predicate - A function that returns `true` when the field value is
 *   valid. Receives both the field value and the full entity instance.
 * @param message   - A short, human-readable description of the constraint,
 *   appended to the thrown error on failure.
 *
 * @throws `Error` - On write operations when any rule's `predicate` returns
 *   `false`. The error message lists all failing rules in the format
 *   `field: message`, joined by `; `.
 *
 * @example
 * ```ts
 * @DataClass()
 * class User {
 *   @KeyPath()
 *   id!: string;
 *
 *   @Validate((v) => typeof v === 'string' && v.includes('@'), 'must be a valid email')
 *   email!: string;
 *
 *   @Validate((v) => typeof v === 'number' && v >= 0, 'age must be >= 0')
 *   age!: number;
 * }
 * ```
 */
function Validate<T = any>(
  predicate: (value: any, item: T) => boolean,
  message: string,
): PropertyDecorator {
  return (target: Object, propertyKey: string | symbol) => {
    const constructor = target.constructor as Function;
    const existing = Reflect.getMetadata('validators', constructor) || [];
    const nextRules = [
      ...existing,
      { field: propertyKey as string, predicate, message } as ValidationRule<T>,
    ];
    Reflect.defineMetadata('validators', nextRules, constructor);
  };
}
 
/**
 * Class decorator that configures an automatic data retention policy for
 * the entity. When one or more entities define a retention policy, the
 * {@link Database} runs a background cleanup job that periodically deletes
 * expired records.
 *
 * @param options - Retention configuration. `seconds` is required.
 *
 * @throws `Error` - At decoration time if `options.seconds` is not a positive integer.
 *
 * @remarks
 * The cleanup interval is derived from the GCD of all registered `seconds`
 * values, ensuring the job runs as infrequently as possible while still
 * honouring every policy. The job uses a cursor-based `readwrite` transaction
 * and emits debug-level log messages on each tick.
 *
 * @example
 * ```ts
 * @RetentionPolicy({ seconds: 60 * 60 * 24 * 30 }) // 30-day retention
 * @DataClass()
 * class Session {
 *   @KeyPath()
 *   id!: string;
 *   userId!: string;
 * }
 * ```
 */
function RetentionPolicy(options: RetentionPolicyOptions): ClassDecorator {
  return (target: Function) => {
    Iif (!Number.isInteger(options.seconds) || options.seconds <= 0) {
      throw new Error('RetentionPolicy.seconds must be a positive integer.');
    }
 
    const metadata: RetentionPolicyMetadata = {
      seconds: options.seconds,
      enabled: options.enabled ?? true,
      field: options.field ?? INTERNAL_CREATED_AT_FIELD,
    };
 
    Reflect.defineMetadata('retention_policy', metadata, target);
  };
}
 
/**
 * Options passed to the {@link DataClass} decorator.
 */
interface DataClassOptions {
  /**
   * Schema version number for this entity. The {@link Database} sets the
   * underlying `IDBDatabase` version to the highest version across all
   * registered entities, triggering `onupgradeneeded` when new entities are
   * added or existing ones are incremented.
   *
   * @default 1
   */
  version?: number;
}
 
/**
 * Class decorator that marks an entity class for use with {@link Database}.
 *
 * `@DataClass` must be applied **after** `@KeyPath` (or `@CompositeKeyPath`)
 * and performs the following at decoration time:
 *
 * 1. Verifies that exactly one `@KeyPath` (or `@CompositeKeyPath`) annotation
 *    is present on the class.
 * 2. Records the schema `version` in `reflect-metadata`.
 * 3. Marks the class as a valid data class (guards against passing plain
 *    classes to {@link Database.build}).
 *
 * @param options - Optional schema version configuration.
 *
 * @throws `Error` - If no `@KeyPath` / `@CompositeKeyPath` annotation is found.
 * @throws `Error` - If more than one property-level `@KeyPath` annotation is
 *   present (use `@CompositeKeyPath` for multi-field keys instead).
 *
 * @example
 * ```ts
 * @DataClass({ version: 2 })
 * class User {
 *   @KeyPath({ generator: 'uuid' })
 *   id!: string;
 *
 *   @Index({ unique: true })
 *   email!: string;
 *
 *   name!: string;
 * }
 * ```
 */
function DataClass(options: DataClassOptions = {}): ClassDecorator {
  return (target: Function) => {
    const keyPathMetadata = Reflect.getMetadata(
      'keypath',
      target,
    ) as KeyPathMetadata;
    if (!keyPathMetadata) {
      throw new Error(`No keypath field defined for the class ${target.name}.`);
    }
 
    // Check for multiple property-level @KeyPath decorators (which is invalid)
    // This is different from composite keys which are defined at class level
    const individualKeypaths =
      Reflect.getMetadata('individual_keypaths', target) || [];
    if (individualKeypaths.length > 1) {
      throw new Error(
        `Only one keypath field can be defined for the class ${target.name}.`,
      );
    }
 
    const version = options.version || 1;
    Reflect.defineMetadata('dataclass', true, target);
    Reflect.defineMetadata('version', version, target);
  };
}
 
// ─── Repository & Database Interfaces ────────────────────────────────────────
 
/**
 * The full CRUD and query surface exposed for each registered entity.
 *
 * An `EntityRepository<T>` is created automatically by {@link Database.build}
 * and is accessible as a named property on the returned database object (e.g.,
 * `db.User`, `db.Order`).
 *
 * @typeParam T - The entity type managed by this repository.
 *
 * @example
 * ```ts
 * const db = await Database.build<{ User: EntityRepository<User> }>('mydb', [User]);
 *
 * await db.User.create(new User('u1', 'Alice', 25));
 * const alice = await db.User.read('u1');
 * await db.User.delete('u1');
 * ```
 */
interface EntityRepository<T> {
  /**
   * Persists a new record.
   *
   * Key generation (if configured) and timestamp injection (`__idb_createdAt`,
   * `__idb_updatedAt`) are applied before storage. Validation rules are
   * enforced prior to the write.
   *
   * @param item - The entity instance to store.
   * @throws `Error` if validation fails or the IDB operation rejects.
   */
  create(item: T): Promise<void>;
 
  /**
   * Persists multiple records sequentially.
   * Equivalent to calling {@link EntityRepository.create} for each item.
   *
   * @param items - An array of entity instances to store.
   */
  createMany(items: T[]): Promise<void>;
 
  /**
   * Retrieves a record by its primary key.
   *
   * @param key - The primary key value. Pass an array for composite keys.
   * @returns A promise resolving to the entity, or `undefined` if not found.
   */
  read(key: string | string[] | number): Promise<T | undefined>;
 
  /**
   * Replaces an existing record with the supplied entity.
   *
   * Preserves the original `__idb_createdAt` timestamp and refreshes
   * `__idb_updatedAt`. Validation rules are enforced prior to the write.
   *
   * @param item - The updated entity instance.
   * @throws `Error` if validation fails or the IDB operation rejects.
   */
  update(item: T): Promise<void>;
 
  /**
   * Updates multiple records sequentially.
   * Equivalent to calling {@link EntityRepository.update} for each item.
   *
   * @param items - An array of updated entity instances.
   */
  updateMany(items: T[]): Promise<void>;
 
  /**
   * Removes the record identified by `key`.
   *
   * @param key - The primary key value. Pass an array for composite keys.
   */
  delete(key: string | string[] | number): Promise<void>;
 
  /**
   * Removes multiple records by their primary keys.
   *
   * @param keys - An array of primary key values.
   */
  deleteMany(keys: Array<string | string[] | number>): Promise<void>;
 
  /**
   * Removes all records that match the supplied query predicate.
   *
   * @param predicate - A callback receiving a {@link QueryBuilder} and
   *   returning the configured builder (or `void`).
   */
  deleteWhere(
    predicate: (query: QueryBuilder<T>) => QueryBuilder<T> | void,
  ): Promise<void>;
 
  /**
   * Returns all records in the store.
   *
   * @returns A promise resolving to an array of all entities.
   */
  list(): Promise<T[]>;
 
  /**
   * Returns a page of records from the store.
   *
   * @param page     - 1-based page number.
   * @param pageSize - Number of records per page.
   * @returns A promise resolving to the requested page.
   */
  listPaginated(page: number, pageSize: number): Promise<T[]>;
 
  /**
   * Returns all records whose indexed field equals `value`.
   *
   * @param indexName - The name of the IDB index to query.
   * @param value     - The index key to look up.
   * @throws `Error` if the named index does not exist.
   */
  findByIndex(indexName: string, value: any): Promise<T[]>;
 
  /**
   * Returns the first record whose indexed field equals `value`, or
   * `undefined` if none is found.
   *
   * @param indexName - The name of the IDB index to query.
   * @param value     - The index key to look up.
   * @throws `Error` if the named index does not exist.
   */
  findOneByIndex(indexName: string, value: any): Promise<T | undefined>;
 
  /**
   * Returns the total number of records in the store.
   *
   * @returns A promise resolving to the record count.
   */
  count(): Promise<number>;
 
  /**
   * Returns whether a record with the given primary key exists.
   *
   * @param key - The primary key to check.
   * @returns `true` if a matching record exists, `false` otherwise.
   */
  exists(key: string): Promise<boolean>;
 
  /**
   * Deletes **all** records from the store.
   */
  clear(): Promise<void>;
 
  /**
   * Returns a new {@link QueryBuilder} scoped to this entity's object store,
   * optionally sharing the supplied transaction.
   *
   * @returns A fresh {@link QueryBuilder} instance ready for chaining.
   */
  query(): QueryBuilder<T>;
}
 
/**
 * Exposes `commit` and `rollback` control over a multi-store IDB transaction.
 *
 * Obtained via {@link Database.beginTransaction} or provided to the callback
 * of {@link Database.transaction}.
 */
interface TransactionController {
  /**
   * Explicitly commits the transaction, waiting for all pending operations
   * to complete. Falls back gracefully when `IDBTransaction.commit` is
   * unavailable in older runtimes.
   */
  commit(): Promise<void>;
 
  /**
   * Aborts the transaction, discarding all uncommitted writes.
   * Subsequent calls are silently ignored.
   */
  rollback(): Promise<void>;
}
 
/**
 * A union of a typed repository map `T` and {@link TransactionController}.
 * The object returned by {@link Database.beginTransaction} and passed to
 * the {@link Database.transaction} callback implements this type.
 *
 * @typeParam T - A `Record` mapping entity names to their `EntityRepository`.
 */
type TransactionalDatabase<T extends Record<string, EntityRepository<any>>> =
  T & TransactionController;
 
/**
 * The object type returned by {@link Database.build}.
 * Extends the base {@link Database} class with dynamically generated
 * `EntityRepository` properties keyed by entity name.
 *
 * @typeParam T - A `Record` mapping entity class names to `EntityRepository` types.
 *
 * @example
 * ```ts
 * type MyDB = DatabaseWithRepositories<{
 *   User: EntityRepository<User>;
 *   Order: EntityRepository<Order>;
 * }>;
 *
 * const db: MyDB = await Database.build<{
 *   User: EntityRepository<User>;
 *   Order: EntityRepository<Order>;
 * }>('mydb', [User, Order]);
 * ```
 */
type DatabaseWithRepositories<T extends Record<string, any>> = Database & T;
 
// ─── Database ────────────────────────────────────────────────────────────────
 
/**
 * Central access point for an IndexedDB database managed by **idb-ts**.
 *
 * A `Database` instance owns the IDB connection, maintains entity
 * repositories, and runs retention-cleanup background jobs. Always obtain
 * instances through the async factory {@link Database.build} - the constructor
 * is private.
 *
 * @remarks
 * **Schema versioning.** The effective database version is the highest
 * `version` value across all registered `@DataClass` entities. On each
 * `onupgradeneeded` event, only stores whose `version` exceeds the previous
 * database version are created or updated, so additive schema evolution is
 * handled automatically.
 *
 * **Retention cleanup.** When entities declare `@RetentionPolicy`, a periodic
 * `setInterval` job is started after the database opens. The interval is the
 * GCD of all configured retention periods (in milliseconds), ensuring every
 * policy is evaluated at the right frequency with a single timer.
 *
 * **Repository access.** After `build` resolves, each registered entity is
 * accessible as a named property on the returned object:
 * ```ts
 * const db = await Database.build<{ User: EntityRepository<User> }>('mydb', [User]);
 * await db.User.create(new User('u1', 'Alice'));
 * ```
 *
 * @example
 * ```ts
 * const db = await Database.build<{
 *   User:  EntityRepository<User>;
 *   Order: EntityRepository<Order>;
 * }>('shop', [User, Order]);
 *
 * await db.User.create(new User('u1', 'Alice', 30));
 * const alice = await db.User.read('u1');
 * db.close();
 * ```
 */
class Database {
  private dbName: string;
  private classes: Function[];
  private db: IDBDatabase | null = null;
  private entityRepositories: Map<string, any> = new Map();
  private dbVersion: number;
  private retentionTimer: ReturnType<typeof setInterval> | null = null;
  private retentionCleanupRunning = false;
  private retentionPolicies: Array<{
    className: string;
    storeName: string;
    policy: RetentionPolicyMetadata;
  }>;
 
  /** @internal Use {@link Database.build} to create instances. */
  private constructor(dbName: string, classes: Function[]) {
    this.dbName = dbName;
    if (!classes.every((cls) => Reflect.getMetadata('dataclass', cls))) {
      throw new Error('All classes should be decorated with @DataClass.');
    }
    this.classes = classes;
    this.dbVersion = this.calculateDatabaseVersion();
    this.retentionPolicies = this.classes
      .map((cls) => {
        const policy = Reflect.getMetadata('retention_policy', cls) as
          | RetentionPolicyMetadata
          | undefined;
        if (!policy?.enabled) {
          return null;
        }
 
        return {
          className: cls.name,
          storeName: cls.name.toLowerCase(),
          policy,
        };
      })
      .filter(
        (
          policy,
        ): policy is {
          className: string;
          storeName: string;
          policy: RetentionPolicyMetadata;
        } => policy !== null,
      );
  }
 
  /**
   * Derives the IDB database version from the highest `version` annotation
   * across all registered entity classes.
   *
   * @returns The calculated database version number.
   * @internal
   */
  private calculateDatabaseVersion(): number {
    // Calculate the database version based on the highest schema version
    const versions = this.classes.map(
      (cls) => Reflect.getMetadata('version', cls) || 1,
    );
    return Math.max(...versions);
  }
 
  /**
   * Creates and initialises a new {@link Database} instance, opening the
   * underlying IndexedDB database and generating entity repositories.
   *
   * This is the **only** public way to obtain a `Database` instance.
   *
   * @typeParam T - A `Record` mapping entity names to their `EntityRepository`
   *   types, used to type the returned object's named repository properties.
   * @param dbName  - The name passed to `indexedDB.open`.
   * @param classes - The `@DataClass`-decorated entity constructors to register.
   *
   * @returns A promise resolving to a fully initialised
   *   {@link DatabaseWithRepositories} instance.
   *
   * @throws `Error` - If any class is not decorated with `@DataClass`.
   * @throws `IDBRequest` error - If the underlying `indexedDB.open` call fails.
   *
   * @example
   * ```ts
   * const db = await Database.build<{
   *   User:  EntityRepository<User>;
   *   Order: EntityRepository<Order>;
   * }>('shop', [User, Order]);
   * ```
   */
  public static async build<T extends Record<string, EntityRepository<any>>>(
    dbName: string,
    classes: Function[],
  ): Promise<DatabaseWithRepositories<T>> {
    const instance = new Database(dbName, classes) as any;
    await instance.initDB();
    instance.generateEntityRepositories();
    return instance as DatabaseWithRepositories<T>;
  }
 
  /** @internal */
  private async initDB(): Promise<void> {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.dbVersion);
 
      request.onupgradeneeded = (event) => {
        const db = request.result;
        const oldVersion = event.oldVersion;
        const newVersion = event.newVersion || this.dbVersion;
 
        console.debug(
          `Database upgrade from version ${oldVersion} to ${newVersion}`,
        );
 
        // Handle schema evolution based on versions
        this.classes.forEach((cls) => {
          const keyPathMetadata = Reflect.getMetadata(
            'keypath',
            cls,
          ) as KeyPathMetadata;
          const indexFields = Reflect.getMetadata('indexes', cls) || [];
          const classVersion = Reflect.getMetadata('version', cls) || 1;
 
          const storeName = cls.name.toLowerCase();
 
          // Only create/update stores for classes whose version is greater than the old DB version
          Eif (classVersion > oldVersion) {
            if (!db.objectStoreNames.contains(storeName)) {
              console.debug(
                `Creating object store: ${storeName} (version ${classVersion})`,
              );
 
              // Determine store options based on keypath metadata
              const storeOptions: IDBObjectStoreParameters = {};
 
              Eif (keyPathMetadata) {
                storeOptions.keyPath = keyPathMetadata.fields;
 
                // Handle auto-increment option
                if (keyPathMetadata.options?.autoIncrement) {
                  storeOptions.autoIncrement = true;
                }
              }
 
              const store = db.createObjectStore(storeName, storeOptions);
 
              indexFields.forEach((indexField: string | IndexMetadata) => {
                const indexName =
                  typeof indexField === 'string'
                    ? indexField
                    : indexField.field;
                const indexOptions =
                  typeof indexField === 'string'
                    ? { unique: false }
                    : (indexField.options ?? { unique: false });
 
                Eif (!store.indexNames.contains(indexName)) {
                  store.createIndex(indexName, indexName, indexOptions);
                }
              });
            } else E{
              // Store exists, check if we need to update indexes
              console.debug(
                `Updating object store: ${storeName} (version ${classVersion})`,
              );
              const transaction = request.transaction;
              if (transaction) {
                const store = transaction.objectStore(storeName);
 
                indexFields.forEach((indexField: string | IndexMetadata) => {
                  const indexName =
                    typeof indexField === 'string'
                      ? indexField
                      : indexField.field;
                  const indexOptions =
                    typeof indexField === 'string'
                      ? { unique: false }
                      : (indexField.options ?? { unique: false });
 
                  if (!store.indexNames.contains(indexName)) {
                    console.debug(`Adding index: ${indexName} to ${storeName}`);
                    store.createIndex(indexName, indexName, indexOptions);
                  }
                });
              }
            }
          }
        });
      };
 
      request.onsuccess = () => {
        this.db = request.result;
        console.debug(
          `Database initialized (version ${this.dbVersion}) with object stores for: ${this.classes.map((cls) => `${cls.name}(v${Reflect.getMetadata('version', cls) || 1})`).join(', ')}`,
        );
        this.startRetentionCleanup();
        resolve();
      };
 
      request.onerror = () => {
        console.error('Error initializing database:', request.error);
        reject(request.error);
      };
    });
  }
 
  /** @internal */
  private generateEntityRepositories(): void {
    this.classes.forEach((cls) => {
      const entityName = cls.name;
      const repository = this.createEntityRepository(cls);
 
      // repo name, internal use
      this.entityRepositories.set(entityName, repository);
 
      // Dynamically add the repository as a property on the database instance
      Object.defineProperty(this, entityName, {
        value: repository,
        writable: false,
        enumerable: true,
        configurable: false,
      });
    });
  }
 
  /**
   * Calculates the setInterval period for the retention cleanup job as the
   * GCD of all registered policy `seconds` values, converted to milliseconds.
   *
   * @returns The interval in milliseconds, or `undefined` if no retention
   *   policies are registered.
   * @internal
   */
  private calculateRetentionCleanupIntervalMs(): number | undefined {
    if (!this.retentionPolicies.length) {
      return undefined;
    }
 
    const gcd = (left: number, right: number): number => {
      let a = left;
      let b = right;
      while (b !== 0) {
        const remainder = a % b;
        a = b;
        b = remainder;
      }
      return Math.abs(a);
    };
 
    const seconds = this.retentionPolicies.map(({ policy }) => policy.seconds);
    return (
      seconds.reduce((accumulator, value) => gcd(accumulator, value)) * 1000
    );
  }
 
  /** @internal */
  private startRetentionCleanup(): void {
    const cleanupIntervalMs = this.calculateRetentionCleanupIntervalMs();
    if (!cleanupIntervalMs || !this.db || this.retentionTimer) {
      return;
    }
 
    console.debug(
      `Retention cleanup enabled for ${this.retentionPolicies.length} entities every ${cleanupIntervalMs}ms`,
    );
    void this.runRetentionCleanup();
    this.retentionTimer = setInterval(() => {
      void this.runRetentionCleanup();
    }, cleanupIntervalMs);
  }
 
  /** @internal */
  private async runRetentionCleanup(): Promise<void> {
    Iif (
      !this.db ||
      this.retentionCleanupRunning ||
      !this.retentionPolicies.length
    ) {
      return;
    }
 
    this.retentionCleanupRunning = true;
    try {
      console.debug('Retention cleanup tick started');
      for (const { storeName, className, policy } of this.retentionPolicies) {
        await this.cleanupExpiredRecords(storeName, className, policy);
      }
      console.debug('Retention cleanup tick finished');
    } finally {
      this.retentionCleanupRunning = false;
    }
  }
 
  /** @internal */
  private cleanupExpiredRecords(
    storeName: string,
    className: string,
    policy: RetentionPolicyMetadata,
  ): Promise<void> {
    Iif (!this.db) {
      return Promise.resolve();
    }
 
    return new Promise((resolve, reject) => {
      try {
        const transaction = this.db!.transaction(storeName, 'readwrite');
        const store = transaction.objectStore(storeName);
        const cutoff = Date.now() - policy.seconds * 1000;
        const request = store.openCursor();
 
        request.onsuccess = () => {
          const cursor = request.result;
          if (!cursor) {
            return;
          }
 
          const value = cursor.value as Record<string, any>;
          const timestamp = value?.[policy.field];
          console.debug(
            `Retention cleanup inspecting ${className}.${policy.field}:`,
            timestamp,
            'cutoff:',
            cutoff,
          );
          if (typeof timestamp === 'number' && timestamp <= cutoff) {
            const deleteRequest = cursor.delete();
            deleteRequest.onsuccess = () => {
              console.debug(
                `Retention cleanup removed expired record from ${className}`,
              );
              cursor.continue();
            };
            deleteRequest.onerror = () =>
              reject(
                deleteRequest.error ??
                  new Error(`Retention cleanup delete failed for ${className}`),
              );
            return;
          }
 
          cursor.continue();
        };
 
        transaction.oncomplete = () => resolve();
        transaction.onerror = () =>
          reject(
            transaction.error ??
              new Error(`Retention cleanup failed for ${className}`),
          );
        transaction.onabort = () =>
          reject(
            transaction.error ??
              new Error(`Retention cleanup aborted for ${className}`),
          );
      } catch (error) {
        reject(error);
      }
    });
  }
 
  /** @internal */
  private createEntityRepository<T>(
    cls: Function,
    transaction?: IDBTransaction,
  ): EntityRepository<T> {
    const self = this;
    const creationTimestampField = INTERNAL_CREATED_AT_FIELD;
    const updateTimestampField = INTERNAL_UPDATED_AT_FIELD;
    const validators = (Reflect.getMetadata('validators', cls) ||
      []) as ValidationRule<T>[];
 
    const validateItem = (item: T): void => {
      const failures: string[] = [];
 
      validators.forEach((rule) => {
        const value = (item as any)[rule.field];
        let valid = false;
 
        try {
          valid = rule.predicate(value, item);
        } catch {
          valid = false;
        }
 
        if (!valid) {
          failures.push(`${rule.field}: ${rule.message}`);
        }
      });
 
      if (failures.length) {
        throw new Error(
          `Validation failed for ${cls.name}: ${failures.join('; ')}`,
        );
      }
    };
 
    const generateKey = (item: T): string | number | undefined => {
      const keyPathMetadata = Reflect.getMetadata(
        'keypath',
        cls,
      ) as KeyPathMetadata;
      Iif (!keyPathMetadata?.options?.generator) return undefined;
 
      const generator = keyPathMetadata.options.generator;
 
      if (typeof generator === 'function') {
        return generator(item);
      }
 
      switch (generator) {
        case 'uuid':
          return KeyGenerators.uuid();
        case 'timestamp':
          return KeyGenerators.timestamp();
        case 'random':
          return KeyGenerators.random();
        default:
          return undefined;
      }
    };
 
    const applyTimestampFields = (item: T, existingItem?: T): void => {
      const now = Date.now();
      const existingCreationValue = existingItem
        ? (existingItem as any)[creationTimestampField]
        : undefined;
 
      (item as any)[creationTimestampField] =
        existingCreationValue !== undefined ? existingCreationValue : now;
      (item as any)[updateTimestampField] = now;
    };
 
    const readExistingItem = (
      store: IDBObjectStore,
      key: string | string[] | number,
    ): Promise<T | undefined> => {
      return new Promise<T | undefined>((resolve, reject) => {
        const request = store.get(key);
        request.onsuccess = () => resolve(request.result as T | undefined);
        request.onerror = () => reject(request.error);
      });
    };
 
    const createStoredItem = (
      store: IDBObjectStore,
      item: T,
    ): Promise<void> => {
      return new Promise<void>((resolve, reject) => {
        const request = store.add(item);
        request.onsuccess = () => resolve();
        request.onerror = () => reject(request.error);
      });
    };
 
    const updateStoredItem = async (
      store: IDBObjectStore,
      item: T,
    ): Promise<void> => {
      const key = extractKey(item);
 
      let existingItem: T | undefined;
      Eif (key !== undefined && key !== null) {
        existingItem = await readExistingItem(store, key);
      }
 
      applyTimestampFields(item, existingItem);
 
      await new Promise<void>((resolve, reject) => {
        const request = store.put(item);
        request.onsuccess = () => resolve();
        request.onerror = () => reject(request.error);
      });
    };
 
    const deleteStoredItem = (
      store: IDBObjectStore,
      key: string | string[] | number,
    ): Promise<void> => {
      return new Promise<void>((resolve, reject) => {
        const request = store.delete(key);
        request.onsuccess = () => resolve();
        request.onerror = () => reject(request.error);
      });
    };
 
    // Helper function to extract key from item
    const extractKey = (item: T): any => {
      const keyPathMetadata = Reflect.getMetadata(
        'keypath',
        cls,
      ) as KeyPathMetadata;
      Iif (!keyPathMetadata) return undefined;
 
      const fields = keyPathMetadata.fields;
 
      if (Array.isArray(fields)) {
        // Composite key
        return fields.map((field) => (item as any)[field]);
      } else {
        // Single field key
        return (item as any)[fields];
      }
    };
 
    // Helper function to set key on item
    const setKey = (item: T, key: string | number): void => {
      const keyPathMetadata = Reflect.getMetadata(
        'keypath',
        cls,
      ) as KeyPathMetadata;
      Iif (!keyPathMetadata) return;
 
      const fields = keyPathMetadata.fields;
 
      Eif (typeof fields === 'string') {
        (item as any)[fields] = key;
      }
      // Note: Composite keys cannot be auto-generated in this simple implementation
    };
 
    return {
      query(): QueryBuilder<T> {
        Iif (!self.db) throw new Error('Database not initialized.');
        const storeName = cls.name.toLowerCase();
        return new QueryBuilder<T>(self.db, storeName, transaction);
      },
 
      create: async (item: T): Promise<void> => {
        // Generate key if needed
        const keyPathMetadata = Reflect.getMetadata(
          'keypath',
          cls,
        ) as KeyPathMetadata;
        if (
          keyPathMetadata?.options?.generator &&
          !keyPathMetadata.options.autoIncrement
        ) {
          const currentKey = extractKey(item);
          Eif (
            currentKey === undefined ||
            currentKey === null ||
            currentKey === ''
          ) {
            const generatedKey = generateKey(item);
            Eif (generatedKey !== undefined) {
              setKey(item, generatedKey);
            }
          }
        }
 
        validateItem(item);
        applyTimestampFields(item);
 
        return this.performOperation(
          cls.name,
          'readwrite',
          (store) => {
            return createStoredItem(store, item).then(() => {
              console.debug(`Item added to ${cls.name}:`, item);
            });
          },
          transaction,
        );
      },
 
      createMany: async (items: T[]): Promise<void> => {
        const repository = this.createEntityRepository<T>(cls, transaction);
        for (const item of items) {
          await repository.create(item);
        }
      },
 
      read: async (key: string | string[] | number): Promise<T | undefined> => {
        return this.performOperation(
          cls.name,
          'readonly',
          (store) => {
            const request = store.get(key);
            return new Promise<T | undefined>((resolve, reject) => {
              request.onsuccess = () => {
                console.debug(`Item read from ${cls.name}:`, request.result);
                resolve(request.result as T | undefined);
              };
              request.onerror = () => reject(request.error);
            });
          },
          transaction,
        );
      },
 
      update: async (item: T): Promise<void> => {
        validateItem(item);
 
        return this.performOperation(
          cls.name,
          'readwrite',
          (store) => {
            return updateStoredItem(store, item).then(() => {
              console.debug(`Item updated in ${cls.name}:`, item);
            });
          },
          transaction,
        );
      },
 
      updateMany: async (items: T[]): Promise<void> => {
        const repository = this.createEntityRepository<T>(cls, transaction);
        for (const item of items) {
          await repository.update(item);
        }
      },
 
      delete: async (key: string | string[] | number): Promise<void> => {
        return this.performOperation(
          cls.name,
          'readwrite',
          (store) => {
            return deleteStoredItem(store, key).then(() => {
              console.debug(`Item deleted from ${cls.name}:`, key);
            });
          },
          transaction,
        );
      },
 
      deleteMany: async (
        keys: Array<string | string[] | number>,
      ): Promise<void> => {
        const repository = this.createEntityRepository<T>(cls, transaction);
        for (const key of keys) {
          await repository.delete(key);
        }
      },
 
      deleteWhere: async (
        predicate: (query: QueryBuilder<T>) => QueryBuilder<T> | void,
      ): Promise<void> => {
        const repository = this.createEntityRepository<T>(cls, transaction);
        const query = repository.query();
        const resolvedQuery = predicate(query) ?? query;
        const matches = await resolvedQuery.execute();
        const keys = matches
          .map((item) => extractKey(item))
          .filter(
            (key): key is string | string[] | number =>
              key !== undefined && key !== null,
          );
 
        await repository.deleteMany(keys);
      },
 
      list: async (): Promise<T[]> => {
        return this.performOperation(
          cls.name,
          'readonly',
          (store) => {
            const request = store.getAll();
            return new Promise<T[]>((resolve, reject) => {
              request.onsuccess = () => {
                console.debug(`All items from ${cls.name}:`, request.result);
                resolve(request.result as T[]);
              };
              request.onerror = () => reject(request.error);
            });
          },
          transaction,
        );
      },
 
      listPaginated: async (page: number, pageSize: number): Promise<T[]> => {
        return this.performOperation(
          cls.name,
          'readonly',
          (store) => {
            const request = store.getAll();
            return new Promise<T[]>((resolve, reject) => {
              request.onsuccess = () => {
                const items = request.result as T[];
                const paginatedItems = items.slice(
                  (page - 1) * pageSize,
                  page * pageSize,
                );
                console.debug(
                  `Paginated items from ${cls.name}:`,
                  paginatedItems,
                );
                resolve(paginatedItems);
              };
              request.onerror = () => reject(request.error);
            });
          },
          transaction,
        );
      },
 
      findByIndex: async (indexName: string, value: any): Promise<T[]> => {
        return this.performOperation(
          cls.name,
          'readonly',
          (store) => {
            if (!store.indexNames.contains(indexName)) {
              throw new Error(
                `Index '${indexName}' does not exist on ${cls.name}`,
              );
            }
 
            const index = store.index(indexName);
            const request = index.getAll(value);
            return new Promise<T[]>((resolve, reject) => {
              request.onsuccess = () => {
                console.debug(
                  `Items found by index ${indexName} with value ${value}:`,
                  request.result,
                );
                resolve(request.result as T[]);
              };
              request.onerror = () => reject(request.error);
            });
          },
          transaction,
        );
      },
 
      findOneByIndex: async (
        indexName: string,
        value: any,
      ): Promise<T | undefined> => {
        return this.performOperation(
          cls.name,
          'readonly',
          (store) => {
            if (!store.indexNames.contains(indexName)) {
              throw new Error(
                `Index '${indexName}' does not exist on ${cls.name}`,
              );
            }
 
            const index = store.index(indexName);
            const request = index.get(value);
            return new Promise<T | undefined>((resolve, reject) => {
              request.onsuccess = () => {
                console.debug(
                  `Item found by index ${indexName} with value ${value}:`,
                  request.result,
                );
                resolve(request.result as T | undefined);
              };
              request.onerror = () => reject(request.error);
            });
          },
          transaction,
        );
      },
 
      count: async (): Promise<number> => {
        return this.performOperation(
          cls.name,
          'readonly',
          (store) => {
            const request = store.count();
            return new Promise<number>((resolve, reject) => {
              request.onsuccess = () => {
                console.debug(`Count for ${cls.name}:`, request.result);
                resolve(request.result);
              };
              request.onerror = () => reject(request.error);
            });
          },
          transaction,
        );
      },
 
      exists: async (key: string): Promise<boolean> => {
        return this.performOperation(
          cls.name,
          'readonly',
          (store) => {
            const request = store.count(key);
            return new Promise<boolean>((resolve, reject) => {
              request.onsuccess = () => {
                const exists = request.result > 0;
                console.debug(
                  `Exists check for ${cls.name} with key ${key}:`,
                  exists,
                );
                resolve(exists);
              };
              request.onerror = () => reject(request.error);
            });
          },
          transaction,
        );
      },
 
      clear: async (): Promise<void> => {
        return this.performOperation(
          cls.name,
          'readwrite',
          (store) => {
            const request = store.clear();
            return new Promise<void>((resolve, reject) => {
              request.onsuccess = () => {
                console.debug(`Cleared all items from ${cls.name}`);
                resolve();
              };
              request.onerror = () => reject(request.error);
            });
          },
          transaction,
        );
      },
    };
  }
 
  /** @internal */
  private async performOperation<R>(
    className: string,
    mode: IDBTransactionMode,
    operation: (store: IDBObjectStore) => Promise<R>,
    transaction?: IDBTransaction,
  ): Promise<R> {
    if (!this.db && !transaction) {
      throw new Error('Database not initialized.');
    }
 
    const storeName = className.toLowerCase();
    const activeTransaction =
      transaction ?? this.db!.transaction(storeName, mode);
    const store = activeTransaction.objectStore(storeName);
 
    return operation(store);
  }
 
  /** @internal */
  private createTransactionHandle(
    entityNames: string[],
    mode: IDBTransactionMode,
  ): TransactionalDatabase<Record<string, EntityRepository<any>>> {
    Iif (!this.db) {
      throw new Error('Database not initialized.');
    }
 
    const uniqueEntityNames = [...new Set(entityNames)];
    const storeNames = uniqueEntityNames.map((entityName) => {
      const entityClass = this.classes.find((cls) => cls.name === entityName);
      Iif (!entityClass) {
        throw new Error(
          `Entity '${entityName}' is not registered in ${this.dbName}.`,
        );
      }
 
      return entityClass.name.toLowerCase();
    });
 
    const nativeTransaction = this.db.transaction(storeNames, mode);
    let rollbackRequested = false;
 
    const completion = new Promise<void>((resolve, reject) => {
      nativeTransaction.oncomplete = () => resolve();
      nativeTransaction.onabort = () => {
        Eif (rollbackRequested) {
          resolve();
          return;
        }
 
        reject(nativeTransaction.error ?? new Error('Transaction aborted.'));
      };
      nativeTransaction.onerror = () => {
        if (rollbackRequested) {
          resolve();
          return;
        }
 
        reject(nativeTransaction.error ?? new Error('Transaction failed.'));
      };
    });
 
    const handle = {} as TransactionalDatabase<
      Record<string, EntityRepository<any>>
    >;
    uniqueEntityNames.forEach((entityName) => {
      const entityClass = this.classes.find((cls) => cls.name === entityName);
      Eif (entityClass) {
        handle[entityName] = this.createEntityRepository(
          entityClass,
          nativeTransaction,
        );
      }
    });
 
    handle.commit = async () => {
      Eif (typeof nativeTransaction.commit === 'function') {
        nativeTransaction.commit();
      }
 
      await completion;
    };
 
    handle.rollback = async () => {
      rollbackRequested = true;
      try {
        nativeTransaction.abort();
      } catch {
        // Ignore abort errors after the transaction has already settled.
      }
 
      await completion.catch(() => undefined);
    };
 
    return handle;
  }
 
  /**
   * Opens a multi-store IDB transaction and returns a
   * {@link TransactionalDatabase} with per-entity repositories that share the
   * underlying `IDBTransaction`.
   *
   * Use the returned handle's `commit()` and `rollback()` methods to finalise
   * or discard the transaction. For automatic commit/rollback, prefer the
   * callback-based {@link Database.transaction} method.
   *
   * @param entityNames - Names of the entity classes whose stores will be
   *   enrolled in the transaction.
   * @param mode        - IDB transaction mode (`'readonly'` or `'readwrite'`).
   *   Defaults to `'readwrite'`.
   *
   * @returns A promise resolving to a {@link TransactionalDatabase} handle.
   *
   * @throws `Error` if any name in `entityNames` is not registered.
   *
   * @example
   * ```ts
   * const tx = await db.beginTransaction(['User', 'Order']);
   * try {
   *   await tx.User.create(user);
   *   await tx.Order.create(order);
   *   await tx.commit();
   * } catch (e) {
   *   await tx.rollback();
   * }
   * ```
   */
  public async beginTransaction(
    entityNames: string[],
    mode: IDBTransactionMode = 'readwrite',
  ): Promise<TransactionalDatabase<Record<string, EntityRepository<any>>>> {
    return this.createTransactionHandle(entityNames, mode);
  }
 
  /**
   * Executes `callback` within a single `readwrite` IDB transaction that spans
   * **all** registered entities. Commits automatically on success; rolls back
   * and rethrows on any error.
   *
   * @typeParam T - The type of the value returned by `callback`.
   * @param callback - An async or synchronous function receiving the
   *   {@link TransactionalDatabase} handle. The callback's return value is
   *   forwarded to the caller.
   *
   * @returns A promise resolving to the value returned by `callback`.
   *
   * @throws Re-throws any error thrown by `callback` after rolling back.
   *
   * @example
   * ```ts
   * await db.transaction(async (tx) => {
   *   await tx.User.create(user);
   *   await tx.Order.create(order);
   *   await tx.OrderItem.create(item);
   * });
   * ```
   */
  public async transaction<T>(
    callback: (
      tx: TransactionalDatabase<Record<string, EntityRepository<any>>>,
    ) => Promise<T> | T,
  ): Promise<T> {
    const tx = this.createTransactionHandle(
      this.classes.map((cls) => cls.name),
      'readwrite',
    );
 
    try {
      const result = await callback(tx);
      await tx.commit();
      return result;
    } catch (error) {
      await tx.rollback();
      throw error;
    }
  }
 
  /**
   * Closes the underlying IDB connection and stops the retention cleanup timer.
   * The instance must not be used after calling this method.
   *
   * @example
   * ```ts
   * db.close();
   * ```
   */
  close(): void {
    if (this.retentionTimer) {
      clearInterval(this.retentionTimer);
      this.retentionTimer = null;
    }
 
    Eif (this.db) {
      this.db.close();
      this.db = null;
    }
  }
 
  /**
   * Returns the names of all entity classes registered with this database.
   *
   * @returns An array of entity class name strings.
   */
  getAvailableEntities(): string[] {
    return Array.from(this.entityRepositories.keys());
  }
 
  /**
   * Returns the current IDB database version, derived from the highest
   * `version` annotation across all registered entities.
   *
   * @returns The database version number.
   */
  getDatabaseVersion(): number {
    return this.dbVersion;
  }
 
  /**
   * Returns a `Map` of each registered entity name to its configured schema
   * version.
   *
   * @returns A `Map<string, number>` where keys are entity class names and
   *   values are version numbers.
   */
  getEntityVersions(): Map<string, number> {
    const versions = new Map<string, number>();
    this.classes.forEach((cls) => {
      const version = Reflect.getMetadata('version', cls) || 1;
      versions.set(cls.name, version);
    });
    return versions;
  }
 
  /**
   * Returns the schema version of a single registered entity.
   *
   * @param entityName - The class name of the entity to look up.
   * @returns The entity's version number, or `undefined` if not registered.
   */
  getEntityVersion(entityName: string): number | undefined {
    const cls = this.classes.find((c) => c.name === entityName);
    return cls ? Reflect.getMetadata('version', cls) || 1 : undefined;
  }
}
 
export {
  Database,
  KeyPath,
  CompositeKeyPath,
  DataClass,
  Index,
  Validate,
  RetentionPolicy,
  EntityRepository,
  KeyGenerators,
};
export type {
  DatabaseWithRepositories,
  DataClassOptions,
  KeyPathOptions,
  KeyPathMetadata,
  RetentionPolicyOptions,
  RetentionPolicyMetadata,
};