-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
2163 lines (1949 loc) · 68.3 KB
/
Copy pathapi.ts
File metadata and controls
2163 lines (1949 loc) · 68.3 KB
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
import {
AuthSession,
BillingCheckout,
BillingAdminCustomer,
BillingAdminOverview,
BillingOffersResponse,
BillingOperationalAlert,
BillingReceiptsResponse,
BillingSummary,
BillingWebhookEvent,
CompanyTrack,
Competition,
CompetitionDetail,
CompetitionStatus,
ContestRank,
ContestLeaderboardEntry,
Difficulty,
ExecutionMode,
LeaderboardEntry,
LearningTrack,
LoginPayload,
NewContestInput,
NewLearningTrackInput,
NewProblemInput,
Problem,
ProblemDetail,
SignupPayload,
SubmissionRecord,
SubmissionResult,
RecentActivityItem,
SubmissionTestCaseResult,
TopicProgressPoint,
UpdateProfileInput,
User,
UserProfile,
UserProgress,
UserStats,
} from "@/types";
import { AUTH_COOKIE_NAME, AUTH_COOKIE_TTL_SECONDS } from "@/lib/auth";
import { trackEvent } from "@/lib/analytics";
import { reportError, reportMessage } from "@/lib/observability";
import rawProblemCatalog from "@/data/problem-catalog.json";
import { runPythonInBrowser, type BrowserPracticeCase } from "@/lib/browserPython";
type ApiMode = "mock" | "live" | "auto";
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "/api";
const DEFAULT_API_MODE = process.env.NODE_ENV === "production" ? "live" : "mock";
const API_MODE = ((process.env.NEXT_PUBLIC_API_MODE || DEFAULT_API_MODE).toLowerCase() ||
DEFAULT_API_MODE) as ApiMode;
const API_RETRY_COUNT = Number(process.env.NEXT_PUBLIC_API_RETRY_COUNT || 2);
const API_TIMEOUT_MS = Number(process.env.NEXT_PUBLIC_API_TIMEOUT_MS || 8000);
const EXECUTION_ADAPTER = (process.env.NEXT_PUBLIC_EXECUTION_MODE || "browser").toLowerCase();
const ALLOW_MOCK_FALLBACK = process.env.NEXT_PUBLIC_API_FALLBACK_TO_MOCK
? process.env.NEXT_PUBLIC_API_FALLBACK_TO_MOCK === "true"
: process.env.NODE_ENV !== "production";
const MOCK_SESSION_KEY = "katalume.mock.session";
const SUBMISSION_HISTORY_KEY = "katalume.submission.history";
const ACTIVE_USER_KEY = "katalume.active.user";
// Practice history is scoped per signed-in account so two people sharing a
// browser never inherit each other's local progress. The marker holds only an
// opaque user id (never a credential); anonymous practice uses "anon".
function setActiveUser(userId: string | null): void {
if (!isBrowser()) return;
if (userId) window.localStorage.setItem(ACTIVE_USER_KEY, userId);
else window.localStorage.removeItem(ACTIVE_USER_KEY);
}
function submissionHistoryKey(): string {
if (!isBrowser()) return SUBMISSION_HISTORY_KEY;
const uid = window.localStorage.getItem(ACTIVE_USER_KEY) || "anon";
const scoped = `${SUBMISSION_HISTORY_KEY}.${uid}`;
// One-time migration: claim the old shared key for the current account.
const legacy = window.localStorage.getItem(SUBMISSION_HISTORY_KEY);
if (legacy !== null && window.localStorage.getItem(scoped) === null) {
window.localStorage.setItem(scoped, legacy);
window.localStorage.removeItem(SUBMISSION_HISTORY_KEY);
}
return scoped;
}
const FETCH_DELAY_MS = 420;
const AUTH_DELAY_MS = 550;
interface CatalogProblemSpec {
slug: string;
title: string;
difficulty: Difficulty;
category: string;
acceptanceRate: number;
tags: string[];
summary: string;
description: string;
constraints: string[];
hints: string[];
starterCode: string;
sampleTestCases: Array<{ input: string; output: string }>;
hiddenTestCount: number;
editorial: ProblemDetail["editorial"];
testcases: Array<BrowserPracticeCase & { timeLimit: number; memoryLimit: number }>;
}
interface LivePracticeSpec {
problemId: string;
slug: string;
testcaseVersion: number;
testcases: Array<BrowserPracticeCase & { timeLimit?: number; memoryLimit?: number }>;
}
const MOCK_COMPANY_TRACKS: CompanyTrack[] = [
{
id: "track-ml-core-50",
title: "ML Engineer Core 50",
company: "Meta",
description:
"A focused set of 50 modeling + feature engineering problems for ML interviews.",
totalProblems: 50,
solvedProblems: 19,
tags: ["modeling", "metrics", "feature-engineering"],
},
{
id: "track-pandas-interview-30",
title: "Pandas Interview 30",
company: "Uber",
description:
"Table transform and aggregation patterns commonly asked in data interviews.",
totalProblems: 30,
solvedProblems: 11,
tags: ["pandas", "joins", "groupby"],
},
{
id: "track-recommendation-20",
title: "Recommendation Systems 20",
company: "Netflix",
description:
"Ranking, retrieval, and evaluation exercises for recommender workflows.",
totalProblems: 20,
solvedProblems: 4,
tags: ["ranking", "retrieval", "offline-metrics"],
},
];
const MOCK_RECENT_RANKS: ContestRank[] = [
{
contest: "Model Metrics Sprint",
rank: 182,
participants: 4820,
score: 1780,
date: "2026-02-24",
},
{
contest: "Feature Engineering Weekly",
rank: 96,
participants: 3910,
score: 1860,
date: "2026-02-17",
},
{
contest: "Data Prep Rapid Round",
rank: 121,
participants: 4055,
score: 1814,
date: "2026-02-10",
},
];
const PROBLEM_CATALOG = rawProblemCatalog as unknown as CatalogProblemSpec[];
const MOCK_PROBLEMS: ProblemDetail[] = PROBLEM_CATALOG.map((problem, index) => ({
id: `p-${String(index + 1).padStart(3, "0")}`,
slug: problem.slug,
title: problem.title,
difficulty: problem.difficulty,
category: problem.category,
acceptance: problem.acceptanceRate,
acceptanceRate: problem.acceptanceRate,
status: "unsolved",
tags: problem.tags,
summary: problem.summary,
description: problem.description,
constraints: problem.constraints,
examples: problem.sampleTestCases,
sampleTestCases: problem.sampleTestCases,
hiddenTestCount: problem.hiddenTestCount,
hints: problem.hints,
editorial: problem.editorial,
starterCode: problem.starterCode,
companies: [],
trackIds: [],
}));
const CATALOG_BY_IDENTIFIER = new Map<string, CatalogProblemSpec>();
PROBLEM_CATALOG.forEach((problem, index) => {
CATALOG_BY_IDENTIFIER.set(problem.slug, problem);
CATALOG_BY_IDENTIFIER.set(`p-${String(index + 1).padStart(3, "0")}`, problem);
});
function wait(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
function isBrowser(): boolean {
return typeof window !== "undefined";
}
function getNormalizedApiMode(): ApiMode {
if (API_MODE === "mock" || API_MODE === "live" || API_MODE === "auto") {
return API_MODE;
}
return DEFAULT_API_MODE as ApiMode;
}
export function getBackendMode(): ApiMode {
return getNormalizedApiMode();
}
function persistSession(session: AuthSession): void {
setActiveUser(session.user?.id || null);
if (!isBrowser()) {
return;
}
if (getNormalizedApiMode() === "mock") {
window.localStorage.setItem(MOCK_SESSION_KEY, JSON.stringify(session));
window.document.cookie = `${AUTH_COOKIE_NAME}=1; path=/; max-age=${AUTH_COOKIE_TTL_SECONDS}; samesite=lax`;
} else {
window.localStorage.removeItem(MOCK_SESSION_KEY);
window.document.cookie = `${AUTH_COOKIE_NAME}=; path=/; max-age=0; samesite=lax`;
}
}
function readStoredSession(): AuthSession | null {
if (!isBrowser()) {
return null;
}
const hasMockAuthCookie = window.document.cookie
.split(";")
.some((part) => part.trim().startsWith(`${AUTH_COOKIE_NAME}=`));
if (getNormalizedApiMode() === "mock" && !hasMockAuthCookie) {
window.localStorage.removeItem(MOCK_SESSION_KEY);
return null;
}
const raw = window.localStorage.getItem(MOCK_SESSION_KEY);
if (!raw) {
return null;
}
try {
return JSON.parse(raw) as AuthSession;
} catch {
window.localStorage.removeItem(MOCK_SESSION_KEY);
return null;
}
}
function clearStoredSession(): void {
setActiveUser(null);
if (!isBrowser()) {
return;
}
window.localStorage.removeItem(MOCK_SESSION_KEY);
window.document.cookie = `${AUTH_COOKIE_NAME}=; path=/; max-age=0; samesite=lax`;
}
function createMockSession(name: string, email: string): AuthSession {
const now = new Date();
const token = `mock_${Math.random().toString(36).slice(2)}_${Date.now()}`;
return {
user: {
id: `user_${email.toLowerCase().replace(/[^a-z0-9]/g, "")}`,
name,
email: email.toLowerCase(),
avatarUrl: "",
createdAt: now.toISOString(),
roles: ["User"],
},
accessToken: token,
expiresAt: new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString(),
};
}
function getProblemByIdentifier(identifier: string): ProblemDetail | undefined {
return MOCK_PROBLEMS.find(
(problem) => problem.id === identifier || problem.slug === identifier
);
}
// Lightweight metadata for a problem, enough to attribute a solve to its
// difficulty and topic. Problems served by the live backend are not in the
// bundled catalog, so we remember their metadata when the arena opens them
// (see fetchProblemBySlug) and consult it wherever the bundle lookup misses,
// keeping progress views consistent for imported problems.
interface ProblemMeta {
slug: string;
id: string;
title: string;
difficulty: Difficulty;
category: string;
}
const PROBLEM_META_KEY = "katalume.problem.meta";
function rememberProblemMeta(problem: ProblemDetail): void {
if (!isBrowser()) return;
try {
const raw = window.localStorage.getItem(PROBLEM_META_KEY);
const store = (raw ? JSON.parse(raw) : {}) as Record<string, ProblemMeta>;
const meta: ProblemMeta = {
slug: problem.slug,
id: problem.id,
title: problem.title,
difficulty: problem.difficulty,
category: problem.category,
};
store[problem.slug] = meta;
store[problem.id] = meta;
window.localStorage.setItem(PROBLEM_META_KEY, JSON.stringify(store));
} catch {
// Best-effort cache; ignore quota/serialization errors.
}
}
// Cache metadata for EVERY problem the live backend lists (not just opened
// ones) so difficulty denominators and topic totals reflect the full catalog
// instead of the bundled subset.
function rememberProblemList(problems: Problem[]): void {
if (!isBrowser()) return;
try {
const raw = window.localStorage.getItem(PROBLEM_META_KEY);
const store = (raw ? JSON.parse(raw) : {}) as Record<string, ProblemMeta>;
for (const problem of problems) {
if (!problem.slug || !problem.difficulty) continue;
const meta: ProblemMeta = {
slug: problem.slug,
id: problem.id,
title: problem.title,
difficulty: problem.difficulty,
category: (problem as { category?: string }).category || "General",
};
store[problem.slug] = meta;
store[problem.id] = meta;
}
window.localStorage.setItem(PROBLEM_META_KEY, JSON.stringify(store));
} catch {
// Best-effort cache; ignore quota/serialization errors.
}
}
// The union of bundled problems and every remembered live problem, deduped by
// slug — the closest local view of the real catalog.
function allKnownProblemMeta(): Map<string, ProblemMeta> {
const known = new Map<string, ProblemMeta>();
for (const problem of MOCK_PROBLEMS) {
known.set(problem.slug, {
slug: problem.slug,
id: problem.id,
title: problem.title,
difficulty: problem.difficulty,
category: problem.category,
});
}
if (isBrowser()) {
try {
const raw = window.localStorage.getItem(PROBLEM_META_KEY);
if (raw) {
const store = JSON.parse(raw) as Record<string, ProblemMeta>;
for (const meta of Object.values(store)) {
if (meta?.slug && !known.has(meta.slug)) known.set(meta.slug, meta);
}
}
} catch {
// fall back to the bundle alone
}
}
return known;
}
function resolveProblemMeta(identifier: string): ProblemMeta | undefined {
const bundled = getProblemByIdentifier(identifier);
if (bundled) {
return {
slug: bundled.slug,
id: bundled.id,
title: bundled.title,
difficulty: bundled.difficulty,
category: bundled.category,
};
}
if (!isBrowser()) return undefined;
try {
const raw = window.localStorage.getItem(PROBLEM_META_KEY);
if (!raw) return undefined;
const store = JSON.parse(raw) as Record<string, ProblemMeta>;
return store[identifier];
} catch {
return undefined;
}
}
function readSubmissionHistoryStore(): SubmissionRecord[] {
if (!isBrowser()) {
return [];
}
const raw = window.localStorage.getItem(submissionHistoryKey());
if (!raw) {
return [];
}
try {
const parsed = JSON.parse(raw) as SubmissionRecord[];
return Array.isArray(parsed) ? parsed : [];
} catch {
window.localStorage.removeItem(submissionHistoryKey());
return [];
}
}
function writeSubmissionHistoryStore(records: SubmissionRecord[]): void {
if (!isBrowser()) {
return;
}
window.localStorage.setItem(
submissionHistoryKey(),
JSON.stringify(records.slice(0, 180))
);
}
function upsertSubmissionRecord(record: SubmissionRecord): void {
const history = readSubmissionHistoryStore();
history.unshift(record);
writeSubmissionHistoryStore(history);
}
function computeDynamicStatus(
problemId: string,
fallback: Problem["status"]
): Problem["status"] {
const history = readSubmissionHistoryStore();
const forProblem = history.filter((entry) => entry.problemId === problemId);
if (forProblem.some((entry) => entry.mode === "submit" && entry.result.status === "Accepted")) {
return "solved";
}
if (forProblem.length > 0) {
return "attempted";
}
return fallback;
}
function normalizeToListItem(problem: ProblemDetail): Problem {
return {
id: problem.id,
slug: problem.slug,
title: problem.title,
difficulty: problem.difficulty,
category: problem.category,
acceptance: problem.acceptance,
acceptanceRate: problem.acceptanceRate,
status: computeDynamicStatus(problem.id, problem.status),
tags: [...problem.tags],
summary: problem.summary,
companies: problem.companies,
trackIds: problem.trackIds,
};
}
function createSubmissionRecord(
problemId: string,
code: string,
mode: ExecutionMode,
result: SubmissionResult,
problemIdentifier = problemId,
fallbackTitle?: string
): SubmissionRecord {
const problem = getProblemByIdentifier(problemIdentifier);
return {
id: result.submissionId,
problemId,
problemSlug: problem?.slug || problemId,
// Problems served by the live backend (e.g. imported pipeline problems)
// are not in the bundled catalog, so fall back to the title the arena
// passes through instead of showing "Unknown Problem".
problemTitle: problem?.title || fallbackTitle || "Unknown Problem",
code,
mode,
result,
createdAt: result.submittedAt,
};
}
function parseJsonSafely<T>(text: string): T {
return JSON.parse(text) as T;
}
export class ApiError extends Error {
status: number;
code?: string;
upgradeUrl?: string;
constructor(status: number, message: string, code?: string, upgradeUrl?: string) {
super(message);
this.name = "ApiError";
this.status = status;
this.code = code;
this.upgradeUrl = upgradeUrl;
}
}
async function fetchWithRetry<T>(
path: string,
init?: RequestInit,
retries = API_RETRY_COUNT,
onResponse?: (response: Response) => void
): Promise<T> {
const method = (init?.method || "GET").toUpperCase();
// Only retry idempotent methods. Retrying POST (e.g. /submissions) on a
// timeout can duplicate a submission that actually succeeded server-side.
const isIdempotent = method === "GET" || method === "HEAD";
const maxRetries = isIdempotent ? retries : 0;
let attempt = 0;
let lastError: unknown;
let refreshedSession = false;
while (attempt <= maxRetries) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), API_TIMEOUT_MS);
try {
const response = await fetch(`${API_BASE_URL}${path}`, {
...init,
signal: controller.signal,
credentials: "include",
headers: {
"Content-Type": "application/json",
...(init?.headers || {}),
},
});
clearTimeout(timeoutId);
if (
(response.status === 401 || response.status === 403) &&
!refreshedSession &&
!path.startsWith("/auth/") &&
getNormalizedApiMode() !== "mock"
) {
refreshedSession = true;
const refreshed = await fetch(`${API_BASE_URL}/auth/refresh`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
});
if (refreshed.ok) continue;
}
if (!response.ok) {
const raw = await response.text();
let detail: { message?: string; code?: string; upgradeUrl?: string } = {};
try {
detail = raw ? JSON.parse(raw) : {};
} catch {
detail = { message: raw };
}
const error: ApiError & { retryable?: boolean } = new ApiError(
response.status,
detail.message || "Request failed",
detail.code,
detail.upgradeUrl
);
// Client errors (4xx) are deterministic — retrying can't help. Only 5xx is retryable.
error.retryable = response.status >= 500;
throw error;
}
const text = await response.text();
onResponse?.(response);
return text ? parseJsonSafely<T>(text) : ({} as T);
} catch (error) {
clearTimeout(timeoutId);
lastError = error;
attempt += 1;
// Network/abort errors carry no `retryable` flag → treated as retryable.
const retryable = (error as { retryable?: boolean })?.retryable !== false;
if (retryable && attempt <= maxRetries) {
await wait(250 * attempt);
continue;
}
break;
}
}
throw lastError instanceof Error ? lastError : new Error("Request failed");
}
async function runWithBackendSwitch<T>(
operation: string,
liveExecutor: () => Promise<T>,
mockExecutor: () => Promise<T>
): Promise<T> {
const mode = getNormalizedApiMode();
if (mode === "mock") {
return mockExecutor();
}
try {
const response = await liveExecutor();
void trackEvent({ name: "api_live_success", payload: { operation } });
return response;
} catch (error) {
reportError(error, { operation, mode });
if (mode === "live" && !ALLOW_MOCK_FALLBACK) {
throw error instanceof Error ? error : new Error("Live API request failed");
}
reportMessage("Falling back to mock API", { operation, mode });
void trackEvent({ name: "api_live_fallback", payload: { operation, mode } });
return mockExecutor();
}
}
function toAuthSessionFromLive(
payload: unknown,
fallbackName: string,
fallbackEmail: string
): AuthSession {
const parsed = (payload || {}) as {
token?: string;
accessToken?: string;
expiresAt?: string;
user?: Partial<AuthSession["user"]> & { username?: string };
};
const now = new Date();
return {
user: {
id: parsed.user?.id || `user_${fallbackEmail.replace(/[^a-z0-9]/gi, "")}`,
name: parsed.user?.name || parsed.user?.username || fallbackName,
email: parsed.user?.email || fallbackEmail,
avatarUrl: parsed.user?.avatarUrl || "",
createdAt: parsed.user?.createdAt || now.toISOString(),
roles: parsed.user?.roles || ["User"],
},
expiresAt:
parsed.expiresAt || new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString(),
};
}
function toProblemFromLive(payload: unknown): Problem {
const parsed = payload as Partial<Problem> & { _id?: string };
const id = parsed.id || parsed._id || `p-live-${Math.random().toString(36).slice(2, 8)}`;
return {
id,
slug: parsed.slug,
title: parsed.title || "Untitled Problem",
difficulty: parsed.difficulty || "Medium",
category: parsed.category || "General",
acceptance: parsed.acceptance || parsed.acceptanceRate || 0,
acceptanceRate: parsed.acceptanceRate || parsed.acceptance || 0,
status:
EXECUTION_ADAPTER === "browser"
? computeDynamicStatus(id, parsed.status || "unsolved")
: parsed.status || "unsolved",
tags: parsed.tags || [],
summary: parsed.summary,
companies: parsed.companies,
trackIds: parsed.trackIds,
accessTier: parsed.accessTier,
locked: Boolean(parsed.locked),
};
}
function toProblemDetailFromLive(slug: string, payload: unknown): ProblemDetail {
const base = toProblemFromLive(payload);
const parsed = payload as Partial<ProblemDetail>;
const bundled = getProblemByIdentifier(slug);
return {
...base,
slug: parsed.slug || slug,
description: parsed.description || "Problem description is unavailable.",
constraints: parsed.constraints || [],
examples: parsed.examples || [],
hints: parsed.hints || [],
sampleTestCases: parsed.sampleTestCases || parsed.examples || [],
hiddenTestCount: parsed.hiddenTestCount || 0,
editorial:
parsed.editorial || bundled?.editorial ||
({
summary: "Editorial unavailable.",
approach: "Connect the backend editorial endpoint to populate this section.",
timeComplexity: "N/A",
spaceComplexity: "N/A",
pitfalls: [],
} as ProblemDetail["editorial"]),
starterCode: parsed.starterCode || "def solve():\n pass",
};
}
function normalizeLiveSubmission(
problemId: string,
mode: ExecutionMode,
payload: unknown
): SubmissionResult {
const parsed = payload as Partial<SubmissionResult> & {
status?: SubmissionResult["status"] | string;
_id?: string;
id?: string;
runtime?: number;
memory?: number;
errorMessage?: string;
stderr?: string;
compileOutput?: string;
stdout?: string;
};
const testCases: SubmissionTestCaseResult[] = (parsed.testCases || []).map((item) => ({
name: item.name || "Case",
visibility: item.visibility || (mode === "run" ? "sample" : "hidden"),
input: item.input,
expectedOutput: item.expectedOutput,
actualOutput: item.actualOutput,
passed: Boolean(item.passed),
errorMessage: item.errorMessage,
}));
const accepted = parsed.status === "Accepted";
const totalCount = parsed.totalCount ?? (testCases.length || 1);
const passedCount =
parsed.passedCount ?? (testCases.length ? testCases.filter((testCase) => testCase.passed).length : accepted ? 1 : 0);
const executionError = /runtime|compilation|internal|limit|error/i.test(parsed.status || "");
return {
submissionId: parsed.submissionId || parsed._id || parsed.id || `sub_live_${Date.now()}`,
problemId,
mode,
visibility: parsed.visibility || (mode === "run" ? "sample" : "hidden"),
status: accepted ? "Accepted" : executionError ? "Runtime Error" : "Failed",
runtimeMs: parsed.runtimeMs ?? Math.round(Number(parsed.runtime || 0) * 1000),
memoryMb: parsed.memoryMb ?? Number(parsed.memory || 0) / 1024,
score: parsed.score ?? Math.round((passedCount / Math.max(1, totalCount)) * 100),
message: parsed.message || (accepted ? "Execution accepted." : parsed.status || "Execution completed."),
passedCount,
totalCount,
traceback: parsed.traceback || parsed.errorMessage || parsed.stderr || parsed.compileOutput,
testCases,
source: "live",
submittedAt: parsed.submittedAt || new Date().toISOString(),
};
}
function mockFetchProblems(tags: string[] = []): Problem[] {
const problems = tags.length
? MOCK_PROBLEMS.filter((problem) => problem.tags.some((tag) => tags.includes(tag)))
: MOCK_PROBLEMS;
return clone(problems.map(normalizeToListItem));
}
function mockFetchProblemBySlug(slug: string): ProblemDetail {
const problem = MOCK_PROBLEMS.find((item) => item.slug === slug);
if (!problem) {
throw new Error(`Problem with slug "${slug}" was not found.`);
}
return clone(problem);
}
// The backend caps each list page at 200 problems and signals more pages via
// an X-Next-Cursor response header (an _id cursor for ?before=).
const PROBLEMS_PAGE_LIMIT = 200;
const PROBLEMS_MAX_PAGES = 10;
async function liveFetchProblems(tags: string[] = []): Promise<Problem[]> {
const tagsQuery = tags.length ? `&tags=${encodeURIComponent(tags.join(","))}` : "";
const all: Problem[] = [];
let cursor: string | null = null;
for (let page = 0; page < PROBLEMS_MAX_PAGES; page += 1) {
const cursorQuery = cursor ? `&before=${encodeURIComponent(cursor)}` : "";
let nextCursor: string | null = null;
const data = await fetchWithRetry<unknown[]>(
`/problems?limit=${PROBLEMS_PAGE_LIMIT}${tagsQuery}${cursorQuery}`,
{ method: "GET" },
API_RETRY_COUNT,
(response) => {
nextCursor = response.headers?.get("x-next-cursor") ?? null;
}
);
all.push(...data.map((entry) => toProblemFromLive(entry)));
cursor = nextCursor;
if (!cursor || data.length === 0) break;
}
return all;
}
async function liveFetchProblemBySlug(slug: string): Promise<ProblemDetail> {
const data = await fetchWithRetry<unknown>(`/problems/${slug}`, { method: "GET" });
return toProblemDetailFromLive(slug, data);
}
async function browserExecute(
problemId: string,
code: string,
mode: ExecutionMode,
catalogIdentifier = problemId
) {
let testcases: BrowserPracticeCase[];
if (getNormalizedApiMode() === "mock") {
const spec = CATALOG_BY_IDENTIFIER.get(catalogIdentifier);
if (!spec) {
throw new Error("The selected practice problem could not be loaded.");
}
testcases = spec.testcases;
} else {
const live = await fetchWithRetry<LivePracticeSpec>(
`/problems/${encodeURIComponent(catalogIdentifier)}/practice`,
{ method: "GET" }
);
if (!Array.isArray(live.testcases) || live.testcases.length === 0) {
throw new Error("This problem has no browser-practice tests.");
}
testcases = live.testcases.map((testcase) => ({
input: testcase.input,
expectedOutput: testcase.expectedOutput,
isPublic: Boolean(testcase.isPublic),
}));
}
return runPythonInBrowser(problemId, code, mode, testcases);
}
async function liveExecute(problemId: string, code: string, mode: ExecutionMode, contestId?: string) {
if (mode === "run") {
const queued = await fetchWithRetry<{ id: string; status: string }>("/runner/run", {
method: "POST",
body: JSON.stringify({ problemId, code, languageId: 71, customInput: "" }),
});
const completed = await pollEvaluation<{ status: string; result?: unknown; error?: string }>(
`/runner/jobs/${queued.id}`
);
if (!completed.result) throw new Error(completed.error || "Run evaluation failed");
return normalizeLiveSubmission(problemId, mode, completed.result);
}
const idempotencyKey = crypto.randomUUID();
const queued = await fetchWithRetry<{ _id: string; status: string }>("/submissions", {
method: "POST",
headers: { "Idempotency-Key": idempotencyKey },
body: JSON.stringify({ problemId, code, languageId: 71, ...(contestId ? { contestId } : {}) }),
});
const completed = await pollEvaluation<{ _id: string; status: string; runtime?: number; memory?: number; errorMessage?: string }>(
`/submissions/${queued._id}`
);
return normalizeLiveSubmission(problemId, mode, completed);
}
async function pollEvaluation<T extends { status: string }>(path: string): Promise<T> {
const deadline = Date.now() + 120000;
while (Date.now() < deadline) {
const state = await fetchWithRetry<T>(path, { method: "GET" });
if (!["queued", "processing", "Queued", "Processing"].includes(state.status)) return state;
await wait(500);
}
throw new Error("Evaluation timed out. The job remains available in submission history.");
}
async function persistExecutionRecord(
problemId: string,
code: string,
mode: ExecutionMode,
result: SubmissionResult,
problemIdentifier = problemId,
fallbackTitle?: string
): Promise<void> {
const record = createSubmissionRecord(problemId, code, mode, result, problemIdentifier, fallbackTitle);
// Cache local and legacy mock results. In live mode the backend is the source
// of truth for history and solved-state; caching live results here would
// create a split-brain (e.g. localStorage-derived "solved" status diverging
// from the server). `source` is "mock" both in mock mode and when a live
// call falls back to mock, which is exactly when we want the local cache.
if (result.source !== "live") {
upsertSubmissionRecord(record);
}
void trackEvent({
name: mode === "run" ? "code_run" : "code_submit",
payload: {
problemId,
problemSlug: record.problemSlug,
result: result.status,
passedCount: result.passedCount,
totalCount: result.totalCount,
source: result.source,
},
});
}
function buildHeatmap(history: SubmissionRecord[]) {
const today = new Date();
const data: UserProfile["heatmap"] = [];
for (let i = 119; i >= 0; i -= 1) {
const date = new Date(today);
date.setDate(today.getDate() - i);
const key = date.toISOString().slice(0, 10);
const count = history.filter((entry) => entry.createdAt.slice(0, 10) === key).length;
data.push({ date: key, count });
}
return data;
}
function buildAcceptanceTrend(history: SubmissionRecord[]) {
const monthMap = new Map<string, { accepted: number; total: number }>();
history.forEach((entry) => {
const month = entry.createdAt.slice(0, 7);
const existing = monthMap.get(month) || { accepted: 0, total: 0 };
existing.total += 1;
if (entry.result.status === "Accepted") {
existing.accepted += 1;
}
monthMap.set(month, existing);
});
return Array.from(monthMap.entries())
.sort(([a], [b]) => (a > b ? 1 : -1))
.slice(-6)
.map(([label, value]) => ({
label,
acceptance:
value.total === 0 ? 0 : Math.round((value.accepted / value.total) * 100),
}));
}
function buildTopicProgress(history: SubmissionRecord[]): TopicProgressPoint[] {
const solvedByProblem = new Set(
history
.filter((entry) => entry.mode === "submit" && entry.result.status === "Accepted")
.map((entry) => entry.problemId)
);
const topicTotals = new Map<string, { solved: number; total: number }>();
MOCK_PROBLEMS.forEach((problem) => {
const existing = topicTotals.get(problem.category) || { solved: 0, total: 0 };
existing.total += 1;
if (solvedByProblem.has(problem.id)) {
existing.solved += 1;
}
topicTotals.set(problem.category, existing);
});
// Fold in solved problems served by the live backend (not in the bundle),
// attributed to their topic via remembered metadata, so topic coverage
// reflects imported solves instead of staying at zero.
const catalogIds = new Set(MOCK_PROBLEMS.map((problem) => problem.id));
const importedSolved = new Map<string, ProblemMeta>();
for (const entry of history) {
if (entry.mode !== "submit" || entry.result.status !== "Accepted") continue;
if (catalogIds.has(entry.problemId)) continue;
const meta = resolveProblemMeta(entry.problemSlug) || resolveProblemMeta(entry.problemId);
if (meta) importedSolved.set(meta.slug, meta);
}
for (const meta of importedSolved.values()) {
const existing = topicTotals.get(meta.category) || { solved: 0, total: 0 };
existing.solved += 1;
existing.total += 1;
topicTotals.set(meta.category, existing);
}
return Array.from(topicTotals.entries()).map(([topic, data]) => ({
topic,
solved: data.solved,
total: data.total,
}));
}
async function mockFetchUserProfile(): Promise<UserProfile> {
const session = readStoredSession();
const history = readSubmissionHistoryStore();
const submits = history.filter((entry) => entry.mode === "submit");
const accepted = submits.filter((entry) => entry.result.status === "Accepted");
const fallbackUser = session?.user || {