File size: 12,388 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
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
/**
 * Unit tests for parseClaudeJson (src/lib/claude.ts).
 *
 * parseClaudeJson strips markdown code fences that Claude sometimes wraps
 * around JSON responses despite explicit instructions not to, then parses
 * the result. It is used in 15+ API routes β€” correctness here directly
 * impacts all AI-backed features.
 *
 * Covers:
 *   - Clean JSON (object, array, primitive)
 *   - Markdown code fences: ```json ... ``` (with and without "json" tag)
 *   - Bare triple-backtick fences: ``` ... ```
 *   - Leading / trailing whitespace (with and without fences)
 *   - Mixed whitespace inside fences (newlines, spaces)
 *   - Nested objects and arrays
 *   - Invalid JSON β†’ SyntaxError
 *   - Empty string β†’ SyntaxError
 *   - Type parameter passthrough (generic inference)
 *   - Uppercase JSON tag: ```JSON ... ``` (case-insensitive strip)
 *   - Fence with trailing newline after closing backticks
 */

import { describe, it, expect } from "vitest";
import { parseClaudeJson } from "../claude";

// ─── Helpers ─────────────────────────────────────────────────────────────────

function fence(lang: string, content: string): string {
  return `\`\`\`${lang}\n${content}\n\`\`\``;
}

function bareFence(content: string): string {
  return `\`\`\`\n${content}\n\`\`\``;
}

// ─── Clean JSON ───────────────────────────────────────────────────────────────

describe("parseClaudeJson β€” clean JSON (no fences)", () => {
  it("parses a plain JSON object", () => {
    const result = parseClaudeJson<{ score: number }>('{"score":0.85}');
    expect(result).toEqual({ score: 0.85 });
  });

  it("parses a plain JSON array", () => {
    const result = parseClaudeJson<string[]>('["a","b","c"]');
    expect(result).toEqual(["a", "b", "c"]);
  });

  it("parses a JSON number", () => {
    const result = parseClaudeJson<number>("42");
    expect(result).toBe(42);
  });

  it("parses a JSON boolean", () => {
    expect(parseClaudeJson<boolean>("true")).toBe(true);
    expect(parseClaudeJson<boolean>("false")).toBe(false);
  });

  it("parses a JSON null", () => {
    expect(parseClaudeJson<null>("null")).toBeNull();
  });
});

// ─── Markdown fences: ```json ... ``` ────────────────────────────────────────

describe("parseClaudeJson β€” ```json fences", () => {
  it("strips ```json fence and parses the inner JSON", () => {
    const input = fence("json", '{"report":"great week","highlights":["a"]}');
    const result = parseClaudeJson<{ report: string; highlights: string[] }>(input);
    expect(result.report).toBe("great week");
    expect(result.highlights).toEqual(["a"]);
  });

  it("strips ```json fence around a JSON array", () => {
    const input = fence("json", '["x","y"]');
    expect(parseClaudeJson<string[]>(input)).toEqual(["x", "y"]);
  });

  it("handles multiline JSON object inside ```json fence", () => {
    const inner = JSON.stringify(
      {
        question: "What is entropy?",
        options: ["A", "B", "C", "D"],
        correctIndex: 2,
        explanation: "Because thermodynamics.",
      },
      null,
      2,
    );
    const input = fence("json", inner);
    const result = parseClaudeJson<{
      question: string;
      options: string[];
      correctIndex: number;
      explanation: string;
    }>(input);
    expect(result.question).toBe("What is entropy?");
    expect(result.options).toHaveLength(4);
    expect(result.correctIndex).toBe(2);
  });
});

// ─── Bare triple-backtick fences ─────────────────────────────────────────────

