1
import { Validator } from '@cfworker/json-schema';
2
import type { OutputUnit, Schema as InterpreterSchema, SchemaDraft } from '@cfworker/json-schema';
3
-import { Either, ParseResult, Schema } from 'effect';
3
+import { Schema } from 'effect';
4
5
export type JsonSchemaValidationIssue = {
6
readonly code: string;
232
const requiredNameFromError = (error: OutputUnit): string | undefined =>
233
error.error.match(/required property "([^"]+)"/)?.[1];
234
235
+const matchesPattern = (pattern: string, key: string): boolean => {
236
+ try {
237
+ return new RegExp(pattern, 'u').test(key);
238
+ } catch {
239
+ return false;
240
+ }
241
+};
242
+
243
const propertyIsDeclared = (parent: JsonObject | null, key: string): boolean => {
244
if (!parent) {
245
return false;
251
return false;
252
}
253
246
- return Object.keys(parent.patternProperties).some(pattern =>
247
- Either.getOrElse(
248
- Either.try(() => new RegExp(pattern, 'u').test(key)),
249
- () => false
250
- )
251
- );
254
+ return Object.keys(parent.patternProperties).some(pattern => matchesPattern(pattern, key));
255
};
256
257
const hasSpecificChildError = (errors: ReadonlyArray<OutputUnit>, error: OutputUnit): boolean =>
343
return `${location}: ${issue.message}`;
344
});
345
346
+// Validation is expressed as a filter over `Schema.Unknown` rather than a
347
+// `Schema.declare` codec: the interpreter already owns the whole decision, so
348
+// there is nothing to decode, and a filter reports every failure through the
349
+// `{ path, message }` shape Effect normalizes for us. `Schema.filter` is also
350
+// the API that survives the Effect 4 rewrite — where `ParseResult` is split
351
+// into `SchemaIssue`/`SchemaParser` and declarations lose their encode half —
352
+// as a rename to `Schema.check(Schema.makeFilter(...))`.
353
export const jsonSchemaToEffectSchema = (
354
jsonSchema: JsonObject,
355
options: JsonSchemaToEffectSchemaOptions = {}
346
-) => {
356
+): Schema.Schema<unknown> => {
357
const normalizedSchema = normalizeJsonSchema(jsonSchema);
358
const validator = new Validator(normalizedSchema, options.draft ?? '7', false);
359
const formatIssues = options.formatIssues ?? defaultFormatIssues;
360
351
- return Schema.declare([Schema.Unknown], {
352
- decode: () => (input, _parseOptions, ast) => {
353
- const validation = Either.try(() => validator.validate(input));
354
- if (Either.isLeft(validation)) {
355
- return ParseResult.fail(
356
- new ParseResult.Type(ast, input, `JSON Schema validation failed: ${validation.left}`)
357
- );
361
+ return Schema.Unknown.pipe(
362
+ Schema.filter(input => {
363
+ let validation: ReturnType<Validator['validate']>;
364
+ try {
365
+ validation = validator.validate(input);
366
+ } catch (error) {
367
+ return `JSON Schema validation failed: ${error}`;
368
}
359
- if (validation.right.valid) {
360
- return ParseResult.succeed(input);
369
+ if (validation.valid) {
370
+ return true;
371
}
372
363
- const issues = mapValidationErrors(validation.right.errors, normalizedSchema);
373
+ const issues = mapValidationErrors(validation.errors, normalizedSchema);
374
const messages = formatIssues(issues);
365
- const [first, ...rest] = messages.map(message => new ParseResult.Type(ast, input, message));
366
- return ParseResult.fail(
367
- first
368
- ? new ParseResult.Composite(ast, input, [first, ...rest])
369
- : new ParseResult.Type(ast, input, 'Input does not match the JSON schema.')
370
- );
371
- },
372
- encode: () => input => ParseResult.succeed(input),
373
- });
375
+ if (messages.length === 0) {
376
+ return 'Input does not match the JSON schema.';
377
+ }
378
+
379
+ // `formatIssues` may fan one issue out into several messages, so the
380
+ // location stays inside the message (as it always has) instead of being
381
+ // reported as a structural path.
382
+ return messages.map(message => ({ path: [], message }));
383
+ })
384
+ );
385
};