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
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 strips JSONC syntax before parsing.
49 */
50const decodeJsonString = Schema.decodeEffect(Schema.UnknownFromJsonString);
51
52const parseLenientJsonGetter = SchemaGetter.onSome((input: string) => {
53 // Strip single-line comments - alternation preserves quoted strings.
54 let stripped = input.replace(
55 /("(?:[^"\\]|\\.)*")|\/\/[^\n]*/g,
56 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
57 );
58
59 // Strip multi-line comments.
60 stripped = stripped.replace(
61 /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\//g,
62 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
63 );
64
65 // Strip trailing commas before `}` or `]`.
66 stripped = stripped.replace(/,(\s*[}\]])/g, "$1");
67
68 return decodeJsonString(stripped).pipe(
69 Effect.map(Option.some),
70 Effect.mapError(
71 (error) => new SchemaIssue.InvalidValue(Option.some(input), { message: String(error) }),
72 ),
73 );
74});
75
76/**
77 * Schema transformation: lenient JSONC string ↔ unknown.
78 *
79 * Same API as `SchemaTransformation.fromJsonString`, but the decode side
80 * strips trailing commas and JS-style comments before parsing.
81 * Encoding produces strict JSON via `JSON.stringify`.
82 */
83export const fromLenientJsonString = new SchemaTransformation.Transformation(
84 parseLenientJsonGetter,
85 SchemaGetter.stringifyJson(),
86);
87
88export const prettyJsonString = SchemaGetter.parseJson<string>().compose(
89 SchemaGetter.stringifyJson({ space: 2 }),
90);
91
92/**
93 * Build a schema that decodes a lenient JSON string into `A`.
94 *
95 * Drop-in replacement for `Schema.fromJsonString(schema)` that tolerates
96 * trailing commas and comments in the input.
97 */
98export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
99 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
100
101export function extractJsonObject(raw: string): string {
102 const trimmed = raw.trim();
103 if (trimmed.length === 0) {
104 return trimmed;
105 }
106
107 const start = trimmed.indexOf("{");
108 if (start < 0) {
109 return trimmed;
110 }
111
112 let depth = 0;
113 let inString = false;
114 let escaping = false;
115 for (let index = start; index < trimmed.length; index += 1) {
116 const char = trimmed[index];
117 if (inString) {
118 if (escaping) {
119 escaping = false;
120 } else if (char === "\\") {
121 escaping = true;
122 } else if (char === '"') {
123 inString = false;
124 }
125 continue;
126 }
127
128 if (char === '"') {
129 inString = true;
130 continue;
131 }
132
133 if (char === "{") {
134 depth += 1;
135 continue;
136 }
137
138 if (char === "}") {
139 depth -= 1;
140 if (depth === 0) {
141 return trimmed.slice(start, index + 1);
142 }
143 }
144 }
145
146 return trimmed.slice(start);
147}
148
149/**
150 * Build a JSON string schema that encodes with stable 2-space formatting.
151 *
152 * Decode behavior matches `Schema.fromJsonString(schema)`. Encode behavior
153 * keeps the transformation schema-based while preserving human-readable JSON.
154 */
155export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
156 Schema.fromJsonString(schema).pipe(
157 Schema.encode({
158 decode: prettyJsonString,
159 encode: prettyJsonString,
160 }),
161 );