describe("parseClaudeJson β€” bare ``` fences (no language tag)", () => {
  it("strips bare ``` fence and parses inner JSON", () => {
    const input = bareFence('{"score":1,"feedback":"perfect"}');
    const result = parseClaudeJson<{ score: number; feedback: string }>(input);
    expect(result.score).toBe(1);
    expect(result.feedback).toBe("perfect");
  });

  it("strips bare ``` fence around a JSON array", () => {
    const input = bareFence("[1,2,3]");
    expect(parseClaudeJson<number[]>(input)).toEqual([1, 2, 3]);
  });
});

// ─── Case-insensitive fence tag ───────────────────────────────────────────────

describe("parseClaudeJson β€” case-insensitive fence tag", () => {
  it("strips ```JSON fence (uppercase tag)", () => {
    const input = fence("JSON", '{"ok":true}');
    const result = parseClaudeJson<{ ok: boolean }>(input);
    expect(result.ok).toBe(true);
  });

  it("strips ```Json fence (mixed-case tag)", () => {
    const input = fence("Json", '{"value":99}');
    const result = parseClaudeJson<{ value: number }>(input);
    expect(result.value).toBe(99);
  });
});

// ─── Whitespace handling ──────────────────────────────────────────────────────

describe("parseClaudeJson β€” leading / trailing whitespace", () => {
  it("strips leading and trailing spaces from plain JSON", () => {
    const result = parseClaudeJson<{ n: number }>("   { \"n\": 7 }   ");
    expect(result.n).toBe(7);
  });

  it("strips leading and trailing newlines from plain JSON", () => {
    const result = parseClaudeJson<{ n: number }>("\n\n{\"n\":7}\n\n");
    expect(result.n).toBe(7);
  });

  it("handles extra whitespace after opening fence tag", () => {
    // ```json   (trailing spaces after tag)
    const input = "```json   \n{\"x\":1}\n```";
    const result = parseClaudeJson<{ x: number }>(input);
    expect(result.x).toBe(1);
  });

  it("handles trailing whitespace after closing fence backticks", () => {
    const input = "```json\n{\"x\":2}\n```   ";
    const result = parseClaudeJson<{ x: number }>(input);
    expect(result.x).toBe(2);
  });
});

// ─── Nested structures ────────────────────────────────────────────────────────

describe("parseClaudeJson β€” nested objects and arrays", () => {
  it("correctly parses deeply nested JSON inside a fence", () => {
    const data = {
      user: {
        name: "Alice",
        scores: [1, 2, 3],
        meta: { active: true },
      },
    };
    const input = fence("json", JSON.stringify(data));
    const result = parseClaudeJson<typeof data>(input);
    expect(result.user.name).toBe("Alice");
    expect(result.user.scores).toEqual([1, 2, 3]);
    expect(result.user.meta.active).toBe(true);
  });

  it("handles an array of objects inside a fence", () => {
    const data = [{ id: 1, label: "a" }, { id: 2, label: "b" }];
    const input = fence("json", JSON.stringify(data));
    const result = parseClaudeJson<typeof data>(input);
    expect(result).toHaveLength(2);
    expect(result[0].label).toBe("a");
    expect(result[1].id).toBe(2);
  });
});

// ─── Error cases ──────────────────────────────────────────────────────────────

describe("parseClaudeJson β€” invalid input throws SyntaxError", () => {
  it("throws SyntaxError for invalid JSON (no fences)", () => {
    expect(() => parseClaudeJson("not valid json")).toThrow(SyntaxError);
  });

  it("throws SyntaxError for empty string", () => {
    expect(() => parseClaudeJson("")).toThrow(SyntaxError);
  });

  it("throws SyntaxError for a fence containing invalid JSON", () => {
    const input = fence("json", "{ broken json: here }");
    expect(() => parseClaudeJson(input)).toThrow(SyntaxError);
  });

  it("throws SyntaxError for a partial JSON object", () => {
    expect(() => parseClaudeJson('{"key": "value"')).toThrow(SyntaxError);
  });

  it("throws SyntaxError for plain prose text", () => {
    expect(() =>
      parseClaudeJson("Here is the analysis you requested: blah blah."),
    ).toThrow(SyntaxError);
  });
});

