RotNot / src /lib /__tests__ /claude.test.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
12.4 kB
/**
* 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"]);
});
});