File size: 32,093 Bytes
f91a684 | 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 | import { getActivityDateKey } from './activityDates';
export const AUTH_TOKEN_KEY = 'ryp_auth_token';
const LOCAL_AUTH_TOKEN_PREFIX = 'local-demo:';
const LOCAL_AUTH_USERS_KEY = 'ryp_local_users';
export type AuthUser = {
id: string;
email: string;
displayName: string;
photoURL?: string;
createdAt: string;
currentStreak: number;
longestStreak: number;
coins: number;
};
export type CoinTransaction = {
id: string;
userId: string;
amount: number;
source: string;
category: string;
createdAt: string;
};
export type ProgressLeaderboardEntry = {
id: string;
displayName: string;
solvedCount: number;
currentStreak: number;
weeklySolved: number;
coins: number;
score: number;
rank: number;
isCurrentUser: boolean;
codingStreak?: number;
languageStats?: Record<string, number>;
};
export type UserProgressStats = {
solvedQuestionIds: string[];
dailyActivity: Record<string, number>;
dailyActivityBreakdown?: Record<string, Record<string, number>>;
solvedCount: number;
activeDays: number;
weeklySolved: number;
leaderboard: ProgressLeaderboardEntry[];
codingLeaderboard: ProgressLeaderboardEntry[];
codingSolvedCount: number;
};
type StoredLocalUser = AuthUser & {
password: string;
lastActiveAt?: string;
streakTimeZone?: string;
solvedQuestionIds?: string[];
dailyActivity?: Record<string, number>;
dailyActivityBreakdown?: Record<string, Record<string, number>>;
languageStats?: Record<string, number>;
purchasedItemIds?: number[];
};
function apiUrl(path: string): string {
const base = (
import.meta.env.VITE_API_BASE as string | undefined
)
?.trim()
.replace(/\/$/, '') ?? '';
const p = path.startsWith('/') ? path : `/${path}`;
return `${base}${p}`;
}
function clientTimeZone(): string | null {
try {
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone?.trim();
return timeZone || null;
} catch {
return null;
}
}
function isLocalDevOrigin() {
if (typeof window === 'undefined') {
return false;
}
const host = window.location.hostname;
return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
}
function shouldUseLocalAuthFallback(error: unknown) {
return (
isLocalDevOrigin() &&
error instanceof Error &&
error.message.startsWith('Cannot reach server')
);
}
function loadLocalUsers(): StoredLocalUser[] {
if (typeof window === 'undefined') {
return [];
}
const raw = window.localStorage.getItem(LOCAL_AUTH_USERS_KEY);
if (!raw) {
return [];
}
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function saveLocalUsers(users: StoredLocalUser[]) {
if (typeof window === 'undefined') {
return;
}
window.localStorage.setItem(LOCAL_AUTH_USERS_KEY, JSON.stringify(users));
}
function normalizeEmail(email: string) {
return email.trim().toLowerCase();
}
function createLocalUserId() {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return `local-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
function createLocalToken(userId: string) {
return `${LOCAL_AUTH_TOKEN_PREFIX}${userId}`;
}
function isLocalToken(token: string) {
return token.startsWith(LOCAL_AUTH_TOKEN_PREFIX);
}
function toAuthUser(user: StoredLocalUser): AuthUser {
const normalizedUser = normalizeLocalUser(user);
const { password: _password, lastActiveAt: _lastActiveAt, streakTimeZone: _streakTimeZone, solvedQuestionIds: _solvedQuestionIds, dailyActivity: _dailyActivity, purchasedItemIds: _purchasedItemIds, ...safeUser } = normalizedUser;
return {
...safeUser,
currentStreak: visibleLocalCurrentStreak(normalizedUser),
};
}
function findLocalUserByToken(token: string) {
if (!isLocalToken(token)) {
return null;
}
const userId = token.slice(LOCAL_AUTH_TOKEN_PREFIX.length);
return loadLocalUsers().find((user) => user.id === userId) ?? null;
}
function registerLocalUser(
email: string,
password: string,
displayName: string,
): { token: string; user: AuthUser } {
const users = loadLocalUsers();
const normalizedEmail = normalizeEmail(email);
if (users.some((user) => normalizeEmail(user.email) === normalizedEmail)) {
throw new Error('An account with this email already exists.');
}
const newUser: StoredLocalUser = {
id: createLocalUserId(),
email: normalizedEmail,
password,
displayName: displayName.trim(),
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString(),
currentStreak: 1,
longestStreak: 1,
coins: 0,
streakTimeZone: clientTimeZone() ?? 'UTC',
solvedQuestionIds: [],
dailyActivity: {},
purchasedItemIds: [],
};
users.push(newUser);
saveLocalUsers(users);
return {
token: createLocalToken(newUser.id),
user: toAuthUser(newUser),
};
}
function loginLocalUser(email: string, password: string): { token: string; user: AuthUser } {
const normalizedEmail = normalizeEmail(email);
const users = loadLocalUsers();
const userIndex = users.findIndex(
(candidate) =>
normalizeEmail(candidate.email) === normalizedEmail && candidate.password === password,
);
if (userIndex === -1) {
throw new Error('Invalid email or password.');
}
const user = normalizeLocalUser(users[userIndex]);
touchLocalStreak(user, new Date());
users[userIndex] = user;
saveLocalUsers(users);
return {
token: createLocalToken(user.id),
user: toAuthUser(user),
};
}
function updateLocalUser(
token: string,
data: { displayName?: string; oldPassword?: string; newPassword?: string },
): { user: AuthUser } {
const users = loadLocalUsers();
const userId = token.slice(LOCAL_AUTH_TOKEN_PREFIX.length);
const userIndex = users.findIndex((candidate) => candidate.id === userId);
if (userIndex === -1) {
throw new Error('Not authenticated');
}
const user = users[userIndex];
if (data.newPassword) {
if (!data.oldPassword || data.oldPassword !== user.password) {
throw new Error('Current password is incorrect.');
}
user.password = data.newPassword;
}
if (data.displayName?.trim()) {
user.displayName = data.displayName.trim();
}
users[userIndex] = user;
saveLocalUsers(users);
return { user: toAuthUser(user) };
}
function updateLocalCoins(token: string, amount: number): { user: AuthUser } {
const users = loadLocalUsers();
const userId = token.slice(LOCAL_AUTH_TOKEN_PREFIX.length);
const userIndex = users.findIndex((candidate) => candidate.id === userId);
if (userIndex === -1) {
throw new Error('Not authenticated');
}
const user = users[userIndex];
user.coins = Math.max(0, (user.coins || 0) + amount);
users[userIndex] = user;
saveLocalUsers(users);
return { user: toAuthUser(user) };
}
function normalizeLocalSolvedQuestionIds(ids: string[] | undefined) {
const seen = new Set<string>();
const normalized: string[] = [];
for (const rawId of ids ?? []) {
const id = rawId.trim();
if (!id || seen.has(id)) {
continue;
}
seen.add(id);
normalized.push(id);
}
return normalized;
}
function normalizeLocalDailyActivity(activity: Record<string, number> | undefined) {
const normalized: Record<string, number> = {};
for (const [key, count] of Object.entries(activity ?? {})) {
if (typeof count !== 'number' || !Number.isFinite(count) || count <= 0) {
continue;
}
normalized[key.trim()] = Math.floor(count);
}
return normalized;
}
function normalizeLocalUser(user: StoredLocalUser): StoredLocalUser {
const solvedQuestionIds = normalizeLocalSolvedQuestionIds(user.solvedQuestionIds);
const dailyActivity = normalizeLocalDailyActivity(user.dailyActivity);
const currentStreak = Math.max(0, Math.floor(user.currentStreak || 0));
const longestStreak = Math.max(currentStreak, Math.floor(user.longestStreak || 0));
const coins = Math.max(0, Math.floor(user.coins || 0));
return {
...user,
currentStreak,
longestStreak,
coins,
streakTimeZone: user.streakTimeZone || clientTimeZone() || 'UTC',
solvedQuestionIds,
dailyActivity,
purchasedItemIds: Array.isArray(user.purchasedItemIds) ? user.purchasedItemIds : [],
};
}
function differenceInLocalDays(later: Date, earlier: Date) {
const laterDate = new Date(later);
const earlierDate = new Date(earlier);
laterDate.setHours(0, 0, 0, 0);
earlierDate.setHours(0, 0, 0, 0);
return Math.round((laterDate.getTime() - earlierDate.getTime()) / (1000 * 60 * 60 * 24));
}
function visibleLocalCurrentStreak(user: StoredLocalUser) {
if (!user.lastActiveAt) {
return 0;
}
const lastActiveAt = new Date(user.lastActiveAt);
if (Number.isNaN(lastActiveAt.getTime())) {
return 0;
}
const dayDelta = differenceInLocalDays(new Date(), lastActiveAt);
return dayDelta <= 1 ? Math.max(0, Math.floor(user.currentStreak || 0)) : 0;
}
function weeklySolvedFromLocalActivity(activity: Record<string, number>) {
const normalizedActivity = normalizeLocalDailyActivity(activity);
let total = 0;
for (let offset = 0; offset < 7; offset += 1) {
const currentDate = new Date();
currentDate.setDate(currentDate.getDate() - offset);
total += normalizedActivity[getActivityDateKey(currentDate)] || 0;
}
return total;
}
function trimLocalLeaderboard(entries: ProgressLeaderboardEntry[], currentUserId: string, limit = 10) {
if (entries.length <= limit) {
return entries;
}
const currentIndex = entries.findIndex((entry) => entry.id === currentUserId);
if (currentIndex === -1 || currentIndex < limit) {
return entries.slice(0, limit);
}
return [...entries.slice(0, limit - 1), entries[currentIndex]];
}
function weeklyCodingSolvedFromLocalActivity(breakdown: Record<string, Record<string, number>> | undefined) {
if (!breakdown) return 0;
let total = 0;
for (let offset = 0; offset < 7; offset += 1) {
const currentDate = new Date();
currentDate.setDate(currentDate.getDate() - offset);
const dayKey = getActivityDateKey(currentDate);
const dayBreakdown = breakdown[dayKey];
if (dayBreakdown && typeof dayBreakdown.coding === 'number') {
total += dayBreakdown.coding;
}
}
return total;
}
function codingCurrentStreakFromLocalActivity(breakdown: Record<string, Record<string, number>> | undefined) {
if (!breakdown || Object.keys(breakdown).length === 0) return 0;
let streak = 0;
const now = new Date();
const todayKey = getActivityDateKey(now);
const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayKey = getActivityDateKey(yesterday);
const todayCoding = breakdown[todayKey]?.['coding'] || 0;
const yesterdayCoding = breakdown[yesterdayKey]?.['coding'] || 0;
if (todayCoding === 0 && yesterdayCoding === 0) return 0;
let currentDay = new Date(now);
if (todayCoding === 0) {
currentDay.setDate(currentDay.getDate() - 1);
}
while (true) {
const dayKey = getActivityDateKey(currentDay);
const codingCount = breakdown[dayKey]?.['coding'] || 0;
if (codingCount > 0) {
streak++;
currentDay.setDate(currentDay.getDate() - 1);
} else {
break;
}
}
return streak;
}
function buildLocalCodingLeaderboard(users: StoredLocalUser[], currentUserId: string) {
const leaderboard = users
.map((candidate) => {
const user = normalizeLocalUser(candidate);
let codingSolvedCount = 0;
for (const id of user.solvedQuestionIds || []) {
if (!id.startsWith('sd-') && !id.startsWith('cs-') && !id.startsWith('apt-')) {
codingSolvedCount++;
}
}
const weeklySolved = weeklyCodingSolvedFromLocalActivity(user.dailyActivityBreakdown);
const codingStreak = codingCurrentStreakFromLocalActivity(user.dailyActivityBreakdown);
const currentStreak = visibleLocalCurrentStreak(user);
const coins = Math.max(0, user.coins || 0);
return {
id: user.id,
displayName: user.displayName.trim() || 'User',
solvedCount: codingSolvedCount,
currentStreak,
codingStreak,
weeklySolved,
coins,
score: codingSolvedCount * 100,
rank: 0,
languageStats: user.languageStats,
isCurrentUser: user.id === currentUserId,
} satisfies ProgressLeaderboardEntry;
})
.sort((left, right) => {
if (right.score !== left.score) return right.score - left.score;
if (right.solvedCount !== left.solvedCount) return right.solvedCount - left.solvedCount;
if (right.weeklySolved !== left.weeklySolved) return right.weeklySolved - left.weeklySolved;
if (right.coins !== left.coins) return right.coins - left.coins;
return left.displayName.localeCompare(right.displayName);
})
.map((entry, index) => ({
...entry,
rank: index + 1,
}));
return leaderboard;
}
function buildLocalLeaderboard(users: StoredLocalUser[], currentUserId: string) {
const leaderboard = users
.map((candidate) => {
const user = normalizeLocalUser(candidate);
const solvedCount = user.solvedQuestionIds?.length || 0;
const weeklySolved = weeklySolvedFromLocalActivity(user.dailyActivity || {});
const currentStreak = visibleLocalCurrentStreak(user);
const coins = Math.max(0, user.coins || 0);
return {
id: user.id,
displayName: user.displayName.trim() || 'User',
solvedCount,
currentStreak,
weeklySolved,
coins,
score: solvedCount * 100 + weeklySolved * 15 + currentStreak * 30 + coins,
rank: 0,
isCurrentUser: user.id === currentUserId,
} satisfies ProgressLeaderboardEntry;
})
.sort((left, right) => {
if (right.score !== left.score) {
return right.score - left.score;
}
if (right.solvedCount !== left.solvedCount) {
return right.solvedCount - left.solvedCount;
}
if (right.weeklySolved !== left.weeklySolved) {
return right.weeklySolved - left.weeklySolved;
}
if (right.coins !== left.coins) {
return right.coins - left.coins;
}
return left.displayName.localeCompare(right.displayName);
})
.map((entry, index) => ({
...entry,
rank: index + 1,
}));
// Return full list β the dashboard panel limits to 3 in the UI; the full leaderboard page shows all.
return leaderboard;
}
function buildLocalProgressStats(userId: string, users: StoredLocalUser[]): UserProgressStats {
const user = users.map(normalizeLocalUser).find((candidate) => candidate.id === userId);
if (!user) {
throw new Error('Not authenticated');
}
const solvedQuestionIds = normalizeLocalSolvedQuestionIds(user.solvedQuestionIds);
const dailyActivity = normalizeLocalDailyActivity(user.dailyActivity);
const rawUser = users.find((candidate) => candidate.id === userId);
const dailyActivityBreakdown: Record<string, Record<string, number>> = rawUser?.dailyActivityBreakdown ?? {};
let codingSolvedCount = 0;
for (const id of solvedQuestionIds) {
if (!id.startsWith('sd-') && !id.startsWith('cs-') && !id.startsWith('apt-')) {
codingSolvedCount++;
}
}
return {
solvedQuestionIds,
dailyActivity,
dailyActivityBreakdown,
solvedCount: solvedQuestionIds.length,
activeDays: Object.values(dailyActivity).filter((count) => count > 0).length,
weeklySolved: weeklySolvedFromLocalActivity(dailyActivity),
leaderboard: buildLocalLeaderboard(users, userId),
codingLeaderboard: buildLocalCodingLeaderboard(users, userId),
codingSolvedCount,
};
}
function updateLocalStreakForSolve(user: StoredLocalUser, now: Date) {
const lastActiveAt = user.lastActiveAt ? new Date(user.lastActiveAt) : null;
const lastActiveIsValid = Boolean(lastActiveAt && !Number.isNaN(lastActiveAt.getTime()));
if (!lastActiveIsValid) {
user.currentStreak = 1;
user.longestStreak = Math.max(user.longestStreak || 0, 1);
user.lastActiveAt = now.toISOString();
return;
}
const dayDelta = differenceInLocalDays(now, lastActiveAt!);
if (dayDelta <= 0) {
return;
}
if (dayDelta === 1) {
user.currentStreak = Math.max(0, user.currentStreak || 0) + 1;
} else {
user.currentStreak = 1;
}
user.longestStreak = Math.max(user.longestStreak || 0, user.currentStreak);
user.lastActiveAt = now.toISOString();
}
/**
* Touch the streak on every login event (password login, session restore, Google OAuth).
* Mirrors the backend nextStreakUpdate logic:
* - No lastActiveAt β streak becomes 1.
* - Same calendar day β no change (already counted).
* - Consecutive day β streak increments by 1.
* - Missed day(s) β streak resets to 1.
* Always keeps longestStreak up to date.
*/
function touchLocalStreak(user: StoredLocalUser, now: Date) {
const lastActiveAt = user.lastActiveAt ? new Date(user.lastActiveAt) : null;
const lastActiveIsValid = Boolean(lastActiveAt && !Number.isNaN(lastActiveAt.getTime()));
if (!lastActiveIsValid) {
user.currentStreak = 1;
user.longestStreak = Math.max(user.longestStreak || 0, 1);
user.lastActiveAt = now.toISOString();
return;
}
const dayDelta = differenceInLocalDays(now, lastActiveAt!);
if (dayDelta <= 0) {
// Already counted for today β nothing to do.
return;
}
if (dayDelta === 1) {
user.currentStreak = Math.max(0, user.currentStreak || 0) + 1;
} else {
// Missed one or more days β start a fresh streak.
user.currentStreak = 1;
}
user.longestStreak = Math.max(user.longestStreak || 0, user.currentStreak);
user.lastActiveAt = now.toISOString();
}
function mergeLocalProgress(token: string, data: { solvedQuestionIds: string[]; dailyActivity: Record<string, number> }) {
const users = loadLocalUsers();
const userId = token.slice(LOCAL_AUTH_TOKEN_PREFIX.length);
const userIndex = users.findIndex((candidate) => candidate.id === userId);
if (userIndex === -1) {
throw new Error('Not authenticated');
}
const user = normalizeLocalUser(users[userIndex]);
const mergedSolvedQuestionIds = normalizeLocalSolvedQuestionIds([
...(user.solvedQuestionIds || []),
...normalizeLocalSolvedQuestionIds(data.solvedQuestionIds),
]);
const mergedDailyActivity = {
...normalizeLocalDailyActivity(user.dailyActivity),
...normalizeLocalDailyActivity(data.dailyActivity),
};
user.solvedQuestionIds = mergedSolvedQuestionIds;
user.dailyActivity = mergedDailyActivity;
users[userIndex] = user;
saveLocalUsers(users);
return {
user: toAuthUser(user),
stats: buildLocalProgressStats(user.id, users),
};
}
function recordLocalSolvedQuestion(
token: string,
questionId: string,
difficulty: string,
language?: string,
) {
const users = loadLocalUsers();
const userId = token.slice(LOCAL_AUTH_TOKEN_PREFIX.length);
const userIndex = users.findIndex((candidate) => candidate.id === userId);
if (userIndex === -1) {
throw new Error('Not authenticated');
}
const reward = getSolveReward(difficulty);
if (reward == null) {
throw new Error('Question difficulty is required.');
}
const user = normalizeLocalUser(users[userIndex]);
const solvedQuestionIds = normalizeLocalSolvedQuestionIds(user.solvedQuestionIds);
const dailyActivity = normalizeLocalDailyActivity(user.dailyActivity);
const alreadySolved = solvedQuestionIds.includes(questionId);
if (!alreadySolved) {
const now = new Date();
solvedQuestionIds.push(questionId);
const todayKey = getActivityDateKey(now);
dailyActivity[todayKey] = (dailyActivity[todayKey] || 0) + 1;
// Detect section from question ID prefix (mirrors backend logic)
let section = 'coding';
if (questionId.startsWith('sd-')) {
section = 'systemDesign';
} else if (questionId.startsWith('cs-dbms-')) {
section = 'dbms';
} else if (questionId.startsWith('cs-os-')) {
section = 'os';
} else if (questionId.startsWith('cs-cn-')) {
section = 'cn';
} else if (questionId.startsWith('cs-')) {
section = 'csFundamentals';
} else if (questionId.startsWith('apt-')) {
section = 'aptitude';
}
const breakdown = user.dailyActivityBreakdown ?? {};
if (!breakdown[todayKey]) {
breakdown[todayKey] = {};
}
breakdown[todayKey][section] = (breakdown[todayKey][section] || 0) + 1;
user.dailyActivityBreakdown = breakdown;
user.solvedQuestionIds = solvedQuestionIds;
user.dailyActivity = dailyActivity;
if (section === 'coding' && language) {
const stats = user.languageStats ?? {};
const lang = language.toLowerCase().trim();
stats[lang] = (stats[lang] || 0) + 1;
user.languageStats = stats;
}
updateLocalStreakForSolve(user, now);
user.coins = Math.max(0, user.coins || 0) + reward;
}
users[userIndex] = user;
saveLocalUsers(users);
return {
user: toAuthUser(user),
stats: buildLocalProgressStats(user.id, users),
};
}
function spendLocalCoins(token: string, amount: number): { user: AuthUser; stats: UserProgressStats } {
const users = loadLocalUsers();
const userId = token.slice(LOCAL_AUTH_TOKEN_PREFIX.length);
const userIndex = users.findIndex((candidate) => candidate.id === userId);
if (userIndex === -1) {
throw new Error('Not authenticated');
}
const user = normalizeLocalUser(users[userIndex]);
if (amount <= 0) {
throw new Error('Amount must be greater than 0.');
}
if (user.coins < amount) {
throw new Error('Not enough coins.');
}
user.coins -= amount;
users[userIndex] = user;
saveLocalUsers(users);
return {
user: toAuthUser(user),
stats: buildLocalProgressStats(user.id, users),
};
}
const REACHABILITY_HINT =
'Start the API with "npm run api". For a single-server launch, run "npm start" and open http://localhost:3000. For Vite development, run "npm run api" and "npm run dev", then open http://localhost:5173. If the UI is on another port, add VITE_API_BASE=http://localhost:3000 to .env and restart.';
export async function apiFetch(path: string, init?: RequestInit): Promise<Response> {
const url = apiUrl(path);
const headers = new Headers(init?.headers);
const timeZone = clientTimeZone();
if (timeZone && !headers.has('X-Timezone')) {
headers.set('X-Timezone', timeZone);
}
try {
const response = await fetch(url, {
...init,
headers,
});
return response;
} catch (error) {
console.error('API fetch error:', { url, error });
throw new Error(`Cannot reach server (${url}). ${REACHABILITY_HINT}`);
}
}
async function parseJson(res: Response) {
const text = await res.text();
try {
return text ? JSON.parse(text) : {};
} catch (error) {
console.error('JSON parse error:', { text, error });
return { error: 'Invalid server response' };
}
}
export async function registerUser(
email: string,
password: string,
displayName: string,
): Promise<{ token: string; user: AuthUser }> {
try {
const res = await apiFetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, displayName }),
});
const data = await parseJson(res);
if (!res.ok) {
if (isLocalDevOrigin() && res.status >= 500) {
return registerLocalUser(email, password, displayName);
}
throw new Error(data.error || 'Registration failed');
}
return data as { token: string; user: AuthUser };
} catch (error) {
if (shouldUseLocalAuthFallback(error)) {
return registerLocalUser(email, password, displayName);
}
console.error('Registration error:', error);
throw error;
}
}
export async function loginUser(
email: string,
password: string,
): Promise<{ token: string; user: AuthUser }> {
try {
const res = await apiFetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await parseJson(res);
if (!res.ok) {
if (isLocalDevOrigin() && res.status >= 500) {
return loginLocalUser(email, password);
}
throw new Error(data.error || 'Login failed');
}
return data as { token: string; user: AuthUser };
} catch (error) {
if (shouldUseLocalAuthFallback(error)) {
return loginLocalUser(email, password);
}
console.error('Login error:', error);
throw error;
}
}
export async function fetchSessionUser(token: string): Promise<AuthUser | null> {
if (isLocalToken(token)) {
const users = loadLocalUsers();
const userId = token.slice(LOCAL_AUTH_TOKEN_PREFIX.length);
const userIndex = users.findIndex((u) => u.id === userId);
if (userIndex === -1) return null;
const user = normalizeLocalUser(users[userIndex]);
touchLocalStreak(user, new Date());
users[userIndex] = user;
saveLocalUsers(users);
return toAuthUser(user);
}
try {
const res = await apiFetch('/api/auth/me', {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return null;
const data = await parseJson(res);
return (data as { user: AuthUser }).user ?? null;
} catch (error) {
console.error('Fetch session user error:', error);
return null;
}
}
export async function updateProfile(
token: string,
data: { displayName?: string; oldPassword?: string; newPassword?: string },
): Promise<{ user: AuthUser }> {
if (isLocalToken(token)) {
const result = updateLocalUser(token, data);
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: result.user }));
}
return result;
}
const res = await apiFetch('/api/auth/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(data),
});
const resData = await parseJson(res);
if (!res.ok) {
throw new Error(resData.error || 'Failed to update profile');
}
return resData as { user: AuthUser };
}
export async function addCoins(
token: string,
amount: number,
): Promise<{ user: AuthUser }> {
if (isLocalToken(token)) {
const result = updateLocalCoins(token, amount);
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: result.user }));
}
return result;
}
const res = await apiFetch('/api/user/add-coins', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ amount }),
});
const resData = await parseJson(res);
if (!res.ok) {
throw new Error(resData.error || 'Failed to add coins');
}
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: resData.user }));
}
return resData as { user: AuthUser };
}
function getSolveReward(difficulty: string) {
const normalizedDifficulty = difficulty.trim().toLowerCase();
if (normalizedDifficulty === 'easy') {
return 10;
}
if (normalizedDifficulty === 'medium') {
return 25;
}
if (normalizedDifficulty === 'hard') {
return 50;
}
return null;
}
export async function fetchUserProgress(
token: string,
): Promise<UserProgressStats> {
if (isLocalToken(token)) {
const localUser = findLocalUserByToken(token);
if (!localUser) {
throw new Error('Not authenticated');
}
return buildLocalProgressStats(localUser.id, loadLocalUsers());
}
const res = await apiFetch('/api/user/stats', {
headers: {
Authorization: `Bearer ${token}`,
},
});
const resData = await parseJson(res);
if (!res.ok) {
throw new Error(resData.error || 'Failed to load progress');
}
const typed = resData as { user?: AuthUser; stats: UserProgressStats };
if (typed.user && typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: typed.user }));
}
return typed.stats;
}
export async function importUserProgress(
token: string,
data: { solvedQuestionIds: string[]; dailyActivity: Record<string, number> },
): Promise<{ user: AuthUser; stats: UserProgressStats }> {
if (isLocalToken(token)) {
const result = mergeLocalProgress(token, data);
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: result.user }));
}
return result;
}
const res = await apiFetch('/api/user/import-progress', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(data),
});
const resData = await parseJson(res);
if (!res.ok) {
throw new Error(resData.error || 'Failed to import progress');
}
const typed = resData as { user: AuthUser; stats: UserProgressStats };
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: typed.user }));
}
return typed;
}
export async function recordSolvedQuestion(
token: string,
data: { questionId: string; difficulty: string; language?: string },
): Promise<{ user: AuthUser; stats: UserProgressStats }> {
if (isLocalToken(token)) {
const result = recordLocalSolvedQuestion(token, data.questionId, data.difficulty, data.language);
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: result.user }));
}
return result;
}
const res = await apiFetch('/api/user/solve-question', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(data),
});
const resData = await parseJson(res);
if (!res.ok) {
throw new Error(resData.error || 'Failed to record solved question');
}
const typed = resData as { user: AuthUser; stats: UserProgressStats };
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: typed.user }));
}
return typed;
}
export async function spendCoins(
token: string,
amount: number,
): Promise<{ user: AuthUser; stats: UserProgressStats }> {
if (isLocalToken(token)) {
const result = spendLocalCoins(token, amount);
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: result.user }));
}
return result;
}
const res = await apiFetch('/api/user/spend-coins', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ amount }),
});
const resData = await parseJson(res);
if (!res.ok) {
throw new Error(resData.error || 'Failed to spend coins');
}
const typed = resData as { user: AuthUser; stats: UserProgressStats };
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('user-updated', { detail: typed.user }));
}
return typed;
}
export async function fetchCoinHistory(token: string): Promise<CoinTransaction[]> {
if (isLocalToken(token)) {
const localUser = findLocalUserByToken(token);
if (!localUser || !localUser.coins) {
return [];
}
return [
{
id: 'legacy-balance',
userId: localUser.id,
amount: localUser.coins,
source: 'Initial Balance',
category: 'bonus',
createdAt: localUser.createdAt || new Date().toISOString(),
}
];
}
const res = await apiFetch('/api/user/coin-history', {
headers: {
Authorization: `Bearer ${token}`,
},
});
const resData = await parseJson(res);
if (!res.ok) {
throw new Error(resData.error || 'Failed to fetch coin history');
}
return resData as CoinTransaction[];
}
|