@devries-cameron20 / composio Mirror · read-only / commits / b7592585d
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 16:00 UTC

refactor(json-schema-to-effect-schema): validate through a filter instead of a declaration

`Schema.declare`, `ParseResult`, and `Either` are all removed or reshaped in Effect 4, so the converter compiled against three APIs that do not survive the next major. Express validation as a filter over `Schema.Unknown` instead: the filter returns the formatted messages and Effect builds the issue tree, which drops the hand-constructed `ParseResult.Composite`/`Type` values and the identity encode half that declarations no longer carry. `Either.try` has no `Result` counterpart in Effect 4 and both uses were local try/catch in disguise, so they become that. Reported messages are unchanged: the location stays inside the message, because `formatIssues` may fan one issue out into several. Tests move to `decodeUnknownOption`, which keeps its name across both majors. The CLI keeps `ParseResult.ArrayFormatter` while the repo is on Effect 3.x.

jkomyno committed Aug 6, 2026 at 21:25 UTC b7592585dde831710bd6e48a87dcbf35b7e62d6c
2 files changed +47 -36
ts/packages/json-schema-to-effect-schema/src/index.ts
+38 -27
@@ -1,6 +1,6 @@
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,6 +232,14 @@ const propertyNameFromError = (error: OutputUnit): string | undefined =>
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;
@@ -243,12 +251,7 @@ const propertyIsDeclared = (parent: JsonObject | null, key: string): boolean =>
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 =>
@@ -340,35 +343,43 @@ const defaultFormatIssues = (
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 };
ts/packages/json-schema-to-effect-schema/test/json-schema-to-effect-schema.test.ts
+9 -9
@@ -1,5 +1,5 @@
1 import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
2 -import { Either, Schema } from 'effect';
2 +import { Option, Schema } from 'effect';
3 import { describe, expect, it } from 'vitest';
4 import { jsonSchemaToEffectSchema, type JsonSchemaValidationIssue } from '../src/index';
5 import { acceptedFor, loadObjectCases } from './fixtures/corpus';
@@ -7,8 +7,8 @@ import { acceptedFor, loadObjectCases } from './fixtures/corpus';
7 type JsonSchema = Record<string, unknown>;
8
9 const effectAccepts = (schema: JsonSchema, input: unknown): boolean =>
10 - Either.isRight(
11 - Schema.decodeUnknownEither(jsonSchemaToEffectSchema(schema), { errors: 'all' })(input)
10 + Option.isSome(
11 + Schema.decodeUnknownOption(jsonSchemaToEffectSchema(schema), { errors: 'all' })(input)
12 );
13
14 const zodAccepts = (schema: JsonSchema, input: unknown): boolean =>
@@ -100,13 +100,13 @@ describe('jsonSchemaToEffectSchema', () => {
100 },
101 });
102
103 - const result = Schema.decodeUnknownEither(effectSchema, { errors: 'all' })({
103 + const result = Schema.decodeUnknownOption(effectSchema, { errors: 'all' })({
104 email: 42,
105 profile: { age: 'old', extra: true },
106 typo: true,
107 });
108
109 - expect(Either.isLeft(result)).toBe(true);
109 + expect(Option.isNone(result)).toBe(true);
110 expect(captured).toEqual(
111 expect.arrayContaining([
112 expect.objectContaining({ code: 'type', path: ['email'] }),
@@ -125,16 +125,16 @@ describe('shared cross-SDK object corpus', () => {
125 const expected = acceptedFor(instance, 'effect');
126
127 it(`instance ${index} is ${expected ? 'accepted' : 'rejected'}`, () => {
128 - const result = Schema.decodeUnknownEither(
128 + const result = Schema.decodeUnknownOption(
129 jsonSchemaToEffectSchema(testCase.schema as JsonSchema),
130 { errors: 'all' }
131 )(instance.input);
132
133 - expect(Either.isRight(result)).toBe(expected);
134 - if (Either.isRight(result) && instance.effect && 'output' in instance.effect) {
133 + expect(Option.isSome(result)).toBe(expected);
134 + if (Option.isSome(result) && instance.effect && 'output' in instance.effect) {
135 // Effect decoding is validation-only: a successful decode returns the
136 // input value unchanged, with no default materialization.
137 - expect(result.right).toEqual(instance.effect.output);
137 + expect(result.value).toEqual(instance.effect.output);
138 }
139 });
140 }