File size: 3,167 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { NextRequest, NextResponse } from "next/server";
import { withApiError, ApiError } from "@/lib/api-error";
import { resolveProblem } from "@/lib/coding/store";
import { runJavaScriptTests } from "@/lib/coding/harness";
import { gradeCodeRun } from "@/lib/coding/grade";
import { awardCodingXp } from "@/lib/coding/award";
import {
  isExecutableProblem,
  isExecutableLanguage,
  type CodingDifficulty,
} from "@/lib/coding/types";

interface SubmitCodeBody {
  instanceId?: string;
  code?: string;
  durationSecs?: number;
  userId?: number;
}

/**
 * POST /api/coding/submit-code
 * Body: { instanceId, code, durationSecs? }
 *
 * Runs the user's code against the FULL (incl. hidden) test suite in the
 * sandbox. When every test passes, awards "code" XP for the coding category.
 * This is the test-driven correctness check.
 */
export const POST = withApiError(async (request: NextRequest) => {
  let body: SubmitCodeBody;
  try {
    body = await request.json();
  } catch {
    throw new ApiError(400, "Invalid JSON body");
  }

  const { instanceId, code, durationSecs } = body;
  const userId = body.userId ?? 1;

  if (!instanceId || typeof code !== "string" || code.trim().length === 0) {
    throw new ApiError(400, "instanceId and non-empty code are required");
  }

  const problem = resolveProblem(instanceId);
  if (!problem) {
    throw new ApiError(404, "Problem not found (it may have expired — regenerate it).");
  }
  if (!isExecutableProblem(problem)) {
    throw new ApiError(400, "This problem type is graded by written answer, not code.");
  }
  if (!isExecutableLanguage(problem.language)) {
    throw new ApiError(
      400,
      `Auto-grading by execution supports JavaScript/TypeScript only.`,
    );
  }

  const run = runJavaScriptTests(code, problem.entryFunction, problem.tests);
  const grade = gradeCodeRun(run);

  // Hide nothing post-submission — full TDD feedback helps the user learn.
  const baseResponse = {
    correct: grade.isCorrect,
    passed: run.passed,
    total: run.total,
    results: run.results,
    stdout: run.stdout,
    compileError: run.compileError ?? null,
    qualityScore: grade.qualityScore,
  };

  if (!grade.isCorrect) {
    return NextResponse.json({
      ...baseResponse,
      awarded: false,
      message:
        run.compileError != null
          ? "Your code did not compile."
          : `${run.passed}/${run.total} tests passed. Keep going!`,
    });
  }

  const award = await awardCodingXp({
    userId,
    exerciseType: "code",
    description: `Solved ${problem.difficulty} ${problem.type} "${problem.title}" (code)`,
    qualityScore: grade.qualityScore,
    difficulty: problem.difficulty as CodingDifficulty,
    durationSecs,
    metadata: {
      problemId: problem.id,
      problemType: problem.type,
      language: problem.language,
      difficulty: problem.difficulty,
      passed: run.passed,
      total: run.total,
      kind: "code",
    },
  });

  return NextResponse.json({
    ...baseResponse,
    awarded: true,
    ...award,
    message: award.isCriticalHit
      ? "Critical Hit! All tests pass!"
      : "All tests pass — solved!",
  });
});