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

schemaJson.ts

110 lines3.0 KB

1import * as Effect from "effect/Effect";
2import * as Exit from "effect/Exit";
3import * as Result from "effect/Result";
4import * as Schema from "effect/Schema";
5import * as SchemaGetter from "effect/SchemaGetter";
6import * as SchemaTransformation from "effect/SchemaTransformation";
7​
8export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
9 schema: S,
10) => {
11 const decode = Schema.decodeExit(Schema.fromJsonString(schema));
12 return (input: string) => {
13 const result = decode(input);
14 if (Exit.isFailure(result)) {
15 return Result.fail(result.cause);
16 }
17 return Result.succeed(result.value);
18 };
19};
20​
21const decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
22​
23const parseLenientJsonGetter = SchemaGetter.transformEffect((input: string) => {
24 // Match comments together so URLs stay inside blocks; whitespace keeps adjacent tokens apart.
25 let stripped = input.replace(
26 /("(?:[^"\\]|\\.)*")|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,
27 (match, stringLiteral: string | undefined) => (stringLiteral ? match : " "),
28 );
29​
30 // A comma right after an opener trails nothing, so leave it for JSON.parse to reject.
31 stripped = stripped.replace(
32 /("(?:[^"\\]|\\.)*")|([[{]\s*,)|,(\s*[}\]])/g,
33 (
34 match,
35 stringLiteral: string | undefined,
36 leadingComma: string | undefined,
37 bracket: string | undefined,
38 ) => (stringLiteral || leadingComma ? match : (bracket ?? "")),
39 );
40​
41 return decodeJsonString(stripped).pipe(Effect.mapError((error) => error.issue));
42});
43​
44const fromLenientJsonString = new SchemaTransformation.Transformation(
45 parseLenientJsonGetter,
46 SchemaGetter.stringifyJson(),
47);
48​
49const prettyJsonString = SchemaGetter.parseJson<string>().pipe(
50 SchemaGetter.compose(SchemaGetter.stringifyJson({ space: 2 })),
51);
52​
53export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
54 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
55​
56export function extractJsonObject(raw: string): string {
57 const trimmed = raw.trim();
58 if (trimmed.length === 0) {
59 return trimmed;
60 }
61​
62 const start = trimmed.indexOf("{");
63 if (start < 0) {
64 return trimmed;
65 }
66​
67 let depth = 0;
68 let inString = false;
69 let escaping = false;
70 for (let index = start; index < trimmed.length; index += 1) {
71 const char = trimmed[index];
72 if (inString) {
73 if (escaping) {
74 escaping = false;
75 } else if (char === "\\") {
76 escaping = true;
77 } else if (char === '"') {
78 inString = false;
79 }
80 continue;
81 }
82​
83 if (char === '"') {
84 inString = true;
85 continue;
86 }
87​
88 if (char === "{") {
89 depth += 1;
90 continue;
91 }
92​
93 if (char === "}") {
94 depth -= 1;
95 if (depth === 0) {
96 return trimmed.slice(start, index + 1);
97 }
98 }
99 }
100​
101 return trimmed.slice(start);
103​
104export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
105 Schema.fromJsonString(schema).pipe(
106 Schema.encode({
107 decode: prettyJsonString,
108 encode: prettyJsonString,
109 }),
110 );