// ─── Real-world Claude response patterns ─────────────────────────────────────

describe("parseClaudeJson β€” realistic Claude response formats", () => {
  it("parses a typical Feynman score response", () => {
    const text = fence(
      "json",
      JSON.stringify({
        scores: {
          clarity: 4,
          accuracy: 3,
          depth: 2,
          examples: 3,
        },
        gaps: ["Didn't mention eigenvalues"],
        feedback: "Good explanation overall.",
        overallScore: 0.72,
      }),
    );
    const result = parseClaudeJson<{
      scores: Record<string, number>;
      gaps: string[];
      feedback: string;
      overallScore: number;
    }>(text);
    expect(result.overallScore).toBe(0.72);
    expect(result.gaps).toHaveLength(1);
    expect(result.scores.clarity).toBe(4);
  });

  it("parses a typical assess route response", () => {
    const text = fence(
      "json",
      JSON.stringify({
        question: "Which principle does X illustrate?",
        options: ["Option A", "Option B", "Option C", "Option D"],
        correctIndex: 1,
        explanation: "Because of Y.",
      }),
    );
    const result = parseClaudeJson<{
      question: string;
      options: string[];
      correctIndex: number;
      explanation: string;
    }>(text);
    expect(result.options).toHaveLength(4);
    expect(result.correctIndex).toBe(1);
  });

  it("parses a typical quest lesson response with MC and SA questions", () => {
    const lesson = {
      title: "Introduction to Recursion",
      introduction: "Recursion is...",
      keyPoints: ["Base case", "Recursive case"],
      multipleChoice: [
        {
          question: "What stops infinite recursion?",
          options: ["A", "B", "C", "D"],
          correctIndex: 0,
        },
      ],
      shortAnswer: {
        question: "Explain tail recursion.",
        sampleAnswer: "When the recursive call is the last operation.",
      },
    };
    const result = parseClaudeJson<typeof lesson>(fence("json", JSON.stringify(lesson)));
    expect(result.title).toBe("Introduction to Recursion");
    expect(result.multipleChoice).toHaveLength(1);
    expect(result.shortAnswer.question).toBe("Explain tail recursion.");
  });

  it("handles JSON without fences (some Claude versions don't add them)", () => {
    const payload = { score: 0.9, isCorrect: true };
    const result = parseClaudeJson<typeof payload>(JSON.stringify(payload));
    expect(result.score).toBe(0.9);
    expect(result.isCorrect).toBe(true);
  });
});

// ─── Reasoning-model output (prose / thinking around the JSON) ────────────────

describe("parseClaudeJson β€” reasoning-model output", () => {
  it("extracts JSON when a reasoning model adds a prose preamble", () => {
    const text =
      'We are asked to return only JSON. The answer is: {"identifiedIssueIds":["i1"],"falsePositives":1,"feedback":"ok"}';
    const result = parseClaudeJson<{ identifiedIssueIds: string[]; falsePositives: number }>(text);
    expect(result.identifiedIssueIds).toEqual(["i1"]);
    expect(result.falsePositives).toBe(1);
  });

  it("extracts JSON when there is trailing prose after the object", () => {
    const text = '{"coveredPointIds":["p1","p2"]}\n\nThat completes the grading.';
    const result = parseClaudeJson<{ coveredPointIds: string[] }>(text);
    expect(result.coveredPointIds).toEqual(["p1", "p2"]);
  });

  it("strips <think> blocks before parsing", () => {
    const text = '<think>Let me reason about this first…</think>\n{"score":0.8}';
    const result = parseClaudeJson<{ score: number }>(text);
    expect(result.score).toBe(0.8);
  });

  it("extracts an array span wrapped in prose", () => {
    const text = 'Here are the ids: ["a","b","c"] β€” done.';
    const result = parseClaudeJson<string[]>(text);
    expect(result).toEqual(["a", "b", "c"]);
  });
});