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

schemaJson.ts

160 lines4.6 KB

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​
11export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
12 schema: S,
13) => {
14 const decode = Schema.decodeExit(Schema.fromJsonString(schema));
15 return (input: string) => {
16 const result = decode(input);
17 if (Exit.isFailure(result)) {
18 return Result.fail(result.cause);
19 }
20 return Result.succeed(result.value);
21 };
22};
23​
24export const decodeUnknownJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
25 schema: S,
26) => {
27 const decode = Schema.decodeUnknownExit(Schema.fromJsonString(schema));
28 return (input: unknown) => {
29 const result = decode(input);
30 if (Exit.isFailure(result)) {
31 return Result.fail(result.cause);
32 }
33 return Result.succeed(result.value);
34 };
35};
36​
37export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
38 const squashed = Cause.squash(cause);
39 return Schema.isSchemaError(squashed)
40 ? SchemaIssue.makeFormatterDefault()(squashed.issue)
41 : Cause.pretty(cause);
42};
43​
44/**
45 * A `Getter` that parses a lenient JSON string (tolerating trailing commas
46 * and JS-style comments) into an unknown value.
47 *
48 * Mirrors `SchemaGetter.parseJson()` but uses `parseLenientJson` instead
49 * of `JSON.parse`.
50 */
51const parseLenientJsonGetter = SchemaGetter.onSome((input: string) =>
52 Effect.try({
53 try: () => {
54 // Strip single-line comments — alternation preserves quoted strings.
55 let stripped = input.replace(
56 /("(?:[^"\\]|\\.)*")|\/\/[^\n]*/g,
57 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
58 );
59​
60 // Strip multi-line comments.
61 stripped = stripped.replace(
62 /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\//g,
63 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
64 );
65​
66 // Strip trailing commas before `}` or `]`.
67 stripped = stripped.replace(/,(\s*[}\]])/g, "$1");
68​
69 return Option.some(JSON.parse(stripped));
70 },
71 catch: (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: String(e) }),
72 }),
73);
74​
75/**
76 * Schema transformation: lenient JSONC string ↔ unknown.
77 *
78 * Same API as `SchemaTransformation.fromJsonString`, but the decode side
79 * strips trailing commas and JS-style comments before parsing.
80 * Encoding produces strict JSON via `JSON.stringify`.
81 */
82export const fromLenientJsonString = new SchemaTransformation.Transformation(
83 parseLenientJsonGetter,
84 SchemaGetter.stringifyJson(),
85);
86​
87export const prettyJsonString = SchemaGetter.parseJson<string>().compose(
88 SchemaGetter.stringifyJson({ space: 2 }),
89);
90​
91/**
92 * Build a schema that decodes a lenient JSON string into `A`.
93 *
94 * Drop-in replacement for `Schema.fromJsonString(schema)` that tolerates
95 * trailing commas and comments in the input.
96 */
97export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
98 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
99​
100export function extractJsonObject(raw: string): string {
101 const trimmed = raw.trim();
102 if (trimmed.length === 0) {
103 return trimmed;
104 }
105​
106 const start = trimmed.indexOf("{");
107 if (start < 0) {
108 return trimmed;
109 }
110​
111 let depth = 0;
112 let inString = false;
113 let escaping = false;
114 for (let index = start; index < trimmed.length; index += 1) {
115 const char = trimmed[index];
116 if (inString) {
117 if (escaping) {
118 escaping = false;
119 } else if (char === "\\") {
120 escaping = true;
121 } else if (char === '"') {
122 inString = false;
123 }
124 continue;
125 }
126​
127 if (char === '"') {
128 inString = true;
129 continue;
130 }
131​
132 if (char === "{") {
133 depth += 1;
134 continue;
135 }
136​
137 if (char === "}") {
138 depth -= 1;
139 if (depth === 0) {
140 return trimmed.slice(start, index + 1);
141 }
142 }
143 }
144​
145 return trimmed.slice(start);
147​
148/**
149 * Build a JSON string schema that encodes with stable 2-space formatting.
150 *
151 * Decode behavior matches `Schema.fromJsonString(schema)`. Encode behavior
152 * keeps the transformation schema-based while preserving human-readable JSON.
153 */
154export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
155 Schema.fromJsonString(schema).pipe(
156 Schema.encode({
157 decode: prettyJsonString,
158 encode: prettyJsonString,
159 }),
160 );