Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import * as Schema from "effect/Schema";
7import * as SchemaGetter from "effect/SchemaGetter";
8import * as SchemaIssue from "effect/SchemaIssue";
9import * as SchemaTransformation from "effect/SchemaTransformation";
10
11const MAX_SCHEMA_DIAGNOSTIC_ISSUES = 8;
12const MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS = 16;
13const MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH = 64;
14const MAX_SCHEMA_DIAGNOSTIC_LENGTH = 2_048;
15
16interface SchemaDiagnosticIssue {
17 readonly message: string;
18 readonly path: ReadonlyArray<PropertyKey>;
19}
20
21// Schema's default formatter includes actual values. These diagnostics cross
22// process and UI boundaries, so retain only issue kinds and bounded paths.
23
24function truncateDiagnostic(value: string, maxLength: number): string {
25 return value.length <= maxLength ? value : `${value.slice(0, maxLength - 3)}...`;
26}
27
28function formatDiagnosticPathSegment(key: PropertyKey): string {
29 if (typeof key === "number") {
30 return `[${key}]`;
31 }
32 const value = truncateDiagnostic(
33 typeof key === "symbol" ? String(key) : key,
34 MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH,
35 );
36 return `[${JSON.stringify(value)}]`;
37}
38
39function formatDiagnosticIssue(issue: SchemaDiagnosticIssue): string {
40 if (issue.path.length === 0) {
41 return issue.message;
42 }
43 const path = issue.path
44 .slice(0, MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS)
45 .map(formatDiagnosticPathSegment)
46 .join("");
47 const suffix = issue.path.length > MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS ? "[...]" : "";
48 return `${issue.message}\n at ${path}${suffix}`;
49}
50
51function schemaDiagnosticMessage(issue: SchemaIssue.Issue): string {
52 switch (issue._tag) {
53 case "InvalidType":
54 return "Invalid type";
55 case "InvalidValue":
56 case "Filter":
57 case "AnyOf":
58 case "Encoding":
59 case "Pointer":
60 case "Composite":
61 return "Invalid value";
62 case "MissingKey":
63 return "Missing key";
64 case "UnexpectedKey":
65 return "Unexpected key";
66 case "Forbidden":
67 return "Forbidden operation";
68 case "OneOf":
69 return "Expected exactly one schema member to match";
70 }
71}
72
73function collectSchemaDiagnosticIssues(
74 issue: SchemaIssue.Issue,
75 path: ReadonlyArray<PropertyKey>,
76 diagnostics: Array<SchemaDiagnosticIssue>,
77): number {
78 switch (issue._tag) {
79 case "Encoding":
80 return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);
81 case "Filter":
82 if (issue.issue._tag !== "InvalidValue") {
83 return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);
84 }
85 break;
86 case "Pointer":
87 return collectSchemaDiagnosticIssues(issue.issue, [...path, ...issue.path], diagnostics);
88 case "Composite":
89 return issue.issues.reduce(
90 (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),
91 0,
92 );
93 case "AnyOf":
94 if (issue.issues.length > 0) {
95 return issue.issues.reduce(
96 (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),
97 0,
98 );
99 }
100 break;
101 }
102
103 if (diagnostics.length < MAX_SCHEMA_DIAGNOSTIC_ISSUES) {
104 diagnostics.push({ message: schemaDiagnosticMessage(issue), path });
105 }
106 return 1;
107}
108
109export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
110 schema: S,
111) => {
112 const decode = Schema.decodeExit(Schema.fromJsonString(schema));
113 return (input: string) => {
114 const result = decode(input);
115 if (Exit.isFailure(result)) {
116 return Result.fail(result.cause);
117 }
118 return Result.succeed(result.value);
119 };
120};
121
122export const decodeUnknownJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
123 schema: S,
124) => {
125 const decode = Schema.decodeUnknownExit(Schema.fromJsonString(schema));
126 return (input: unknown) => {
127 const result = decode(input);
128 if (Exit.isFailure(result)) {
129 return Result.fail(result.cause);
130 }
131 return Result.succeed(result.value);
132 };
133};
134
135export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
136 const issues: Array<SchemaDiagnosticIssue> = [];
137 let issueCount = 0;
138 let failureCount = 0;
139 let defectCount = 0;
140 let interruptionCount = 0;
141
142 for (const reason of cause.reasons) {
143 switch (reason._tag) {
144 case "Fail":
145 failureCount += 1;
146 if (Schema.isSchemaError(reason.error)) {
147 issueCount += collectSchemaDiagnosticIssues(reason.error.issue, [], issues);
148 }
149 break;
150 case "Die":
151 defectCount += 1;
152 break;
153 case "Interrupt":
154 interruptionCount += 1;
155 break;
156 }
157 }
158
159 if (issues.length === 0) {
160 return `Schema validation failed (failureCount=${failureCount}, defectCount=${defectCount}, interruptionCount=${interruptionCount}).`;
161 }
162
163 const omittedIssueCount = issueCount - issues.length;
164 const formatted = issues.map(formatDiagnosticIssue).join("\n");
165 if (omittedIssueCount === 0) {
166 return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH);
167 }
168 const suffix = `\n... and ${omittedIssueCount} more issue(s)`;
169 return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH - suffix.length) + suffix;
170};
171
172/**
173 * A `Getter` that parses a lenient JSON string (tolerating trailing commas
174 * and JS-style comments) into an unknown value.
175 *
176 * Mirrors `SchemaGetter.parseJson()` but strips JSONC syntax before parsing.
177 */
178const decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
179
180const parseLenientJsonGetter = SchemaGetter.onSome((input: string) => {
181 // Strip single-line comments - alternation preserves quoted strings.
182 let stripped = input.replace(
183 /("(?:[^"\\]|\\.)*")|\/\/[^\n]*/g,
184 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
185 );
186
187 // Strip multi-line comments.
188 stripped = stripped.replace(
189 /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\//g,
190 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
191 );
192
193 // Strip trailing commas before `}` or `]`. The alternation preserves quoted
194 // strings so a comma inside a string value (e.g. `{"note":"a,]"}`) is not
195 // mistaken for a trailing comma and removed.
196 stripped = stripped.replace(
197 /("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g,
198 (match, stringLiteral: string | undefined, bracket: string | undefined) =>
199 stringLiteral ? match : (bracket ?? ""),
200 );
201
202 return decodeJsonString(stripped).pipe(
203 Effect.map(Option.some),
204 Effect.mapError((error) => error.issue),
205 );
206});
207
208/**
209 * Schema transformation: lenient JSONC string ↔ unknown.
210 *
211 * Same API as `SchemaTransformation.fromJsonString`, but the decode side
212 * strips trailing commas and JS-style comments before parsing.
213 * Encoding produces strict JSON via `JSON.stringify`.
214 */
215export const fromLenientJsonString = new SchemaTransformation.Transformation(
216 parseLenientJsonGetter,
217 SchemaGetter.stringifyJson(),
218);
219
220export const prettyJsonString = SchemaGetter.parseJson<string>().compose(
221 SchemaGetter.stringifyJson({ space: 2 }),
222);
223
224/**
225 * Build a schema that decodes a lenient JSON string into `A`.
226 *
227 * Drop-in replacement for `Schema.fromJsonString(schema)` that tolerates
228 * trailing commas and comments in the input.
229 */
230export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
231 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
232
233export function extractJsonObject(raw: string): string {
234 const trimmed = raw.trim();
235 if (trimmed.length === 0) {
236 return trimmed;
237 }
238
239 const start = trimmed.indexOf("{");
240 if (start < 0) {
241 return trimmed;
242 }
243
244 let depth = 0;
245 let inString = false;
246 let escaping = false;
247 for (let index = start; index < trimmed.length; index += 1) {
248 const char = trimmed[index];
249 if (inString) {
250 if (escaping) {
251 escaping = false;
252 } else if (char === "\\") {
253 escaping = true;
254 } else if (char === '"') {
255 inString = false;
256 }
257 continue;
258 }
259
260 if (char === '"') {
261 inString = true;
262 continue;
263 }
264
265 if (char === "{") {
266 depth += 1;
267 continue;
268 }
269
270 if (char === "}") {
271 depth -= 1;
272 if (depth === 0) {
273 return trimmed.slice(start, index + 1);
274 }
275 }
276 }
277
278 return trimmed.slice(start);
279}
280
281/**
282 * Build a JSON string schema that encodes with stable 2-space formatting.
283 *
284 * Decode behavior matches `Schema.fromJsonString(schema)`. Encode behavior
285 * keeps the transformation schema-based while preserving human-readable JSON.
286 */
287export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
288 Schema.fromJsonString(schema).pipe(
289 Schema.encode({
290 decode: prettyJsonString,
291 encode: prettyJsonString,
292 }),
293 );