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

schemaJson.ts

242 lines7.0 KB

1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import * as SchemaGetter from "effect/SchemaGetter";
7import * as SchemaIssue from "effect/SchemaIssue";
8import * as SchemaTransformation from "effect/SchemaTransformation";
9​
10const MAX_SCHEMA_DIAGNOSTIC_ISSUES = 8;
11const MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS = 16;
12const MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH = 64;
13const MAX_SCHEMA_DIAGNOSTIC_LENGTH = 2_048;
14​
15interface SchemaDiagnosticIssue {
16 readonly message: string;
17 readonly path: ReadonlyArray<PropertyKey>;
19​
20// Schema's default formatter includes actual values. These diagnostics cross
21// process and UI boundaries, so retain only issue kinds and bounded paths.
22​
23function truncateDiagnostic(value: string, maxLength: number): string {
24 return value.length <= maxLength ? value : `${value.slice(0, maxLength - 3)}...`;
26​
27function formatDiagnosticPathSegment(key: PropertyKey): string {
28 if (typeof key === "number") {
29 return `[${key}]`;
30 }
31 const value = truncateDiagnostic(
32 typeof key === "symbol" ? String(key) : key,
33 MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH,
34 );
35 return `[${JSON.stringify(value)}]`;
37​
38function formatDiagnosticIssue(issue: SchemaDiagnosticIssue): string {
39 if (issue.path.length === 0) {
40 return issue.message;
41 }
42 const path = issue.path
43 .slice(0, MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS)
44 .map(formatDiagnosticPathSegment)
45 .join("");
46 const suffix = issue.path.length > MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS ? "[...]" : "";
47 return `${issue.message}\n at ${path}${suffix}`;
49​
50function schemaDiagnosticMessage(issue: SchemaIssue.Issue): string {
51 switch (issue._tag) {
52 case "InvalidType":
53 return "Invalid type";
54 case "InvalidValue":
55 case "Filter":
56 case "AnyOf":
57 case "Encoding":
58 case "Pointer":
59 case "Composite":
60 return "Invalid value";
61 case "MissingKey":
62 return "Missing key";
63 case "UnexpectedKey":
64 return "Unexpected key";
65 case "Forbidden":
66 return "Forbidden operation";
67 case "OneOf":
68 return "Expected exactly one schema member to match";
69 }
71​
72function collectSchemaDiagnosticIssues(
73 issue: SchemaIssue.Issue,
74 path: ReadonlyArray<PropertyKey>,
75 diagnostics: Array<SchemaDiagnosticIssue>,
76): number {
77 switch (issue._tag) {
78 case "Encoding":
79 return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);
80 case "Filter":
81 if (issue.issue._tag !== "InvalidValue") {
82 return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);
83 }
84 break;
85 case "Pointer":
86 return collectSchemaDiagnosticIssues(issue.issue, [...path, ...issue.path], diagnostics);
87 case "Composite":
88 return issue.issues.reduce(
89 (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),
90 0,
91 );
92 case "AnyOf":
93 if (issue.issues.length > 0) {
94 return issue.issues.reduce(
95 (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),
96 0,
97 );
98 }
99 break;
100 }
101​
102 if (diagnostics.length < MAX_SCHEMA_DIAGNOSTIC_ISSUES) {
103 diagnostics.push({ message: schemaDiagnosticMessage(issue), path });
104 }
105 return 1;
107​
108export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
109 schema: S,
110) => {
111 const decode = Schema.decodeExit(Schema.fromJsonString(schema));
112 return (input: string) => {
113 const result = decode(input);
114 if (Exit.isFailure(result)) {
115 return Result.fail(result.cause);
116 }
117 return Result.succeed(result.value);
118 };
119};
120​
121export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
122 const issues: Array<SchemaDiagnosticIssue> = [];
123 let issueCount = 0;
124 let failureCount = 0;
125 let defectCount = 0;
126 let interruptionCount = 0;
127​
128 for (const reason of cause.reasons) {
129 switch (reason._tag) {
130 case "Fail":
131 failureCount += 1;
132 if (Schema.isSchemaError(reason.error)) {
133 issueCount += collectSchemaDiagnosticIssues(reason.error.issue, [], issues);
134 }
135 break;
136 case "Die":
137 defectCount += 1;
138 break;
139 case "Interrupt":
140 interruptionCount += 1;
141 break;
142 }
143 }
144​
145 if (issues.length === 0) {
146 return `Schema validation failed (failureCount=${failureCount}, defectCount=${defectCount}, interruptionCount=${interruptionCount}).`;
147 }
148​
149 const omittedIssueCount = issueCount - issues.length;
150 const formatted = issues.map(formatDiagnosticIssue).join("\n");
151 if (omittedIssueCount === 0) {
152 return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH);
153 }
154 const suffix = `\n... and ${omittedIssueCount} more issue(s)`;
155 return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH - suffix.length) + suffix;
156};
157​
158const decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
159​
160const parseLenientJsonGetter = SchemaGetter.transformEffect((input: string) => {
161 // Match comments together so URLs stay inside blocks; whitespace keeps adjacent tokens apart.
162 let stripped = input.replace(
163 /("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,
164 (match, stringLiteral: string | undefined) => (stringLiteral ? match : " "),
165 );
166​
167 stripped = stripped.replace(
168 /("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g,
169 (match, stringLiteral: string | undefined, bracket: string | undefined) =>
170 stringLiteral ? match : (bracket ?? ""),
171 );
172​
173 return decodeJsonString(stripped).pipe(Effect.mapError((error) => error.issue));
174});
175​
176const fromLenientJsonString = new SchemaTransformation.Transformation(
177 parseLenientJsonGetter,
178 SchemaGetter.stringifyJson(),
179);
180​
181const prettyJsonString = SchemaGetter.parseJson<string>().pipe(
182 SchemaGetter.compose(SchemaGetter.stringifyJson({ space: 2 })),
183);
184​
185export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
186 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
187​
188export function extractJsonObject(raw: string): string {
189 const trimmed = raw.trim();
190 if (trimmed.length === 0) {
191 return trimmed;
192 }
193​
194 const start = trimmed.indexOf("{");
195 if (start < 0) {
196 return trimmed;
197 }
198​
199 let depth = 0;
200 let inString = false;
201 let escaping = false;
202 for (let index = start; index < trimmed.length; index += 1) {
203 const char = trimmed[index];
204 if (inString) {
205 if (escaping) {
206 escaping = false;
207 } else if (char === "\\") {
208 escaping = true;
209 } else if (char === '"') {
210 inString = false;
211 }
212 continue;
213 }
214​
215 if (char === '"') {
216 inString = true;
217 continue;
218 }
219​
220 if (char === "{") {
221 depth += 1;
222 continue;
223 }
224​
225 if (char === "}") {
226 depth -= 1;
227 if (depth === 0) {
228 return trimmed.slice(start, index + 1);
229 }
230 }
231 }
232​
233 return trimmed.slice(start);
235​
236export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
237 Schema.fromJsonString(schema).pipe(
238 Schema.encode({
239 decode: prettyJsonString,
240 encode: prettyJsonString,
241 }),
242 );