Download src/lib/api-client.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 38 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/api-client.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/lib/api-client.ts
-
curl -L -o api-client.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/api-client.ts
38 kB
/**
* RotNot API Client
*
* Centralises all fetch calls to /api/* routes behind typed functions.
* This abstraction is the foundation for Issue #18 (mobile/Capacitor deployment):
* swapping `baseUrl` to a remote host lets a Capacitor app hit the same API.
*
* Usage:
* import { apiClient } from "@/lib/api-client";
* const dashboard = await apiClient.getDashboard();
*/
import type { ExportData } from "@/lib/export";
export type { ExportData } from "@/lib/export";
// ---------------------------------------------------------------------------
// Base configuration
// ---------------------------------------------------------------------------
/**
* Base URL for all API requests.
* Defaults to "" (relative) for web; override with an absolute URL for
* Capacitor / React Native / external clients.
*/
let _baseUrl = "";
export function setApiBaseUrl(url: string): void {
_baseUrl = url.replace(/\/$/, ""); // strip trailing slash
}
export function getApiBaseUrl(): string {
return _baseUrl;
}
// ---------------------------------------------------------------------------
// Shared error type
// ---------------------------------------------------------------------------
export class ApiClientError extends Error {
readonly status: number;
readonly body: unknown;
constructor(status: number, body: unknown, message?: string) {
super(message ?? `API error ${status}`);
this.name = "ApiClientError";
this.status = status;
this.body = body;
}
}
// ---------------------------------------------------------------------------
// Core fetch helper
// ---------------------------------------------------------------------------
/** localStorage keys for the visitor's own Hugging Face credentials. */
export const HF_TOKEN_STORAGE_KEY = "rotnot:hfToken";
export const HF_MODEL_STORAGE_KEY = "rotnot:hfModel";
/**
* Read the visitor's Hugging Face credentials from localStorage and turn them
* into request headers. No-op server-side (no `window`). The token never
* leaves the browser except as a per-request header over HTTPS.
*/
function llmHeaders(): Record<string, string> {
if (typeof window === "undefined") return {};
const headers: Record<string, string> = {};
try {
const token = window.localStorage.getItem(HF_TOKEN_STORAGE_KEY);
const model = window.localStorage.getItem(HF_MODEL_STORAGE_KEY);
if (token && token.trim()) headers["x-hf-token"] = token.trim();
if (model && model.trim()) headers["x-hf-model"] = model.trim();
} catch {
/* localStorage unavailable (private mode / SSR) β ignore */
}
return headers;
}
async function apiFetch<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
const url = `${_baseUrl}${path}`;
const res = await fetch(url, {
...init,
headers: {
"Content-Type": "application/json",
...llmHeaders(),
...(init.headers ?? {}),
},
});
let body: unknown;
try {
body = await res.json();
} catch {
body = null;
}
if (!res.ok) {
throw new ApiClientError(res.status, body);
}
return body as T;
}
// ---------------------------------------------------------------------------
// Response types (mirrors server response shapes)
// ---------------------------------------------------------------------------
export interface DashboardUser {
id: number;
name: string;
level: number;
totalXp: number;
currentXp: number;
xpToNextLevel: number;
title: string;
dailyGoalXp: number;
streak: number;
longestStreak: number;
streakFreezes: number;
}
export interface DashboardTodayLog {
xpEarned: number;
activityCount: number;
goalMet: boolean;
}
export interface DashboardCategorySkill {
category: string;
level: number;
totalXp: number;
currentXp: number;
xpToNext: number;
/** ISO timestamp of the most recent activity in this category, or null if never played. */
lastPlayedAt: string | null;
}
export interface DashboardActivity {
id: number;
category: string;
exerciseType: string;
description: string;
totalXp: number;
isCriticalHit: boolean;
createdAt: string;
}
export interface DashboardWeeklyLog {
date: string;
xpEarned: number;
activityCount: number;
goalMet: boolean;
}
export interface DashboardResponse {
user: DashboardUser;
todayLog: DashboardTodayLog | null;
categorySkills: DashboardCategorySkill[];
recentActivities: DashboardActivity[];
weeklyLogs: DashboardWeeklyLog[];
}
export interface XpResult {
baseXp: number;
qualityBonus: number;
isCriticalHit: boolean;
totalXp: number;
newCategoryLevel: number;
levelsGained: number;
multiplierBonus?: number;
multiplierPercent?: number;
unlocks?: string[];
streakFreezesGranted?: number;
}
// Chess
export interface ChessPuzzlePayload {
id: string;
fen: string;
pgn: string;
solution: string[];
rating: number;
themes: string[];
plays: number;
gameUrl: string;
}
export interface ChessSubmitBody {
puzzleId: string;
puzzleRating: number;
solved: boolean;
movesPlayed: number;
solutionLen: number;
durationSecs?: number;
userId?: number;
}
export interface ChessSubmitResponse extends XpResult {
solved: boolean;
newTitle?: string;
titleChanged?: boolean;
}
export interface ChessChallengeBody {
level?: number;
userId?: number;
}
export interface ChessChallengeResponse {
gameId: string;
gameUrl: string;
level: number;
}
export type ChessGameResult = "win" | "draw" | "loss";
export interface ChessGameResultBody {
gameId: string;
level: number;
result: ChessGameResult;
userId?: number;
}
export interface ChessGameResultResponse extends XpResult {
result: ChessGameResult;
level: number;
newTitle?: string;
}
// Logic puzzles
export type LogicPuzzleType =
| "sudoku"
| "sequence"
| "pattern"
| "wordscramble"
| "constraint"
| "mathequation";
export interface LogicGenerateParams {
type?: LogicPuzzleType;
difficulty?: "easy" | "medium" | "hard";
sequenceType?: string;
wordCategory?: string;
}
export interface LogicSubmitResponse extends XpResult {
correct: boolean;
speedBonus?: number;
parSecs?: number | null;
isPersonalBest?: boolean;
prevBestSecs?: number | null;
newTitle?: string;
titleChanged?: boolean;
}
// Feynman
export interface FeynmanScoreBody {
topic: string;
domain?: string;
explanation: string;
wasTaught?: boolean;
isReview?: boolean;
topicId?: string;
deepDiveRequested?: boolean;
durationSecs?: number;
}
export interface FeynmanScoreResponse extends XpResult {
scores: { accuracy: number; completeness: number; clarity: number };
feedback: string;
gaps: string[];
newTitle?: string;
titleChanged?: boolean;
}
export interface FeynmanTeachBody {
topic: string;
domain?: string;
topicId?: string;
}
export interface FeynmanTeachResponse {
explanation: string;
keyTakeaways: string[];
grounded?: boolean;
confidenceScore?: string;
sources?: Array<{
url: string;
title: string;
domain: string;
license: string;
}>;
}
export interface FeynmanTeachDeepBody {
topic: string;
domain?: string;
}
export interface FeynmanTeachDeepResponse {
deeperExplanation: string;
examples: Array<{ title: string; description: string }>;
analogy: string;
misconceptions: Array<{ myth: string; reality: string }>;
relatedConcepts: string;
}
export interface FeynmanAssessBody {
topic: string;
domain?: string;
}
export interface FeynmanAssessResponse {
question: string;
options: string[];
correctIndex: number;
explanation: string;
}
export interface FeynmanPrereqEntry {
id: string;
topic: string;
}
export interface FeynmanPrereqEntryFull extends FeynmanPrereqEntry {
domain: string;
difficulty: string;
}
export interface FeynmanCalibrateResponse {
topics: Array<{
id: string;
topic: string;
domain: string;
difficulty: string;
prereqs?: {
ready: boolean;
met: FeynmanPrereqEntry[];
unmet: FeynmanPrereqEntryFull[];
chain: FeynmanPrereqEntryFull[];
};
}>;
suggestions?: Array<{ id: string; topic: string; domain: string; difficulty: string }>;
profile?: {
totalAttempts: number;
recommendedDifficulty: string;
domains: Record<string, { attempts: number; avgScore: number; masteredCount: number }>;
};
}
export interface FeynmanReviewItem {
id: number;
topicId: string;
topic: string;
domain: string;
difficulty: string;
stage: number;
nextReviewAt: string;
lastReviewAt: string | null;
lastScore: number | null;
totalReviews: number;
successCount: number;
}
export interface FeynmanReviewResponse {
due?: FeynmanReviewItem[];
upcoming?: FeynmanReviewItem[];
retained?: number;
summary?: {
due: number;
upcoming: number;
retained: number;
};
}
// Reading
export interface ReadingArticle {
slug: string;
title: string;
difficulty: "beginner" | "intermediate" | "advanced";
domain: string;
estimatedMinutes: number;
wordCount: number;
body: string;
/** Present on URL-fetched and pasted custom content */
sourceUrl?: string;
/** True for user-supplied content (URL or paste) */
isCustom?: boolean;
}
export interface ReadingContentResponse {
article: ReadingArticle;
}
export interface ReadingContentListResponse {
articles: Omit<ReadingArticle, "body">[];
}
export interface ReadingFetchResponse {
article: ReadingArticle & { sourceUrl: string };
}
export interface ReadingContentParams {
difficulty?: "beginner" | "intermediate" | "advanced";
slug?: string;
random?: boolean;
}
export interface ReadingFetchBody {
url?: string;
text?: string;
title?: string;
}
export interface ReadingQuestionsBody {
slug?: string;
content?: { title: string; body: string };
}
export interface ReadingQuestionsResponse {
questions: Array<{
question: string;
type: "recall" | "inference" | "critical";
}>;
}
export interface ReadingScoreBody {
slug?: string;
content?: { title: string; body: string };
questions: string[];
answers: string[];
durationSecs: number;
}
export interface ReadingScoreResponse extends XpResult {
scores: number[];
feedback: string[];
newTitle?: string;
titleChanged?: boolean;
}
// Critical thinking
export interface CriticalGenerateParams {
type?: "flaw-finder" | "steelman" | "devils-advocate";
difficulty?: "easy" | "medium" | "hard";
}
export interface CriticalScoreBody {
exerciseType: "flaw-finder" | "steelman" | "devils-advocate";
passageId: string;
response: string;
difficulty?: "easy" | "medium" | "hard";
durationSecs?: number;
}
export interface CriticalScoreResponse extends XpResult {
score: number;
feedback: string;
newTitle?: string;
titleChanged?: boolean;
}
// Skill Quests
export interface QuestGenerateParams {
domain?: string;
difficulty?: "easy" | "medium" | "hard";
}
/** Mirrors QuestLesson from /api/quests/generate/route.ts */
export interface QuestLesson {
domain: string;
difficulty: string;
title: string;
lesson: string;
exercises: QuestExercise[];
}
/** Mirrors QuestExercise from /api/quests/generate/route.ts */
export interface QuestExercise {
id: number;
type: "multiple-choice" | "short-answer";
question: string;
options?: string[];
correctAnswer: string;
}
export interface QuestSubmitBody {
domain: string;
title: string;
exercises: QuestExercise[];
/** exerciseId β user answer string */
answers: Record<number, string>;
durationSecs?: number;
userId?: number;
}
export interface GradedExercise {
id: number;
correct: boolean;
feedback: string;
}
export interface QuestSubmitResponse {
graded: GradedExercise[];
correctCount: number;
totalExercises: number;
qualityScore: number;
xp: {
baseXp: number;
qualityBonus: number;
multiplierBonus: number;
multiplierPercent: number;
totalXp: number;
isCriticalHit: boolean;
};
levelUp: boolean;
categoryXp: {
currentXp: number;
xpToNext: number;
level: number;
levelUp: boolean;
};
newTitle?: string;
titleChanged?: boolean;
unlocks: string[];
streakFreezesGranted: number;
}
// Profile
export interface ChessComStatsResponse {
bestRating: number | null;
rapid: number | null;
blitz: number | null;
bullet: number | null;
daily: number | null;
rapidBest: number | null;
blitzBest: number | null;
bulletBest: number | null;
puzzleRushBest: number | null;
tacticsHighest: number | null;
}
export interface ProfileDailyActivity {
date: string;
xpEarned: number;
activityCount: number;
goalMet: boolean;
}
export interface ProfileResponse {
user: DashboardUser;
categorySkills: DashboardCategorySkill[];
skillTreeNodes: Array<{
id: number;
category: string;
name: string;
description: string;
levelRequired: number;
parentId: number | null;
nodeType: string;
unlocked: boolean;
}>;
recentActivities: DashboardActivity[];
chesscomStats: ChessComStatsResponse | null;
/** Last 90 days of daily activity for the streak calendar heatmap */
dailyActivity: ProfileDailyActivity[];
}
// Settings
export interface SettingsResponse {
name: string;
dailyGoalXp: number;
lichessUsername: string;
chesscomUsername: string;
}
export interface SettingsPatchBody {
name?: string;
dailyGoalXp?: number;
lichessUsername?: string;
chesscomUsername?: string;
}
// Coach
export interface CoachPerformanceResponse {
categories: Array<{
category: string;
label: string;
successRate: number;
attempts: number;
avgScore: number;
avgDurationSecs: number | null;
totalXp: number;
level: number;
trend: string;
}>;
overallScore: number;
streakDays: number;
longestStreak: number;
totalExercises: number;
activeDays: number;
lastActivityAt: string | null;
}
export interface CoachFeedbackResponse {
feedback: string;
recommendedExercise: { category: string; difficulty: string };
encouragement: string;
cached: boolean;
}
export interface CoachDifficultyResponse {
recommendations: Record<
string,
{ difficulty: string; boost: boolean; reason: string }
>;
}
export interface CoachWeeklyReportAvailable {
hasReport?: true;
report: string;
highlights: string[];
areasToFocus: string[];
weekOverWeek: {
currentWeekXp: number;
previousWeekXp: number;
xpChange: number;
xpChangePercent: number;
currentWeekExercises: number;
previousWeekExercises: number;
currentWeekActiveDays: number;
previousWeekActiveDays: number;
};
generatedAt: string;
cached: boolean;
}
export interface CoachWeeklyReportUnavailable {
hasReport: false;
activeDaysThisWeek: number;
requiredDays: number;
message: string;
}
export type CoachWeeklyReportResponse =
| CoachWeeklyReportAvailable
| CoachWeeklyReportUnavailable;
// Stats
export interface StatsDailyXp {
date: string;
xpEarned: number;
activityCount: number;
goalMet: boolean;
}
export interface StatsCategoryBreakdown {
totalXp: number;
count: number;
avgScore: number;
totalDuration: number;
}
export interface StatsActivity {
id: number;
category: string;
exerciseType: string;
description: string;
baseXp: number;
qualityBonus: number;
isCriticalHit: boolean;
totalXp: number;
score: number | null;
durationSecs: number | null;
createdAt: string;
}
export interface StatsSummary {
totalExercises: number;
totalXpEarned: number;
totalDuration: number;
criticalHits: number;
criticalHitRate: number;
/** Number of exercises completed with a score > 0 */
correctSolves: number;
/** Percentage of scored exercises that were correct (0β100, 1dp). Only counts activities with a non-null score. */
correctSolveRate: number;
goalDaysMet: number;
currentStreak: number;
longestStreak: number;
level: number;
}
export interface StatsResponse {
/** The chart time window used to fetch dailyXp (7, 30, or 90 days). */
windowDays: 7 | 30 | 90;
dailyXp: StatsDailyXp[];
categoryBreakdown: Record<string, StatsCategoryBreakdown>;
recentActivities: StatsActivity[];
/** Total number of activities matching the current filter. Used for pagination. */
activityTotal: number;
/** Active category filter. null = all categories. */
activityCategory: string | null;
summary: StatsSummary;
}
export interface PersonalBestRecord {
exerciseType: string;
exerciseLabel: string;
difficulty: "easy" | "medium" | "hard";
bestSecs: number;
solveCount: number;
achievedAt: string;
}
export interface PersonalBestsResponse {
records: PersonalBestRecord[];
}
// ββ Best Quality Scores ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export interface BestScoreEntry {
category: string;
categoryLabel: string;
exerciseType: string;
exerciseLabel: string;
bestScore: number; // 0β1, 4 dp
attemptCount: number;
scoredCount: number;
achievedAt: string; // ISO timestamp
}
export interface CategoryBestScore {
category: string;
categoryLabel: string;
bestScore: number;
attemptCount: number;
avgScore: number; // 2 dp
}
export interface BestScoresResponse {
byExerciseType: BestScoreEntry[];
byCategory: CategoryBestScore[];
}
// ββ Achievements ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export type AchievementTier = "bronze" | "silver" | "gold" | "platinum";
export interface AchievementRecord {
id: string;
name: string;
description: string;
tier: AchievementTier;
icon: string;
earned: boolean;
earnedAt: string | null;
progress: number;
}
export interface AchievementSummary {
total: number;
earned: number;
byTier: Record<AchievementTier, { total: number; earned: number }>;
}
export interface AchievementsResponse {
achievements: AchievementRecord[];
summary: AchievementSummary;
}
// ---------------------------------------------------------------------------
// Debate Arena
// ---------------------------------------------------------------------------
export interface DebateStartBody {
topicId?: string;
customTopic?: string;
category?: string;
opponentId?: string;
difficulty?: "easy" | "medium" | "hard";
rounds?: 1 | 3 | 5;
userSide?: "pro" | "con";
}
export interface DebateStartResponse {
topic: {
id: string;
topic: string;
category: string;
description: string;
};
opponent: {
id: string;
name: string;
difficulty: string;
description: string;
icon: string;
era: string | null;
};
rounds: number;
userSide: "pro" | "con";
}
export interface DebateRespondBody {
topic: string;
opponentId: string;
round: number;
totalRounds: number;
userSide: "pro" | "con";
userArgument: string;
history?: Array<{
round: number;
userArgument: string;
opponentArgument: string;
}>;
}
export interface DebateRespondResponse {
round: number;
opponentName: string;
opponentArgument: string;
}
export interface DebateRoundDimensionScores {
[dimensionId: string]: number;
}
export interface DebateRoundDebaterScore {
dimensionScores: DebateRoundDimensionScores;
overallScore: number;
analysis: string;
}
export interface DebateRoundJudgement {
round: number;
user: DebateRoundDebaterScore;
opponent: DebateRoundDebaterScore;
roundWinner: "user" | "opponent" | "tie";
roundSummary: string;
/**
* LangSmith run ID for this judged round.
* Present when LANGSMITH_API_KEY is configured; null otherwise.
* Pass to POST /api/debate/feedback to submit human score overrides.
*/
langsmithRunId: string | null;
}
export interface DebateJudgeBody {
topic: string;
round: number;
totalRounds: number;
userArgument: string;
opponentArgument: string;
opponentName: string;
previousRounds?: DebateRoundJudgement[];
}
export interface DebateSummaryBody {
topic: string;
opponentName: string;
opponentId: string;
opponentDifficulty: "easy" | "medium" | "hard";
rounds: DebateRoundJudgement[];
totalRounds: number;
userSide: "pro" | "con";
durationSecs?: number;
}
export interface DebateFinalJudgement {
rounds: DebateRoundJudgement[];
userTotalScore: number;
opponentTotalScore: number;
winner: "user" | "opponent" | "tie";
overallAnalysis: string;
userStrengths: string[];
userWeaknesses: string[];
suggestions: string[];
}
export interface DebateFeedbackResponse {
/** Number of human scores successfully submitted to LangSmith. */
submitted: number;
/** Present when LangSmith is not configured (graceful skip). */
skipped?: string;
}
export interface DebateSummaryResponse {
judgement: DebateFinalJudgement;
xp: {
baseXp: number;
totalXp: number;
qualityBonus: number;
multiplierBonus: number;
multiplierPercent: number;
isCriticalHit: boolean;
};
qualityScore: number;
levelUp: boolean;
categoryXp: {
currentXp: number;
xpToNext: number;
level: number;
levelUp: boolean;
};
newTitle?: string;
unlocks: string[];
streakFreezesGranted: number;
}
// ---------------------------------------------------------------------------
// Coding Training
// ---------------------------------------------------------------------------
export type CodingProblemType =
| "code-creation"
| "debugging"
| "code-review"
| "architecture";
export type CodingDifficulty = "easy" | "medium" | "hard";
export type CodingLanguage = "javascript" | "typescript" | "python" | "go";
export interface CodingGenerateParams {
type: CodingProblemType;
difficulty: CodingDifficulty;
language: CodingLanguage;
}
export interface CodingTestCase {
name: string;
input: unknown[];
expected: unknown;
hidden?: boolean;
}
export interface PublicCodingProblem {
id: string;
type: CodingProblemType;
language: CodingLanguage;
difficulty: CodingDifficulty;
title: string;
prompt: string;
// executable
entryFunction?: string;
starterCode?: string;
buggyCode?: string;
tests?: CodingTestCase[];
// written
code?: string;
}
export interface CodingGenerateResponse {
instanceId: string;
problem: PublicCodingProblem;
meta: { gradedBy: "tests" | "llm-judge"; executable: boolean; source: string };
}
export interface CodingTestResult {
name: string;
passed: boolean;
expected?: unknown;
actual?: unknown;
error?: string;
}
export interface CodingRunResponse {
ran: boolean;
entryFunction: string;
passed: number;
total: number;
allPassed: boolean;
results: CodingTestResult[];
stdout: string[];
compileError: string | null;
note?: string;
}
export interface CodingXpBreakdown {
baseXp: number;
qualityBonus: number;
isCriticalHit: boolean;
multiplierBonus: number;
totalXp: number;
multiplierPercent: number;
}
export interface CodingCategoryXp {
currentXp: number;
xpToNext: number;
level: number;
levelUp: boolean;
}
/** Fields present only when `awarded` is true. */
export interface CodingAwardFields {
xp: CodingXpBreakdown;
isCriticalHit: boolean;
levelUp: boolean;
newUserLevel: number;
categoryLevelUp: boolean;
newCategoryLevel: number;
categoryXp: CodingCategoryXp;
unlocks: string[];
streakFreezesGranted: number;
newTitle?: string;
}
export interface CodingSubmitCodeResponse extends Partial<CodingAwardFields> {
correct: boolean;
awarded: boolean;
passed: number;
total: number;
results: CodingTestResult[];
stdout: string[];
compileError: string | null;
qualityScore: number;
message: string;
}
export interface CodingSubmitWrittenResponse extends Partial<CodingAwardFields> {
correct: boolean;
awarded: boolean;
qualityScore: number;
gradedBy: "llm-judge" | "heuristic";
feedback: string;
expectations: Array<{ id: string; title?: string; point?: string; severity?: string }>;
verdict: { identified?: string[]; covered?: string[] };
message: string;
}
export interface LlmHealthResponse {
ok: boolean;
provider: "hf" | "anthropic" | "none";
model?: string;
reply?: string;
error?: string;
}
// ---------------------------------------------------------------------------
// API client methods
// ---------------------------------------------------------------------------
export const apiClient = {
// ββ Dashboard ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
getDashboard(): Promise<DashboardResponse> {
return apiFetch("/api/dashboard");
},
// ββ Chess ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
getChessPuzzle(options: { daily?: boolean } = {}): Promise<ChessPuzzlePayload> {
const params = options.daily ? "?daily=true" : "";
return apiFetch(`/api/chess/puzzle${params}`);
},
submitChessPuzzle(body: ChessSubmitBody): Promise<ChessSubmitResponse> {
return apiFetch("/api/chess/submit", {
method: "POST",
body: JSON.stringify(body),
});
},
createStockfishChallenge(body: ChessChallengeBody = {}): Promise<ChessChallengeResponse> {
return apiFetch("/api/chess/challenge", {
method: "POST",
body: JSON.stringify(body),
});
},
submitChessGameResult(body: ChessGameResultBody): Promise<ChessGameResultResponse> {
return apiFetch("/api/chess/game-result", {
method: "POST",
body: JSON.stringify(body),
});
},
// ββ Logic Puzzles ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
generateLogicPuzzle(params: LogicGenerateParams = {}): Promise<unknown> {
const qs = new URLSearchParams();
if (params.type) qs.set("type", params.type);
if (params.difficulty) qs.set("difficulty", params.difficulty);
if (params.sequenceType) qs.set("sequenceType", params.sequenceType);
if (params.wordCategory) qs.set("wordCategory", params.wordCategory);
const query = qs.toString();
return apiFetch(`/api/logic/generate${query ? `?${query}` : ""}`);
},
submitLogicPuzzle(body: Record<string, unknown>): Promise<LogicSubmitResponse> {
return apiFetch("/api/logic/submit", {
method: "POST",
body: JSON.stringify(body),
});
},
// ββ Feynman ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
scoreFeynman(body: FeynmanScoreBody): Promise<FeynmanScoreResponse> {
return apiFetch("/api/feynman/score", {
method: "POST",
body: JSON.stringify(body),
});
},
teachFeynman(body: FeynmanTeachBody): Promise<FeynmanTeachResponse> {
return apiFetch("/api/feynman/teach", {
method: "POST",
body: JSON.stringify(body),
});
},
teachFeynmanDeep(body: FeynmanTeachDeepBody): Promise<FeynmanTeachDeepResponse> {
return apiFetch("/api/feynman/teach-deep", {
method: "POST",
body: JSON.stringify(body),
});
},
assessFeynman(body: FeynmanAssessBody): Promise<FeynmanAssessResponse> {
return apiFetch("/api/feynman/assess", {
method: "POST",
body: JSON.stringify(body),
});
},
getCalibratedTopics(options: {
domain?: string;
count?: number;
userId?: number;
} = {}): Promise<FeynmanCalibrateResponse> {
const qs = new URLSearchParams();
if (options.domain) qs.set("domain", options.domain);
if (options.count !== undefined) qs.set("count", String(options.count));
if (options.userId !== undefined) qs.set("userId", String(options.userId));
const query = qs.toString();
return apiFetch(`/api/feynman/calibrate${query ? `?${query}` : ""}`);
},
getFeynmanReviews(options: { summary?: boolean } = {}): Promise<FeynmanReviewResponse> {
const qs = options.summary ? "?summary=true" : "";
return apiFetch(`/api/feynman/review${qs}`);
},
curateFeynmanSources(body: {
topicId: string;
grounded?: boolean;
}): Promise<{ sources: unknown[]; sourceReady: boolean; sourceCount: number }> {
return apiFetch("/api/feynman/curate", {
method: "POST",
body: JSON.stringify(body),
});
},
verifyFeynmanSources(options: {
method?: "GET" | "POST";
limit?: number;
} = {}): Promise<unknown> {
if (options.method === "GET" || !options.method) {
return apiFetch("/api/feynman/verify");
}
return apiFetch("/api/feynman/verify", {
method: "POST",
body: JSON.stringify({ limit: options.limit }),
});
},
// ββ Deep Reading βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
getReadingContent(params: ReadingContentParams = {}): Promise<ReadingContentResponse> {
const qs = new URLSearchParams();
if (params.difficulty) qs.set("difficulty", params.difficulty);
if (params.slug) qs.set("slug", params.slug);
if (params.random) qs.set("random", "true");
const query = qs.toString();
return apiFetch(`/api/reading/content${query ? `?${query}` : ""}`);
},
fetchReadingContent(body: ReadingFetchBody): Promise<ReadingFetchResponse> {
return apiFetch("/api/reading/fetch", {
method: "POST",
body: JSON.stringify(body),
});
},
generateReadingQuestions(
body: ReadingQuestionsBody,
): Promise<ReadingQuestionsResponse> {
return apiFetch("/api/reading/questions", {
method: "POST",
body: JSON.stringify(body),
});
},
scoreReading(body: ReadingScoreBody): Promise<ReadingScoreResponse> {
return apiFetch("/api/reading/score", {
method: "POST",
body: JSON.stringify(body),
});
},
// ββ Critical Thinking ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
generateCriticalExercise(params: CriticalGenerateParams = {}): Promise<unknown> {
const qs = new URLSearchParams();
if (params.type) qs.set("type", params.type);
if (params.difficulty) qs.set("difficulty", params.difficulty);
const query = qs.toString();
return apiFetch(`/api/critical/generate${query ? `?${query}` : ""}`);
},
scoreCritical(body: CriticalScoreBody): Promise<CriticalScoreResponse> {
return apiFetch("/api/critical/score", {
method: "POST",
body: JSON.stringify(body),
});
},
// ββ Skill Quests βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
generateQuest(params: QuestGenerateParams = {}): Promise<QuestLesson> {
const qs = new URLSearchParams();
if (params.domain) qs.set("domain", params.domain);
if (params.difficulty) qs.set("difficulty", params.difficulty);
const query = qs.toString();
return apiFetch(`/api/quests/generate${query ? `?${query}` : ""}`);
},
submitQuest(body: QuestSubmitBody): Promise<QuestSubmitResponse> {
return apiFetch("/api/quests/submit", {
method: "POST",
body: JSON.stringify(body),
});
},
// ββ Profile ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
getProfile(): Promise<ProfileResponse> {
return apiFetch("/api/profile");
},
// ββ Settings βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
getSettings(): Promise<SettingsResponse> {
return apiFetch("/api/settings");
},
updateSettings(body: SettingsPatchBody): Promise<SettingsResponse> {
return apiFetch("/api/settings", {
method: "PATCH",
body: JSON.stringify(body),
});
},
// ββ LLM (Hugging Face) βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Test the visitor's LLM credentials (sent via x-hf-token/x-hf-model headers
* from localStorage). Returns ok + provider/model on success, or an error
* message β always HTTP 200, never throws on a bad token.
*/
getLlmHealth(): Promise<LlmHealthResponse> {
return apiFetch("/api/llm/health");
},
// ββ Data Export ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
exportData(): Promise<ExportData> {
return apiFetch("/api/export");
},
// ββ Stats ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
getStats(opts?: {
days?: 7 | 30 | 90;
activityOffset?: number;
activityLimit?: number;
activityCategory?: string;
}): Promise<StatsResponse> {
const params = new URLSearchParams();
if (opts?.days) params.set("days", String(opts.days));
if (opts?.activityOffset !== undefined)
params.set("activityOffset", String(opts.activityOffset));
if (opts?.activityLimit !== undefined)
params.set("activityLimit", String(opts.activityLimit));
if (opts?.activityCategory && opts.activityCategory !== "all")
params.set("activityCategory", opts.activityCategory);
const qs = params.toString() ? `?${params.toString()}` : "";
return apiFetch(`/api/stats${qs}`);
},
getPersonalBests(): Promise<PersonalBestsResponse> {
return apiFetch("/api/stats/personal-bests");
},
getBestScores(): Promise<BestScoresResponse> {
return apiFetch("/api/stats/best-scores");
},
getAchievements(): Promise<AchievementsResponse> {
return apiFetch("/api/stats/achievements");
},
// ββ Coach ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
getCoachPerformance(): Promise<CoachPerformanceResponse> {
return apiFetch("/api/coach/performance");
},
getCoachDifficulty(): Promise<CoachDifficultyResponse> {
return apiFetch("/api/coach/difficulty");
},
getCoachFeedback(body?: { override?: boolean }): Promise<CoachFeedbackResponse> {
return apiFetch("/api/coach/feedback", {
method: "POST",
body: JSON.stringify(body ?? {}),
});
},
getWeeklyReport(body?: { force?: boolean }): Promise<CoachWeeklyReportResponse> {
return apiFetch("/api/coach/weekly-report", {
method: "POST",
body: JSON.stringify(body ?? {}),
});
},
// ββ Debate Arena βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
startDebate(body: DebateStartBody): Promise<DebateStartResponse> {
return apiFetch("/api/debate/start", {
method: "POST",
body: JSON.stringify(body),
});
},
debateRespond(body: DebateRespondBody): Promise<DebateRespondResponse> {
return apiFetch("/api/debate/respond", {
method: "POST",
body: JSON.stringify(body),
});
},
debateJudge(body: DebateJudgeBody): Promise<DebateRoundJudgement> {
return apiFetch("/api/debate/judge", {
method: "POST",
body: JSON.stringify(body),
});
},
debateSummary(body: DebateSummaryBody): Promise<DebateSummaryResponse> {
return apiFetch("/api/debate/summary", {
method: "POST",
body: JSON.stringify(body),
});
},
/**
* POST /api/debate/feedback
* Submit human override scores for a debate round to LangSmith.
* Enables the reflector to detect judge/human score divergence.
*/
submitDebateFeedback(
runId: string,
scores: Record<string, number>,
): Promise<DebateFeedbackResponse> {
return apiFetch("/api/debate/feedback", {
method: "POST",
body: JSON.stringify({ runId, scores }),
});
},
// ββ Coding Training ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
generateCodingProblem(
params: CodingGenerateParams,
): Promise<CodingGenerateResponse> {
return apiFetch("/api/coding/generate", {
method: "POST",
body: JSON.stringify(params),
});
},
runCode(instanceId: string, code: string): Promise<CodingRunResponse> {
return apiFetch("/api/coding/run", {
method: "POST",
body: JSON.stringify({ instanceId, code }),
});
},
submitCode(
instanceId: string,
code: string,
durationSecs?: number,
): Promise<CodingSubmitCodeResponse> {
return apiFetch("/api/coding/submit-code", {
method: "POST",
body: JSON.stringify({ instanceId, code, durationSecs }),
});
},
submitWrittenAnswer(
instanceId: string,
answer: string,
durationSecs?: number,
): Promise<CodingSubmitWrittenResponse> {
return apiFetch("/api/coding/submit-written", {
method: "POST",
body: JSON.stringify({ instanceId, answer, durationSecs }),
});
},
} as const;
/**
* RotNot API Client
*
* Centralises all fetch calls to /api/* routes behind typed functions.
* This abstraction is the foundation for Issue #18 (mobile/Capacitor deployment):
* swapping `baseUrl` to a remote host lets a Capacitor app hit the same API.
*
* Usage:
* import { apiClient } from "@/lib/api-client";
* const dashboard = await apiClient.getDashboard();
*/
import type { ExportData } from "@/lib/export";
export type { ExportData } from "@/lib/export";
// ---------------------------------------------------------------------------
// Base configuration
// ---------------------------------------------------------------------------
/**
* Base URL for all API requests.
* Defaults to "" (relative) for web; override with an absolute URL for
* Capacitor / React Native / external clients.
*/
let _baseUrl = "";
export function setApiBaseUrl(url: string): void {
_baseUrl = url.replace(/\/$/, ""); // strip trailing slash
}
export function getApiBaseUrl(): string {
return _baseUrl;
}
// ---------------------------------------------------------------------------
// Shared error type
// ---------------------------------------------------------------------------
export class ApiClientError extends Error {
readonly status: number;
readonly body: unknown;
constructor(status: number, body: unknown, message?: string) {
super(message ?? `API error ${status}`);
this.name = "ApiClientError";
this.status = status;
this.body = body;
}
}
// ---------------------------------------------------------------------------
// Core fetch helper
// ---------------------------------------------------------------------------
/** localStorage keys for the visitor's own Hugging Face credentials. */
export const HF_TOKEN_STORAGE_KEY = "rotnot:hfToken";
export const HF_MODEL_STORAGE_KEY = "rotnot:hfModel";
/**
* Read the visitor's Hugging Face credentials from localStorage and turn them
* into request headers. No-op server-side (no `window`). The token never
* leaves the browser except as a per-request header over HTTPS.
*/
function llmHeaders(): Record<string, string> {
if (typeof window === "undefined") return {};
const headers: Record<string, string> = {};
try {
const token = window.localStorage.getItem(HF_TOKEN_STORAGE_KEY);
const model = window.localStorage.getItem(HF_MODEL_STORAGE_KEY);
if (token && token.trim()) headers["x-hf-token"] = token.trim();
if (model && model.trim()) headers["x-hf-model"] = model.trim();
} catch {
/* localStorage unavailable (private mode / SSR) β ignore */
}
return headers;
}
async function apiFetch<T>(
path: string,
init: RequestInit = {},
): Promise<T> {
const url = `${_baseUrl}${path}`;
const res = await fetch(url, {
...init,
headers: {
"Content-Type": "application/json",
...llmHeaders(),
...(init.headers ?? {}),
},
});
let body: unknown;
try {
body = await res.json();
} catch {
body = null;
}
if (!res.ok) {
throw new ApiClientError(res.status, body);