Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

schemaJson.test.ts

151 lines5.2 KB

1import * as Cause from "effect/Cause";
2import * as Exit from "effect/Exit";
3import * as Result from "effect/Result";
4import * as Schema from "effect/Schema";
5import { describe, expect, it } from "vite-plus/test";
6​
7import {
8 decodeJsonResult,
9 extractJsonObject,
10 formatSchemaError,
11 fromLenientJson,
12} from "./schemaJson.ts";
13​
14const decodeLenientJson = Schema.decodeUnknownSync(fromLenientJson(Schema.Unknown));
15​
16describe("schemaJson helpers", () => {
17 it("extracts a balanced JSON object from surrounding text", () => {
18 expect(
19 extractJsonObject(`Sure, here is the JSON:
20\`\`\`json
22 "subject": "Update README",
23 "body": ""
25\`\`\`
26Done.`),
27 ).toBe(`{
28 "subject": "Update README",
29 "body": ""
30}`);
31 });
32​
33 it("ignores braces inside strings while finding the object boundary", () => {
34 expect(
35 extractJsonObject('prefix {"message":"literal } brace","nested":{"ok":true}} suffix'),
36 ).toBe('{"message":"literal } brace","nested":{"ok":true}}');
37 });
38​
39 it("returns trimmed input when no JSON object starts", () => {
40 expect(extractJsonObject(" no structured output ")).toBe("no structured output");
41 });
42​
43 it("decodes JSON with comments and trailing commas", () => {
44 expect(
45 decodeLenientJson(`{
46 // Comments are valid in settings files.
47 "enabled": true,
48 "values": [1, 2,],
49 }`),
50 ).toEqual({
51 enabled: true,
52 values: [1, 2],
53 });
54 });
55​
56 it("rejects malformed JSON after lenient preprocessing", () => {
57 expect(() => decodeLenientJson('{ "enabled": true,, }')).toThrow();
58 });
59​
60 it("preserves commas before brackets inside string values", () => {
61 expect(decodeLenientJson('{"note":"a,]"}')).toEqual({ note: "a,]" });
62 expect(decodeLenientJson('{"list":["x,}"]}')).toEqual({ list: ["x,}"] });
63 expect(decodeLenientJson('{"values":[1, 2,],}')).toEqual({ values: [1, 2] });
64 });
65​
66 it("formats schema failures with paths without exposing invalid values", () => {
67 const decodeCredential = decodeJsonResult(Schema.Struct({ token: Schema.Number }));
68 const decoded = decodeCredential('{"token":"credential=secret-value"}');
69​
70 expect(Result.isFailure(decoded)).toBe(true);
71 if (Result.isFailure(decoded)) {
72 expect(formatSchemaError(decoded.failure)).toBe('Invalid type\n at ["token"]');
73 }
74 });
75​
76 it("preserves nested paths reported by schema filters", () => {
77 const decode = decodeJsonResult(
78 Schema.String.check(
79 Schema.makeFilter(() => ({
80 path: ["session", "token"],
81 issue: "credential is invalid",
82 })),
83 ),
84 );
85 const decoded = decode('"credential=secret-value"');
86​
87 expect(Result.isFailure(decoded)).toBe(true);
88 if (Result.isFailure(decoded)) {
89 const diagnostic = formatSchemaError(decoded.failure);
90 expect(diagnostic).toBe('Invalid value\n at ["session"]["token"]');
91 expect(diagnostic).not.toContain("credential=secret-value");
92 }
93 });
94​
95 it("does not expose malformed lenient JSON input in diagnostics", () => {
96 const decode = Schema.decodeUnknownExit(fromLenientJson(Schema.Unknown));
97 const exit = decode('{"token":"credential=secret-value",,}');
98​
99 expect(Exit.isFailure(exit)).toBe(true);
100 if (Exit.isFailure(exit)) {
101 const diagnostic = formatSchemaError(exit.cause);
102 expect(diagnostic).toBe("Invalid value");
103 expect(diagnostic).not.toContain("credential=secret-value");
104 }
105 });
106​
107 it("summarizes unexpected defects without serializing their messages", () => {
108 const diagnostic = formatSchemaError(Cause.die(new Error("credential=secret-value")));
109​
110 expect(diagnostic).toBe(
111 "Schema validation failed (failureCount=0, defectCount=1, interruptionCount=0).",
112 );
113 });
114​
115 it("bounds the number of formatted schema issues", () => {
116 const decode = decodeJsonResult(Schema.Struct({ token: Schema.Number }));
117 const failures: Array<Cause.Cause<Schema.SchemaError>> = [];
118 for (let index = 0; index < 10; index += 1) {
119 const decoded = decode(`{"token":"credential=secret-value-${index}"}`);
120 if (Result.isFailure(decoded)) {
121 failures.push(decoded.failure);
122 }
123 }
124​
125 const cause = Cause.fromReasons(failures.flatMap((cause) => cause.reasons));
126 const diagnostic = formatSchemaError(cause);
127 expect(diagnostic.match(/Invalid type/g)).toHaveLength(8);
128 expect(diagnostic).toContain("... and 2 more issue(s)");
129 });
130​
131 it("retains the omitted issue count when bounding long diagnostics", () => {
132 const longPath = Array.from({ length: 16 }, (_, index) => `${index}-${"segment".repeat(16)}`);
133 const decode = decodeJsonResult(
134 Schema.String.check(
135 Schema.makeFilter(() => ({ path: longPath, issue: "credential is invalid" })),
136 ),
137 );
138 const failures: Array<Cause.Cause<Schema.SchemaError>> = [];
139 for (let index = 0; index < 10; index += 1) {
140 const decoded = decode(`"credential=secret-value-${index}"`);
141 if (Result.isFailure(decoded)) {
142 failures.push(decoded.failure);
143 }
144 }
145​
146 const cause = Cause.fromReasons(failures.flatMap((cause) => cause.reasons));
147 const diagnostic = formatSchemaError(cause);
148 expect(diagnostic.length).toBeLessThanOrEqual(2_048);
149 expect(diagnostic.endsWith("\n... and 2 more issue(s)")).toBe(true);
150 });
151});