From ebb3f8d47e0e889a20f6d13ce7dc9adc00a24c1f Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Thu, 22 May 2025 17:02:16 +0200 Subject: [PATCH] add decode / encode APIs + renaming (#130) * add decode / encode APIs + renaming * fix bundle * all transformation as functions * rename SchemaParser to SchemaToParser * fix * remove useless transformations * fix bundles * enhance decodeTo / encodeTo to act as composition operators --- bundle/schema-string-async.ts | 14 +- bundle/schema-string-check.ts | 3 +- bundle/schema-string.ts | 3 +- bundle/schema.ts | 3 +- packages/effect/SCHEMA.md | 242 +++++++++--------- packages/effect/dtslint/Schema.tst.ts | 98 ++++++- packages/effect/src/Schema.ts | 132 +++++++--- packages/effect/src/SchemaAST.ts | 12 +- packages/effect/src/SchemaGetter.ts | 61 ++++- packages/effect/src/SchemaSerializer.ts | 2 +- .../{SchemaParser.ts => SchemaToParser.ts} | 38 +-- packages/effect/src/SchemaTransformation.ts | 119 ++++----- packages/effect/src/index.ts | 10 +- packages/effect/src/unstable/HttpBody.ts | 4 +- .../effect/src/unstable/HttpClientResponse.ts | 4 +- .../src/unstable/HttpIncomingMessage.ts | 4 +- packages/effect/test/Schema.test.ts | 147 +++++++++-- packages/effect/test/SchemaFormatter.test.ts | 6 +- packages/effect/test/SchemaTest.ts | 22 +- 19 files changed, 595 insertions(+), 329 deletions(-) rename packages/effect/src/{SchemaParser.ts => SchemaToParser.ts} (86%) diff --git a/bundle/schema-string-async.ts b/bundle/schema-string-async.ts index 5e2c4ebd6a..ccca6e3eb9 100644 --- a/bundle/schema-string-async.ts +++ b/bundle/schema-string-async.ts @@ -1,21 +1,19 @@ import * as Duration from "#dist/effect/Duration" import * as Effect from "#dist/effect/Effect" -import * as Option from "#dist/effect/Option" import * as Result from "#dist/effect/Result" import * as Schema from "#dist/effect/Schema" -import * as SchemaParser from "#dist/effect/SchemaParser" import * as SchemaTransformation from "#dist/effect/SchemaTransformation" const schema = Schema.String.pipe(Schema.decodeTo( Schema.String, - SchemaTransformation.transformOrFail( - (s) => + SchemaTransformation.transformOrFail({ + decode: (s) => Effect.gen(function*() { yield* Effect.clockWith((clock) => clock.sleep(Duration.millis(300))) - return Option.some(s) + return s }), - (s) => Result.succeedSome(s) - ) + encode: Result.ok + }) )) -SchemaParser.decodeUnknown(schema)("a").pipe(Effect.runPromise).then(console.log) +Schema.decodeUnknownEffect(schema)("a").pipe(Effect.runPromise).then(console.log) diff --git a/bundle/schema-string-check.ts b/bundle/schema-string-check.ts index 7fbadbea36..3e5d4f9dcc 100644 --- a/bundle/schema-string-check.ts +++ b/bundle/schema-string-check.ts @@ -1,7 +1,6 @@ import * as Schema from "#dist/effect/Schema" import * as SchemaCheck from "#dist/effect/SchemaCheck" -import * as SchemaParser from "#dist/effect/SchemaParser" const schema = Schema.String.pipe(Schema.check(SchemaCheck.nonEmpty)) -console.log(SchemaParser.decodeUnknownSync(schema)("a")) +console.log(Schema.decodeUnknownSync(schema)("a")) diff --git a/bundle/schema-string.ts b/bundle/schema-string.ts index ae25d4d699..fcdfc57c12 100644 --- a/bundle/schema-string.ts +++ b/bundle/schema-string.ts @@ -1,6 +1,5 @@ import * as Schema from "#dist/effect/Schema" -import * as SchemaParser from "#dist/effect/SchemaParser" const schema = Schema.String -console.log(SchemaParser.decodeUnknownSync(schema)("a")) +console.log(Schema.decodeUnknownSync(schema)("a")) diff --git a/bundle/schema.ts b/bundle/schema.ts index 9815979826..a1da515dbb 100644 --- a/bundle/schema.ts +++ b/bundle/schema.ts @@ -1,5 +1,4 @@ import * as Schema from "#dist/effect/Schema" -import * as SchemaParser from "#dist/effect/SchemaParser" const schema = Schema.Struct({ a: Schema.String, @@ -7,4 +6,4 @@ const schema = Schema.Struct({ c: Schema.ReadonlyArray(Schema.String) }) -console.log(SchemaParser.decodeUnknownSync(schema)({ a: "a", b: 1, c: ["c"] })) +console.log(Schema.decodeUnknownSync(schema)({ a: "a", b: 1, c: ["c"] })) diff --git a/packages/effect/SCHEMA.md b/packages/effect/SCHEMA.md index a0b95c3cda..0fd781b5f5 100644 --- a/packages/effect/SCHEMA.md +++ b/packages/effect/SCHEMA.md @@ -23,22 +23,13 @@ flowchart TD end ``` -## Current Pain Points - -These are known limitations and difficulties: - -- `partial` only allows toggling all fields at once, which limits flexibility. -- Suspended schemas are awkward to use. -- Performance and bundle size need improvement. -- (optional) Custom error handling is limited ([example](https://discord.com/channels/795981131316985866/1347665724361019433/1347831833282347079)). - ## Type Hierarchy ```mermaid flowchart TD T[Top] --> S["Schema[T]"] S --> C["Codec[T, E, RD, RE]"] - C --> B["Bottom[T,E, RD, RE, Ast, CloneOut, AnnotateIn, MakeIn, TypeReadonly, TypeIsOptional, TypeDefault, EncodedIsReadonly, EncodedIsOptional]"] + C --> B["Bottom[T, E, RD, RE, Ast, RebuildOut, AnnotateIn, TypeMakeIn, TypeReadonly, TypeIsOptional, TypeDefault, EncodedIsReadonly, EncodedIsOptional]"] ``` ## More Requirement Type Parameters @@ -73,11 +64,11 @@ const schema = Schema.Struct({ // ┌─── Effect.Effect<{ readonly a: string; }, Schema.CodecError, never> // ▼ -const dec = Schema.decodeUnknown(schema)({ a: "a" }) +const dec = Schema.decodeUnknownEffect(schema)({ a: "a" }) // ┌─── Effect.Effect<{ readonly a: string; }, Schema.CodecError, EncodingService> // ▼ -const enc = Schema.encodeUnknown(schema)({ a: "a" }) +const enc = Schema.encodeUnknownEffect(schema)({ a: "a" }) ``` ## Default JSON Serialization @@ -217,13 +208,13 @@ const User = Schema.Struct({ const data = { id: 1, name: Option.some("John") } const program = Effect.gen(function* () { - const json = yield* Schema.encode( + const json = yield* Schema.encodeEffect( SchemaSerializer.json(Schema.typeCodec(User)) )(data) console.log(json) - const t = yield* Schema.decode(SchemaSerializer.json(Schema.typeCodec(User)))( - json - ) + const t = yield* Schema.decodeEffect( + SchemaSerializer.json(Schema.typeCodec(User)) + )(json) console.log(t) }) @@ -242,7 +233,7 @@ import { Schema } from "effect" // Flips a schema that decodes a string into a number, // turning it into one that decodes a number into a string // -// const StringFromFinite: Schema.flip> +// const StringFromFinite: flip> const StringFromFinite = Schema.flip(Schema.FiniteFromString) // Schema.Codec @@ -256,7 +247,7 @@ import { Schema } from "effect" const StringFromFinite = Schema.flip(Schema.FiniteFromString) -// Schema.decodeTo +// decodeTo StringFromFinite.schema ``` @@ -265,7 +256,7 @@ Applying `flip` twice will return a schema with the same shape as the original o ```ts import { Schema } from "effect" -// const schema: Schema.decodeTo +// const schema: decodeTo const schema = Schema.flip(Schema.flip(Schema.FiniteFromString)) ``` @@ -496,7 +487,7 @@ const schema = Schema.Option(Schema.String).pipe( Schema.refine(Option.isSome, { title: "Some" }) ) -Schema.decodeUnknown(schema)(Option.none()) +Schema.decodeUnknownEffect(schema)(Option.none()) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -531,7 +522,7 @@ const schema = Schema.String.pipe( ) ) -Schema.decodeUnknown(schema)(" a") +Schema.decodeUnknownEffect(schema)(" a") .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -556,7 +547,7 @@ const schema = Schema.Struct({ length: Schema.Number }).pipe( Schema.check(SchemaCheck.minLength(3)) ) -Schema.decodeUnknown(schema)({ length: 2 }) +Schema.decodeUnknownEffect(schema)({ length: 2 }) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -581,7 +572,7 @@ const schema = Schema.String.pipe( Schema.check(SchemaCheck.minLength(3), SchemaCheck.trimmed) ) -Schema.decodeUnknown(schema)(" a", { errors: "all" }) +Schema.decodeUnknownEffect(schema)(" a", { errors: "all" }) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -611,7 +602,7 @@ const schema = Schema.String.pipe( ) ) -Schema.decodeUnknown(schema)(" a", { errors: "all" }) +Schema.decodeUnknownEffect(schema)(" a", { errors: "all" }) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -1089,7 +1080,7 @@ console.log(Schema.decodeUnknownSync(Product)({ quantity: "2" })) import { Schema, SchemaTransformation } from "effect" const SnakeToCamel = Schema.String.pipe( - Schema.decodeTo(Schema.String, SchemaTransformation.snakeToCamel) + Schema.decode(SchemaTransformation.snakeToCamel()) ) const schema = Schema.ReadonlyRecord(SnakeToCamel, Schema.Number) @@ -1106,7 +1097,7 @@ By default duplicate keys are merged with the last value. import { Schema, SchemaTransformation } from "effect" const SnakeToCamel = Schema.String.pipe( - Schema.decodeTo(Schema.String, SchemaTransformation.snakeToCamel) + Schema.decode(SchemaTransformation.snakeToCamel()) ) const schema = Schema.ReadonlyRecord(SnakeToCamel, Schema.Number) @@ -1123,7 +1114,7 @@ You can also customize how duplicate keys are merged. import { Schema, SchemaTransformation } from "effect" const SnakeToCamel = Schema.String.pipe( - Schema.decodeTo(Schema.String, SchemaTransformation.snakeToCamel) + Schema.decode(SchemaTransformation.snakeToCamel()) ) const schema = Schema.ReadonlyRecord(SnakeToCamel, Schema.Number, { @@ -1279,7 +1270,7 @@ class Person extends Schema.Opaque()( .annotate({ title: "Person" }) ) {} -Schema.decodeUnknown(Person)({ name: "" }) +Schema.decodeUnknownEffect(Person)({ name: "" }) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -1776,7 +1767,7 @@ const schema = Schema.Union( { mode: "oneOf" } ) -Schema.decodeUnknown(schema)({ a: "a", b: 1 }) +Schema.decodeUnknownEffect(schema)({ a: "a", b: 1 }) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -1796,119 +1787,141 @@ Transformations are now treated as first-class values, rather than being tied to For example, `trim` is no longer just a codec combinator. It is now a standalone transformation that can be used with any codec that supports it—in this case, any codec working with strings. -**Example** (Using a transformation with debug logging) +**Example** ```ts -import { Option, Schema, SchemaTransformation } from "effect" +import { Schema, SchemaTransformation } from "effect" -// Wrap the trim transformation with debug logging -const trim = SchemaTransformation.tap(SchemaTransformation.trim, { - onDecode: (o) => { - if (Option.isSome(o)) { - console.log(`about to trim "${o.value}"`) - } - } -}) - -// Decode a string, trim it, then parse it into a number -const schema = Schema.String.pipe(Schema.decodeTo(Schema.String, trim)) +const schema = Schema.String.pipe(Schema.decode(SchemaTransformation.trim())) console.log(Schema.decodeUnknownSync(schema)(" 123")) -/* -about to trim " 123" -123 -*/ +// 123 ``` -### Composition +### Transformation Composition -#### compose +Transformation composition is the process of combining multiple transformations into a single transformation. -The `compose` transformation lets you convert from one schema to another when the encoded output of the target schema matches the type of the source schema. +```ts +import { SchemaTransformation } from "effect" + +/* +decoding: trim + toLowerCase +encoding: passthrough +*/ +const trimToLowerCase = SchemaTransformation.trim().compose( + SchemaTransformation.toLowerCase() +) +``` + +### Schema Composition + +#### decodeTo / encodeTo + +The `Schema.decodeTo` API allows you to compose two schemas without requiring the types to match. It skips type checking during the transformation and focuses on structure alone. + +```ts +import { Schema } from "effect" + +const From = Schema.Struct({ + a: Schema.String, + b: Schema.FiniteFromString +}) + +const To = Schema.Struct({ + a: Schema.FiniteFromString, + b: Schema.UndefinedOr(Schema.Number) +}) + +const schema = From.pipe(Schema.decodeTo(To)) +``` + +This approach is useful when you want to connect schemas without enforcing type compatibility between them. + +If you want more control over how the types align, such as ensuring one is a subtype or supertype of the other, you can use the `SchemaTransformation.passthrough*` helpers. + +The `Schema.encodeTo` API is the same as `Schema.decodeTo` but it applies the composition in the other direction. + +```ts +import { Schema } from "effect" + +const From = Schema.Struct({ + a: Schema.String, + b: Schema.FiniteFromString +}) + +const To = Schema.Struct({ + a: Schema.FiniteFromString, + b: Schema.UndefinedOr(Schema.Number) +}) + +const schema = To.pipe(Schema.encodeTo(From)) // same as From.pipe(Schema.decodeTo(To)) +``` + +#### passthrough + +The `passthrough` transformation lets you convert from one schema to another when the encoded output of the target schema matches the type of the source schema. **Example** (Composing schemas where `To.Encoded = From.Type`) ```ts -import { Schema, SchemaGetter, SchemaTransformation } from "effect" - -const FiniteFromString = Schema.String.pipe( - Schema.decodeTo(Schema.Finite, { - decode: SchemaGetter.Number, - encode: SchemaGetter.String - }) -) +import { Schema, SchemaTransformation } from "effect" const From = Schema.Struct({ - a: Schema.String, - b: Schema.String + a: Schema.String }) const To = Schema.Struct({ - a: FiniteFromString, - b: FiniteFromString + a: Schema.FiniteFromString }) // To.Encoded (string) = From.Type (string) const schema = From.pipe( - Schema.decodeTo(To, SchemaTransformation.compose({ strict: false })) + Schema.decodeTo(To, SchemaTransformation.passthrough()) ) ``` -#### composeSupertype +#### passthroughSubtype -Use `composeSupertype` when your source type extends the encoded output of your target schema. +Use `passthroughSubtype` when your source type extends the encoded output of your target schema. **Example** (Composing schemas where `From.Type extends To.Encoded`) ```ts -import { Schema, SchemaGetter, SchemaTransformation } from "effect" +import { Schema, SchemaTransformation } from "effect" -const FiniteFromString = Schema.String.pipe( - Schema.decodeTo(Schema.Finite, { - decode: SchemaGetter.Number, - encode: SchemaGetter.String - }) -) - -const From = FiniteFromString +const From = Schema.FiniteFromString const To = Schema.UndefinedOr(Schema.Number) // From.Type (number) extends To.Encoded (number | undefined) const schema = From.pipe( - Schema.decodeTo(To, SchemaTransformation.composeSupertype()) + Schema.decodeTo(To, SchemaTransformation.passthroughSubtype()) ) ``` -#### composeSubtype +#### passthroughSupertype -Use `composeSubtype` when the encoded output of your target schema extends the type of your source schema. +Use `passthroughSupertype` when the encoded output of your target schema extends the type of your source schema. **Example** (Composing schemas where `From.Encoded extends To.Type`) ```ts -import { Schema, SchemaGetter, SchemaTransformation } from "effect" - -const FiniteFromString = Schema.String.pipe( - Schema.decodeTo(Schema.Finite, { - decode: SchemaGetter.Number, - encode: SchemaGetter.String - }) -) +import { Schema, SchemaTransformation } from "effect" const From = Schema.UndefinedOr(Schema.String) -const To = FiniteFromString +const To = Schema.FiniteFromString // To.Encoded (string) extends From.Type (string | undefined) const schema = From.pipe( - Schema.decodeTo(To, SchemaTransformation.composeSubtype()) + Schema.decodeTo(To, SchemaTransformation.passthroughSupertype()) ) ``` #### Turning off strict mode -To turn off strict mode, pass `{ strict: false }` to `compose` +To turn off strict mode, pass `{ strict: false }` to `passthrough` ```ts import { Schema, SchemaTransformation } from "effect" @@ -1918,7 +1931,7 @@ const From = Schema.String const To = Schema.Number const schema = From.pipe( - Schema.decodeTo(To, SchemaTransformation.compose({ strict: false })) + Schema.decodeTo(To, SchemaTransformation.passthrough({ strict: false })) ) ``` @@ -1966,7 +1979,7 @@ import { Effect, Option, Result, Schema, SchemaFormatter } from "effect" const fallback = Result.ok(Option.some("b")) const schema = Schema.String.pipe(Schema.catchDecoding(() => fallback)) -Schema.decodeUnknown(schema)(null) +Schema.decodeUnknownEffect(schema)(null) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -2009,7 +2022,7 @@ const provided = schema.pipe( ) ) -Schema.decodeUnknown(provided)(null) +Schema.decodeUnknownEffect(provided)(null) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -2033,7 +2046,7 @@ const schema = Schema.Struct({ b: Schema.Number }) -Schema.decodeUnknown(schema)({ a: "", b: null }, { errors: "all" }) +Schema.decodeUnknownEffect(schema)({ a: "", b: null }, { errors: "all" }) .pipe( Effect.mapError((err) => SchemaFormatter.TreeFormatter.format(err.issue)), Effect.runPromise @@ -2061,7 +2074,7 @@ const schema = Schema.Struct({ b: Schema.Number }) -Schema.decodeUnknown(schema)({ a: "", b: null }, { errors: "all" }) +Schema.decodeUnknownEffect(schema)({ a: "", b: null }, { errors: "all" }) .pipe( Effect.mapError((err) => SchemaFormatter.StructuredFormatter.format(err.issue) @@ -2103,7 +2116,9 @@ Output: */ ``` -## Primitives +## Usage + +### Primitives ```ts import { Schema } from "effect" @@ -2121,23 +2136,26 @@ Schema.Null To coerce input data to the appropriate type: ```ts -import { Schema, SchemaParser, SchemaTransformation } from "effect" +import { Schema, SchemaGetter, SchemaToParser } from "effect" // ┌─── Codec // ▼ const schema = Schema.Unknown.pipe( - Schema.decodeTo(Schema.String, SchemaTransformation.String) + Schema.decodeTo(Schema.String, { + decode: SchemaGetter.String(), + encode: SchemaGetter.passthrough() + }) ) -const parse = SchemaParser.decodeUnknownSync(schema) +const parser = SchemaToParser.decodeUnknownSync(schema) -console.log(parse("tuna")) // => "tuna" -console.log(parse(42)) // => "42" -console.log(parse(true)) // => "true" -console.log(parse(null)) // => "null" +console.log(parser("tuna")) // => "tuna" +console.log(parser(42)) // => "42" +console.log(parser(true)) // => "true" +console.log(parser(null)) // => "null" ``` -## Literals +### Literals Literal types: @@ -2186,7 +2204,7 @@ const schema = Schema.Literals(["red", "green", "blue"]) schema.literals ``` -## Strings +### Strings ```ts import { Schema, SchemaCheck } from "effect" @@ -2207,16 +2225,12 @@ To perform some simple string transforms: ```ts import { Schema, SchemaTransformation } from "effect" -Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.trim)) -Schema.String.pipe( - Schema.decodeTo(Schema.String, SchemaTransformation.toLowerCase) -) -Schema.String.pipe( - Schema.decodeTo(Schema.String, SchemaTransformation.toUpperCase) -) +Schema.String.pipe(Schema.decode(SchemaTransformation.trim())) +Schema.String.pipe(Schema.decode(SchemaTransformation.toLowerCase())) +Schema.String.pipe(Schema.decode(SchemaTransformation.toUpperCase())) ``` -## String formats +### String formats ```ts import { Schema, SchemaCheck } from "effect" @@ -2226,7 +2240,7 @@ Schema.String.pipe(Schema.check(SchemaCheck.base64)) Schema.String.pipe(Schema.check(SchemaCheck.base64url)) ``` -## Numbers +### Numbers ```ts import { Schema } from "effect" @@ -2252,7 +2266,7 @@ Schema.Number.pipe(Schema.check(SchemaCheck.nonPositive)) Schema.Number.pipe(Schema.check(SchemaCheck.multipleOf(5))) ``` -## Integers +### Integers ```ts import { Schema, SchemaCheck } from "effect" @@ -2261,7 +2275,7 @@ Schema.Number.pipe(Schema.check(SchemaCheck.int)) Schema.Number.pipe(Schema.check(SchemaCheck.int32)) ``` -## BigInts +### BigInts ```ts import { BigInt, Order, Schema, SchemaCheck } from "effect" @@ -2295,7 +2309,7 @@ Schema.BigInt.pipe(Schema.check(negative)) Schema.BigInt.pipe(Schema.check(nonPositive)) ``` -## Dates +### Dates ```ts import { Schema, SchemaGetter } from "effect" diff --git a/packages/effect/dtslint/Schema.tst.ts b/packages/effect/dtslint/Schema.tst.ts index 44cbfea4a2..aeb304b169 100644 --- a/packages/effect/dtslint/Schema.tst.ts +++ b/packages/effect/dtslint/Schema.tst.ts @@ -9,8 +9,8 @@ const revealClass = , Inheri const FiniteFromString = Schema.String.pipe(Schema.decodeTo( Schema.Finite, new SchemaTransformation.SchemaTransformation( - SchemaGetter.Number, - SchemaGetter.String + SchemaGetter.Number(), + SchemaGetter.String() ) )) @@ -18,8 +18,8 @@ const NumberFromString = Schema.String.pipe( Schema.decodeTo( Schema.Number, new SchemaTransformation.SchemaTransformation( - SchemaGetter.Number, - SchemaGetter.String + SchemaGetter.Number(), + SchemaGetter.String() ) ) ) @@ -634,12 +634,12 @@ describe("Schema", () => { }) }) - describe("compose", () => { + describe("passthrough", () => { it("E = T", () => { Schema.String.pipe( Schema.decodeTo( Schema.String.pipe(Schema.check(SchemaCheck.nonEmpty)), - SchemaTransformation.compose() + SchemaTransformation.passthrough() ) ) }) @@ -648,14 +648,14 @@ describe("Schema", () => { when(Schema.String.pipe).isCalledWith( expect(Schema.decodeTo).type.not.toBeCallableWith( Schema.Number, - SchemaTransformation.compose() + SchemaTransformation.passthrough() ) ) Schema.String.pipe( Schema.decodeTo( Schema.Number, - SchemaTransformation.compose({ strict: false }) + SchemaTransformation.passthrough({ strict: false }) ) ) }) @@ -664,7 +664,7 @@ describe("Schema", () => { Schema.String.pipe( Schema.decodeTo( Schema.UndefinedOr(Schema.String), - SchemaTransformation.composeSupertype() + SchemaTransformation.passthroughSubtype() ) ) }) @@ -673,7 +673,7 @@ describe("Schema", () => { Schema.UndefinedOr(Schema.String).pipe( Schema.decodeTo( Schema.String, - SchemaTransformation.composeSubtype() + SchemaTransformation.passthroughSupertype() ) ) }) @@ -966,4 +966,82 @@ describe("Schema", () => { >() }) }) + + it("decodeTo as composition", () => { + const From = Schema.Struct({ + a: Schema.String, + b: Schema.FiniteFromString + }) + + const To = Schema.Struct({ + a: Schema.FiniteFromString, + b: Schema.UndefinedOr(Schema.Number) + }) + + const schema = From.pipe(Schema.decodeTo(To)) + + expect(Schema.revealCodec(schema)).type.toBe< + Schema.Codec< + { readonly a: number; readonly b: number | undefined }, + { readonly a: string; readonly b: string }, + never, + never + > + >() + expect(schema).type.toBe< + Schema.compose< + Schema.Struct< + { readonly a: Schema.FiniteFromString; readonly b: Schema.Union } + >, + Schema.Struct<{ readonly a: Schema.String; readonly b: Schema.FiniteFromString }> + > + >() + expect(schema.annotate({})).type.toBe< + Schema.compose< + Schema.Struct< + { readonly a: Schema.FiniteFromString; readonly b: Schema.Union } + >, + Schema.Struct<{ readonly a: Schema.String; readonly b: Schema.FiniteFromString }> + > + >() + }) + + it("encodeTo as composition", () => { + const From = Schema.Struct({ + a: Schema.String, + b: Schema.FiniteFromString + }) + + const To = Schema.Struct({ + a: Schema.FiniteFromString, + b: Schema.UndefinedOr(Schema.Number) + }) + + const schema = To.pipe(Schema.encodeTo(From)) + + expect(Schema.revealCodec(schema)).type.toBe< + Schema.Codec< + { readonly a: number; readonly b: number | undefined }, + { readonly a: string; readonly b: string }, + never, + never + > + >() + expect(schema).type.toBe< + Schema.compose< + Schema.Struct< + { readonly a: Schema.FiniteFromString; readonly b: Schema.Union } + >, + Schema.Struct<{ readonly a: Schema.String; readonly b: Schema.FiniteFromString }> + > + >() + expect(schema.annotate({})).type.toBe< + Schema.compose< + Schema.Struct< + { readonly a: Schema.FiniteFromString; readonly b: Schema.Union } + >, + Schema.Struct<{ readonly a: Schema.String; readonly b: Schema.FiniteFromString }> + > + >() + }) }) diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 2ebfdb45d5..30d0c3a720 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -21,8 +21,8 @@ import * as SchemaAST from "./SchemaAST.js" import * as SchemaCheck from "./SchemaCheck.js" import * as SchemaGetter from "./SchemaGetter.js" import * as SchemaIssue from "./SchemaIssue.js" -import * as SchemaParser from "./SchemaParser.js" import * as SchemaResult from "./SchemaResult.js" +import * as SchemaToParser from "./SchemaToParser.js" import * as SchemaTransformation from "./SchemaTransformation.js" import * as Struct_ from "./Struct.js" @@ -177,7 +177,7 @@ export abstract class Bottom$< } makeSync(input: this["~type.make.in"], options?: MakeOptions): this["Type"] { return Result.getOrThrowWith( - SchemaParser.runSyncSchemaResult(SchemaParser.make(this)(input, options)), + SchemaToParser.runSyncSchemaResult(SchemaToParser.makeSchemaResult(this)(input, options)), (issue) => new globalThis.Error("makeSync failure", { cause: issue @@ -268,10 +268,10 @@ export class SchemaError extends Data.TaggedError("SchemaError")<{ * @category Decoding * @since 4.0.0 */ -export function decodeUnknown(codec: Codec) { - const parser = SchemaParser.decodeUnknown(codec) - return (u: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => { - return Effect.mapError(parser(u, options), (issue) => new SchemaError({ issue })) +export function decodeUnknownEffect(codec: Codec) { + const parser = SchemaToParser.decodeUnknownEffect(codec) + return (input: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => { + return Effect.mapError(parser(input, options), (issue) => new SchemaError({ issue })) } } @@ -279,10 +279,10 @@ export function decodeUnknown(codec: Codec) { * @category Decoding * @since 4.0.0 */ -export function decode(codec: Codec) { - const parser = SchemaParser.decode(codec) - return (e: E, options?: SchemaAST.ParseOptions): Effect.Effect => { - return Effect.mapError(parser(e, options), (issue) => new SchemaError({ issue })) +export function decodeEffect(codec: Codec) { + const parser = SchemaToParser.decodeEffect(codec) + return (input: E, options?: SchemaAST.ParseOptions): Effect.Effect => { + return Effect.mapError(parser(input, options), (issue) => new SchemaError({ issue })) } } @@ -290,16 +290,16 @@ export function decode(codec: Codec) { * @category Decoding * @since 4.0.0 */ -export const decodeUnknownSync = SchemaParser.decodeUnknownSync +export const decodeUnknownSync = SchemaToParser.decodeUnknownSync /** * @category Encoding * @since 4.0.0 */ -export function encodeUnknown(codec: Codec) { - const parser = SchemaParser.encodeUnknown(codec) - return (u: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => { - return Effect.mapError(parser(u, options), (issue) => new SchemaError({ issue })) +export function encodeUnknownEffect(codec: Codec) { + const parser = SchemaToParser.encodeUnknownEffect(codec) + return (input: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => { + return Effect.mapError(parser(input, options), (issue) => new SchemaError({ issue })) } } @@ -307,10 +307,10 @@ export function encodeUnknown(codec: Codec) { * @category Encoding * @since 4.0.0 */ -export function encode(codec: Codec) { - const parser = SchemaParser.encode(codec) - return (t: T, options?: SchemaAST.ParseOptions): Effect.Effect => { - return Effect.mapError(parser(t, options), (issue) => new SchemaError({ issue })) +export function encodeEffect(codec: Codec) { + const parser = SchemaToParser.encodeEffect(codec) + return (input: T, options?: SchemaAST.ParseOptions): Effect.Effect => { + return Effect.mapError(parser(input, options), (issue) => new SchemaError({ issue })) } } @@ -318,13 +318,13 @@ export function encode(codec: Codec) { * @category Encoding * @since 4.0.0 */ -export const encodeUnknownSync = SchemaParser.encodeUnknownSync +export const encodeUnknownSync = SchemaToParser.encodeUnknownSync /** * @category Encoding * @since 4.0.0 */ -export const encodeSync = SchemaParser.encodeSync +export const encodeSync = SchemaToParser.encodeSync /** * @category Api interface @@ -1872,6 +1872,12 @@ export interface decodeTo extends readonly to: To } +/** + * @category Api interface + * @since 4.0.0 + */ +export interface compose extends decodeTo {} + class decodeTo$ extends make$> implements decodeTo { @@ -1887,16 +1893,40 @@ class decodeTo$ extends make$(to: To): (from: From) => compose export function decodeTo( to: To, transformation: { readonly decode: SchemaGetter.SchemaGetter readonly encode: SchemaGetter.SchemaGetter } +): (from: From) => decodeTo +/** + * Used by {@link encodeTo} + * + * @internal + */ +export function decodeTo( + to: To, + transformation?: { + readonly decode: SchemaGetter.SchemaGetter + readonly encode: SchemaGetter.SchemaGetter + } | undefined +): (from: From) => decodeTo +export function decodeTo( + to: To, + transformation?: { + readonly decode: SchemaGetter.SchemaGetter + readonly encode: SchemaGetter.SchemaGetter + } | undefined ) { - return (from: From): decodeTo => { + return (from: From) => { return new decodeTo$( - SchemaAST.decodeTo(from.ast, to.ast, SchemaTransformation.make(transformation)), + SchemaAST.decodeTo( + from.ast, + to.ast, + transformation ? SchemaTransformation.make(transformation) : SchemaTransformation.passthrough() + ), from, to ) @@ -1904,17 +1934,61 @@ export function decodeTo(transformation: { + readonly decode: SchemaGetter.SchemaGetter + readonly encode: SchemaGetter.SchemaGetter +}) { + return (self: S): decodeTo, S, RD, RE> => { + return self.pipe( + decodeTo, S, RD, RE>(typeCodec(self), SchemaTransformation.make(transformation)) + ) + } +} + +/** + * @since 4.0.0 + */ +export function encodeTo( + to: To +): (from: From) => decodeTo export function encodeTo( to: To, transformation: { readonly decode: SchemaGetter.SchemaGetter readonly encode: SchemaGetter.SchemaGetter } -) { +): (from: From) => decodeTo +export function encodeTo( + to: To, + transformation?: { + readonly decode: SchemaGetter.SchemaGetter + readonly encode: SchemaGetter.SchemaGetter + } +): (from: From) => decodeTo { return (from: From): decodeTo => { - return to.pipe(decodeTo(from, SchemaTransformation.make(transformation))) + return to.pipe(decodeTo(from, transformation)) + } +} + +/** + * Like {@link encodeTo}, but the transformation is applied to the encoded codec + * (`encodedCodec(self)`). + * + * @since 4.0.0 + */ +export function encode(transformation: { + readonly decode: SchemaGetter.SchemaGetter + readonly encode: SchemaGetter.SchemaGetter +}) { + return (self: S): decodeTo, RD, RE> => { + return encodedCodec(self).pipe( + decodeTo, RD, RE>(self, SchemaTransformation.make(transformation)) + ) } } @@ -1991,7 +2065,7 @@ export function Option(value: S) { return Result.okNone } const input = oinput.value - return SchemaParser.decodeUnknownSchemaResult(value)(input, options).pipe(SchemaResult.mapBoth( + return SchemaToParser.decodeUnknownSchemaResult(value)(input, options).pipe(SchemaResult.mapBoth( { onSuccess: O.some, onFailure: (issue) => { @@ -2044,7 +2118,7 @@ export function Map(key: Key, value: Value) ([key, value]) => (input, ast, options) => { if (input instanceof globalThis.Map) { const array = ReadonlyArray(ReadonlyTuple([key, value])) - return SchemaParser.decodeUnknownSchemaResult(array)([...input], options).pipe(SchemaResult.mapBoth( + return SchemaToParser.decodeUnknownSchemaResult(array)([...input], options).pipe(SchemaResult.mapBoth( { onSuccess: (array: ReadonlyArray) => new globalThis.Map(array), onFailure: (issue) => new SchemaIssue.Composite(ast, O.some(input), [issue]) @@ -2226,8 +2300,8 @@ export interface FiniteFromString extends decodeTo export const FiniteFromString: FiniteFromString = String.pipe(decodeTo( Finite, { - decode: SchemaGetter.Number, - encode: SchemaGetter.String + decode: SchemaGetter.Number(), + encode: SchemaGetter.String() } )) diff --git a/packages/effect/src/SchemaAST.ts b/packages/effect/src/SchemaAST.ts index 294de503b0..f556ea35c0 100644 --- a/packages/effect/src/SchemaAST.ts +++ b/packages/effect/src/SchemaAST.ts @@ -12,8 +12,8 @@ import * as Result from "./Result.js" import type { Annotated, Annotations } from "./SchemaAnnotations.js" import type * as SchemaCheck from "./SchemaCheck.js" import * as SchemaIssue from "./SchemaIssue.js" -import type * as SchemaParser from "./SchemaParser.js" import type * as SchemaResult from "./SchemaResult.js" +import type * as SchemaToParser from "./SchemaToParser.js" import type * as SchemaTransformation from "./SchemaTransformation.js" /** @@ -610,7 +610,7 @@ export class TupleType extends Extensions { new TupleType(this.isReadonly, elements, rest, this.annotations, this.checks, undefined, this.context) } /** @internal */ - parser(go: (ast: AST) => SchemaParser.Parser) { + parser(go: (ast: AST) => SchemaToParser.Parser) { // eslint-disable-next-line @typescript-eslint/no-this-alias const ast = this return Effect.fnUntraced(function*(oinput, options) { @@ -762,7 +762,7 @@ export class TypeLiteral extends Extensions { ) } /** @internal */ - parser(go: (ast: AST) => SchemaParser.Parser) { + parser(go: (ast: AST) => SchemaToParser.Parser) { // eslint-disable-next-line @typescript-eslint/no-this-alias const ast = this // Handle empty Struct({}) case @@ -983,7 +983,7 @@ export class UnionType extends Extensions { new UnionType(types, this.mode, this.annotations, this.checks, undefined, this.context) } /** @internal */ - parser(go: (ast: AST) => SchemaParser.Parser) { + parser(go: (ast: AST) => SchemaToParser.Parser) { // eslint-disable-next-line @typescript-eslint/no-this-alias const ast = this return Effect.fnUntraced(function*(oinput, options) { @@ -1056,7 +1056,7 @@ export class Suspend extends Extensions { return new Suspend(() => flip(this.thunk()), this.annotations, this.checks, undefined, this.context) } /** @internal */ - parser(go: (ast: AST) => SchemaParser.Parser) { + parser(go: (ast: AST) => SchemaToParser.Parser) { return go(this.thunk()) } } @@ -1678,7 +1678,7 @@ const handleTemplateLiteralSpanTypeParens = ( /** @internal */ export const fromPredicate = - (ast: AST, predicate: (input: unknown) => boolean): SchemaParser.Parser => (oinput) => { + (ast: AST, predicate: (input: unknown) => boolean): SchemaToParser.Parser => (oinput) => { if (Option.isNone(oinput)) { return Effect.succeedNone } diff --git a/packages/effect/src/SchemaGetter.ts b/packages/effect/src/SchemaGetter.ts index 7fc9834d11..0e4bcde690 100644 --- a/packages/effect/src/SchemaGetter.ts +++ b/packages/effect/src/SchemaGetter.ts @@ -25,6 +25,17 @@ export class SchemaGetter extends PipeableClass { ) { super() } + compose(other: SchemaGetter): SchemaGetter { + if (isPassthrough(this)) { + return other as any + } + if (isPassthrough(other)) { + return this as any + } + return new SchemaGetter((oe, ast, options) => + this.run(oe, ast, options).pipe(SchemaResult.flatMap((ot) => other.run(ot, ast, options))) + ) + } } /** @@ -33,8 +44,14 @@ export class SchemaGetter extends PipeableClass { * @category constructors * @since 4.0.0 */ -export function fail(f: (ot: Option.Option) => SchemaIssue.Issue): SchemaGetter { - return new SchemaGetter((ot) => SchemaResult.fail(f(ot))) +export function fail(f: (oe: Option.Option) => SchemaIssue.Issue): SchemaGetter { + return new SchemaGetter((oe) => SchemaResult.fail(f(oe))) +} + +const passthrough_ = new SchemaGetter(SchemaResult.succeed) + +function isPassthrough(getter: SchemaGetter): getter is typeof passthrough_ { + return getter.run === passthrough_.run } /** @@ -43,8 +60,26 @@ export function fail(f: (ot: Option.Option) => SchemaIssue.Issue): SchemaG * @category constructors * @since 4.0.0 */ +export function passthrough(options: { readonly strict: false }): SchemaGetter +export function passthrough(): SchemaGetter export function passthrough(): SchemaGetter { - return new SchemaGetter(SchemaResult.succeed) + return passthrough_ +} + +/** + * @since 4.0.0 + */ +export function passthroughSupertype(): SchemaGetter +export function passthroughSupertype(): SchemaGetter { + return passthrough_ +} + +/** + * @since 4.0.0 + */ +export function passthroughSubtype(): SchemaGetter +export function passthroughSubtype(): SchemaGetter { + return passthrough_ } /** @@ -156,31 +191,41 @@ export function withDefault(defaultValue: () => T): SchemaGetter = transform(globalThis.String) +export function String(): SchemaGetter { + return transform(globalThis.String) +} /** * @category Coercions * @since 4.0.0 */ -export const Number: SchemaGetter = transform(globalThis.Number) +export function Number(): SchemaGetter { + return transform(globalThis.Number) +} /** * @category Coercions * @since 4.0.0 */ -export const Boolean: SchemaGetter = transform(globalThis.Boolean) +export function Boolean(): SchemaGetter { + return transform(globalThis.Boolean) +} /** * @category Coercions * @since 4.0.0 */ -export const BigInt: SchemaGetter = transform(globalThis.BigInt) +export function BigInt(): SchemaGetter { + return transform(globalThis.BigInt) +} /** * @category Coercions * @since 4.0.0 */ -export const Date: SchemaGetter = transform((u) => new globalThis.Date(u)) +export function Date(): SchemaGetter { + return transform((u) => new globalThis.Date(u)) +} /** * @category String transformations diff --git a/packages/effect/src/SchemaSerializer.ts b/packages/effect/src/SchemaSerializer.ts index 87c3e14191..a073126a5c 100644 --- a/packages/effect/src/SchemaSerializer.ts +++ b/packages/effect/src/SchemaSerializer.ts @@ -141,6 +141,6 @@ const bigIntLink = new SchemaAST.Link( SchemaAST.stringKeyword, new SchemaTransformation.SchemaTransformation( SchemaGetter.transform(BigInt), - SchemaGetter.String + SchemaGetter.String() ) ) diff --git a/packages/effect/src/SchemaParser.ts b/packages/effect/src/SchemaToParser.ts similarity index 86% rename from packages/effect/src/SchemaParser.ts rename to packages/effect/src/SchemaToParser.ts index 8966a99012..067af80621 100644 --- a/packages/effect/src/SchemaParser.ts +++ b/packages/effect/src/SchemaToParser.ts @@ -18,13 +18,13 @@ import * as SchemaResult from "./SchemaResult.js" * @category Make * @since 4.0.0 */ -export const make = (schema: S) => +export const makeSchemaResult = (schema: S) => ( input: S["~type.make.in"], options?: Schema.MakeOptions ): SchemaResult.SchemaResult => { const parseOptions: SchemaAST.ParseOptions = { "~variant": "make", ...options?.parseOptions } - return validateUnknownParserResult(schema)(input, parseOptions) + return fromASTSchemaResult(SchemaAST.typeAST(schema.ast))(input, parseOptions) } /** @@ -38,7 +38,7 @@ export const decodeUnknownSchemaResult = (codec: Schema.Codec(codec: Schema.Codec) => { +export const decodeUnknownEffect = (codec: Schema.Codec) => { const parser = decodeUnknownSchemaResult(codec) return (u: unknown, options?: SchemaAST.ParseOptions) => { return SchemaResult.asEffect(parser(u, options)) @@ -49,9 +49,9 @@ export const decodeUnknown = (codec: Schema.Codec) = * @category Decoding * @since 4.0.0 */ -export const decode: ( +export const decodeEffect: ( codec: Schema.Codec -) => (e: E, options?: SchemaAST.ParseOptions) => Effect.Effect = decodeUnknown +) => (e: E, options?: SchemaAST.ParseOptions) => Effect.Effect = decodeUnknownEffect /** * @category Decoding @@ -70,7 +70,7 @@ export const encodeUnknownSchemaResult = (codec: Schema.Codec(codec: Schema.Codec) => { +export const encodeUnknownEffect = (codec: Schema.Codec) => { const parser = encodeUnknownSchemaResult(codec) return (u: unknown, options?: SchemaAST.ParseOptions) => { return SchemaResult.asEffect(parser(u, options)) @@ -81,9 +81,9 @@ export const encodeUnknown = (codec: Schema.Codec) = * @category Encoding * @since 4.0.0 */ -export const encode: ( +export const encodeEffect: ( codec: Schema.Codec -) => (t: T, options?: SchemaAST.ParseOptions) => Effect.Effect = encodeUnknown +) => (t: T, options?: SchemaAST.ParseOptions) => Effect.Effect = encodeUnknownEffect /** * @category Encoding @@ -100,20 +100,6 @@ export const encodeSync = ( codec: Schema.Codec ): (t: T, options?: SchemaAST.ParseOptions) => E => fromASTSync(SchemaAST.flip(codec.ast)) -/** - * @category validating - * @since 4.0.0 - */ -export const validateUnknownParserResult = (codec: Schema.Codec) => - fromASTSchemaResult(SchemaAST.typeAST(codec.ast)) - -/** - * @category validating - * @since 4.0.0 - */ -export const validateUnknownSync = (codec: Schema.Codec) => - fromASTSync(SchemaAST.typeAST(codec.ast)) - /** @internal */ export const runSyncSchemaResult = ( sr: SchemaResult.SchemaResult @@ -160,8 +146,8 @@ const defaultParseOptions: SchemaAST.ParseOptions = {} /** @internal */ export const fromASTSchemaResult = (ast: SchemaAST.AST) => { const parser = go(ast) - return (u: unknown, options?: SchemaAST.ParseOptions): SchemaResult.SchemaResult => { - const oinput = Option.some(u) + return (input: unknown, options?: SchemaAST.ParseOptions): SchemaResult.SchemaResult => { + const oinput = Option.some(input) const oa = parser(oinput, options ?? defaultParseOptions) return Effect.flatMap(oa, (oa) => { if (Option.isNone(oa)) { @@ -174,8 +160,8 @@ export const fromASTSchemaResult = (ast: SchemaAST.AST) => { const fromASTSync = (ast: SchemaAST.AST) => { const parser = fromASTSchemaResult(ast) - return (u: unknown, options?: SchemaAST.ParseOptions): A => { - return Result.getOrThrow(runSyncSchemaResult(parser(u, options))) + return (input: unknown, options?: SchemaAST.ParseOptions): A => { + return Result.getOrThrow(runSyncSchemaResult(parser(input, options))) } } diff --git a/packages/effect/src/SchemaTransformation.ts b/packages/effect/src/SchemaTransformation.ts index 989130ef24..a1d6f5f18e 100644 --- a/packages/effect/src/SchemaTransformation.ts +++ b/packages/effect/src/SchemaTransformation.ts @@ -43,6 +43,12 @@ export class SchemaTransformation { flip(): SchemaTransformation { return new SchemaTransformation(this.encode, this.decode) } + compose(other: SchemaTransformation): SchemaTransformation { + return new SchemaTransformation( + this.decode.compose(other.decode), + other.encode.compose(this.encode) + ) + } } /** @@ -98,85 +104,48 @@ export function transformOptional(options: { } /** - * @category Coercions + * @category String transformations * @since 4.0.0 */ -export const String: SchemaTransformation = new SchemaTransformation( - SchemaGetter.String, - SchemaGetter.passthrough() -) - -/** - * @category Coercions - * @since 4.0.0 - */ -export const Number: SchemaTransformation = new SchemaTransformation( - SchemaGetter.Number, - SchemaGetter.passthrough() -) - -/** - * @category Coercions - * @since 4.0.0 - */ -export const Boolean: SchemaTransformation = new SchemaTransformation( - SchemaGetter.Boolean, - SchemaGetter.passthrough() -) - -/** - * @category Coercions - * @since 4.0.0 - */ -export const BigInt: SchemaTransformation = new SchemaTransformation( - SchemaGetter.BigInt, - SchemaGetter.passthrough() -) - -/** - * @category Coercions - * @since 4.0.0 - */ -export const Date: SchemaTransformation = new SchemaTransformation( - SchemaGetter.Date, - SchemaGetter.passthrough() -) +export function trim(): SchemaTransformation { + return new SchemaTransformation( + SchemaGetter.trim(), + SchemaGetter.passthroughSupertype() + ) +} /** * @category String transformations * @since 4.0.0 */ -export const trim: SchemaTransformation = new SchemaTransformation( - SchemaGetter.trim(), - SchemaGetter.passthrough() -) +export function snakeToCamel(): SchemaTransformation { + return new SchemaTransformation( + SchemaGetter.snakeToCamel(), + SchemaGetter.camelToSnake() + ) +} /** * @category String transformations * @since 4.0.0 */ -export const snakeToCamel: SchemaTransformation = new SchemaTransformation( - SchemaGetter.snakeToCamel(), - SchemaGetter.camelToSnake() -) +export function toLowerCase(): SchemaTransformation { + return new SchemaTransformation( + SchemaGetter.toLowerCase(), + SchemaGetter.passthroughSupertype() + ) +} /** * @category String transformations * @since 4.0.0 */ -export const toLowerCase: SchemaTransformation = new SchemaTransformation( - SchemaGetter.toLowerCase(), - SchemaGetter.passthrough() -) - -/** - * @category String transformations - * @since 4.0.0 - */ -export const toUpperCase: SchemaTransformation = new SchemaTransformation( - SchemaGetter.toUpperCase(), - SchemaGetter.passthrough() -) +export function toUpperCase(): SchemaTransformation { + return new SchemaTransformation( + SchemaGetter.toUpperCase(), + SchemaGetter.passthroughSupertype() + ) +} /** * @since 4.0.0 @@ -194,30 +163,32 @@ export function json(options?: JsonOptions): SchemaTransformation() -const _compose = new SchemaTransformation(passthrough, passthrough) +const passthrough_ = new SchemaTransformation( + SchemaGetter.passthrough(), + SchemaGetter.passthrough() +) /** * @since 4.0.0 */ -export function compose(options: { readonly strict: false }): SchemaTransformation -export function compose(): SchemaTransformation -export function compose(): SchemaTransformation { - return _compose +export function passthrough(options: { readonly strict: false }): SchemaTransformation +export function passthrough(): SchemaTransformation +export function passthrough(): SchemaTransformation { + return passthrough_ } /** * @since 4.0.0 */ -export function composeSubtype(): SchemaTransformation -export function composeSubtype(): SchemaTransformation { - return _compose +export function passthroughSupertype(): SchemaTransformation +export function passthroughSupertype(): SchemaTransformation { + return passthrough_ } /** * @since 4.0.0 */ -export function composeSupertype(): SchemaTransformation -export function composeSupertype(): SchemaTransformation { - return _compose +export function passthroughSubtype(): SchemaTransformation +export function passthroughSubtype(): SchemaTransformation { + return passthrough_ } diff --git a/packages/effect/src/index.ts b/packages/effect/src/index.ts index 70cad78749..b16f0df2ca 100644 --- a/packages/effect/src/index.ts +++ b/packages/effect/src/index.ts @@ -514,11 +514,6 @@ export * as SchemaGetter from "./SchemaGetter.js" */ export * as SchemaIssue from "./SchemaIssue.js" -/** - * @since 4.0.0 - */ -export * as SchemaParser from "./SchemaParser.js" - /** * @since 4.0.0 */ @@ -529,6 +524,11 @@ export * as SchemaResult from "./SchemaResult.js" */ export * as SchemaSerializer from "./SchemaSerializer.js" +/** + * @since 4.0.0 + */ +export * as SchemaToParser from "./SchemaToParser.js" + /** * @since 4.0.0 */ diff --git a/packages/effect/src/unstable/HttpBody.ts b/packages/effect/src/unstable/HttpBody.ts index 2143272121..8f390dc680 100644 --- a/packages/effect/src/unstable/HttpBody.ts +++ b/packages/effect/src/unstable/HttpBody.ts @@ -10,7 +10,7 @@ import * as Predicate from "../Predicate.js" import type * as Schema from "../Schema.js" import type { ParseOptions } from "../SchemaAST.js" import type { Issue } from "../SchemaIssue.js" -import * as SchemaParser from "../SchemaParser.js" +import * as SchemaParser from "../SchemaToParser.js" import type * as Stream_ from "../Stream.js" import * as UrlParams from "./UrlParams.js" @@ -239,7 +239,7 @@ export const jsonSchema = >( schema: S, options?: ParseOptions | undefined ) => { - const encode = SchemaParser.encodeUnknown(schema) + const encode = SchemaParser.encodeUnknownEffect(schema) return (body: S["Type"]): Effect.Effect => encode(body, options).pipe( Effect.mapError((issue) => new HttpBodyError({ reason: { _tag: "SchemaError", issue }, cause: issue })), diff --git a/packages/effect/src/unstable/HttpClientResponse.ts b/packages/effect/src/unstable/HttpClientResponse.ts index 41666023bf..fdd678ace0 100644 --- a/packages/effect/src/unstable/HttpClientResponse.ts +++ b/packages/effect/src/unstable/HttpClientResponse.ts @@ -82,7 +82,7 @@ export const schemaJson = < schema: Schema.Codec, options?: ParseOptions | undefined ) => { - const decode = Schema.decodeUnknown(schema) + const decode = Schema.decodeUnknownEffect(schema) return ( self: HttpClientResponse ): Effect.Effect => @@ -110,7 +110,7 @@ export const schemaNoBody = < schema: Schema.Codec, options?: ParseOptions | undefined ) => { - const decode = Schema.decodeUnknown(schema) + const decode = Schema.decodeUnknownEffect(schema) return (self: HttpClientResponse): Effect.Effect => decode({ status: self.status, diff --git a/packages/effect/src/unstable/HttpIncomingMessage.ts b/packages/effect/src/unstable/HttpIncomingMessage.ts index dfb195e054..5a3ef41159 100644 --- a/packages/effect/src/unstable/HttpIncomingMessage.ts +++ b/packages/effect/src/unstable/HttpIncomingMessage.ts @@ -45,7 +45,7 @@ export interface HttpIncomingMessage extends Inspectable.Inspectable { * @category schema */ export const schemaBodyJson = >(schema: S, options?: ParseOptions | undefined) => { - const decode = Schema.decodeUnknown(schema) + const decode = Schema.decodeUnknownEffect(schema) return ( self: HttpIncomingMessage ): Effect.Effect => @@ -77,7 +77,7 @@ export const schemaHeaders = , options?: ParseOptions | undefined ) => { - const decode = Schema.decodeUnknown(schema) + const decode = Schema.decodeUnknownEffect(schema) return (self: HttpIncomingMessage): Effect.Effect => decode(self.headers, options) } diff --git a/packages/effect/test/Schema.test.ts b/packages/effect/test/Schema.test.ts index fe6c739612..c5b53f5854 100644 --- a/packages/effect/test/Schema.test.ts +++ b/packages/effect/test/Schema.test.ts @@ -12,8 +12,8 @@ import { SchemaCheck, SchemaGetter, SchemaIssue, - SchemaParser, SchemaResult, + SchemaToParser, SchemaTransformation } from "effect" import { describe, it } from "vitest" @@ -27,12 +27,11 @@ const assertions = Util.assertions({ fail }) -const Trim = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.trim)) +const Trim = Schema.String.pipe(Schema.decode(SchemaTransformation.trim())) const SnakeToCamel = Schema.String.pipe( - Schema.decodeTo( - Schema.String, - SchemaTransformation.snakeToCamel + Schema.decode( + SchemaTransformation.snakeToCamel() ) ) @@ -40,8 +39,8 @@ const NumberFromString = Schema.String.pipe( Schema.decodeTo( Schema.Number, { - decode: SchemaGetter.Number, - encode: SchemaGetter.String + decode: SchemaGetter.Number(), + encode: SchemaGetter.String() } ) ) @@ -1371,7 +1370,7 @@ describe("Schema", () => { describe("String transformations", () => { it("trim", async () => { - const schema = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.trim)) + const schema = Schema.String.pipe(Schema.decodeTo(Schema.String, SchemaTransformation.trim())) strictEqual(SchemaAST.format(schema.ast), `string <-> string`) @@ -1446,7 +1445,7 @@ describe("Schema", () => { const schema = Schema.String.pipe( Schema.decodeTo( Schema.FiniteFromString, - SchemaTransformation.trim + SchemaTransformation.trim() ) ) @@ -1458,7 +1457,7 @@ describe("Schema", () => { a: Schema.String.pipe( Schema.decodeTo( Schema.String, - SchemaTransformation.compose() + SchemaTransformation.passthrough() ) ) }) @@ -1537,7 +1536,7 @@ describe("Schema", () => { it("double transformation", async () => { const schema = Trim.pipe(Schema.decodeTo( Schema.FiniteFromString, - SchemaTransformation.compose() + SchemaTransformation.passthrough() )) await assertions.decoding.succeed(schema, " 2 ", { expected: 2 }) await assertions.decoding.fail( @@ -1556,11 +1555,11 @@ describe("Schema", () => { a: Schema.String.pipe(Schema.check(SchemaCheck.minLength(2))).pipe( Schema.decodeTo( Schema.String.pipe(Schema.check(SchemaCheck.minLength(3))), - SchemaTransformation.compose() + SchemaTransformation.passthrough() ), Schema.decodeTo( Schema.String, - SchemaTransformation.compose() + SchemaTransformation.passthrough() ) ) }) @@ -1619,13 +1618,29 @@ describe("Schema", () => { }) }) + describe("decode", () => { + it("double transformation", async () => { + const schema = Schema.String.pipe( + Schema.decode( + SchemaTransformation.trim().compose( + SchemaTransformation.toLowerCase() + ) + ) + ) + + await assertions.decoding.succeed(schema, " A ", { expected: "a" }) + + await assertions.encoding.succeed(schema, " A ", { expected: " A " }) + }) + }) + describe("encodeTo", () => { it("required to required", async () => { const schema = Schema.Struct({ a: Schema.String.pipe( Schema.encodeTo( Schema.String, - SchemaTransformation.compose() + SchemaTransformation.passthrough() ) ) }) @@ -1700,7 +1715,7 @@ describe("Schema", () => { it("double transformation", async () => { const schema = Schema.FiniteFromString.pipe(Schema.encodeTo( Trim, - SchemaTransformation.compose() + SchemaTransformation.passthrough() )) await assertions.decoding.succeed(schema, " 2 ", { expected: 2 }) await assertions.decoding.fail( @@ -1719,11 +1734,11 @@ describe("Schema", () => { a: Schema.String.pipe( Schema.encodeTo( Schema.String.pipe(Schema.check(SchemaCheck.minLength(3))), - SchemaTransformation.compose() + SchemaTransformation.passthrough() ), Schema.encodeTo( Schema.String.pipe(Schema.check(SchemaCheck.minLength(2))), - SchemaTransformation.compose() + SchemaTransformation.passthrough() ) ) }) @@ -1753,6 +1768,22 @@ describe("Schema", () => { }) }) + describe("encode", () => { + it("double transformation", async () => { + const schema = Schema.String.pipe( + Schema.encode( + SchemaTransformation.trim().compose( + SchemaTransformation.toLowerCase() + ).flip() + ) + ) + + await assertions.decoding.succeed(schema, " A ", { expected: " A " }) + + await assertions.encoding.succeed(schema, " A ", { expected: "a" }) + }) + }) + describe("flip", () => { it("string & minLength(3) <-> number & greaterThan(2)", async () => { const schema = Schema.FiniteFromString.pipe( @@ -2007,7 +2038,7 @@ describe("Schema", () => { }) await assertions.make.succeed(schema, { a: 1 }) - const spr = SchemaParser.make(schema)({}) + const spr = SchemaToParser.makeSchemaResult(schema)({}) const eff = SchemaResult.asEffect(spr) const provided = Effect.provideService( eff, @@ -2279,7 +2310,7 @@ describe("Schema", () => { const schema = Schema.String.pipe( Schema.decodeTo( Schema.String, - SchemaTransformation.toLowerCase + SchemaTransformation.toLowerCase() ) ) @@ -2289,7 +2320,7 @@ describe("Schema", () => { it("toUpperCase", async () => { const schema = Schema.String.pipe( - Schema.decodeTo(Schema.String, SchemaTransformation.toUpperCase) + Schema.decodeTo(Schema.String, SchemaTransformation.toUpperCase()) ) await assertions.decoding.succeed(schema, "a", { expected: "A" }) @@ -2414,7 +2445,7 @@ describe("Schema", () => { const jsonSerializer = schema.pipe( Schema.encodeTo( Schema.UnknownFromJsonString, - SchemaTransformation.composeSubtype() + SchemaTransformation.passthroughSupertype() ) ) @@ -2433,7 +2464,7 @@ describe("Schema", () => { a: Schema.UnknownFromJsonString.pipe( Schema.decodeTo( Schema.Struct({ b: Schema.Number }), - SchemaTransformation.composeSubtype() + SchemaTransformation.passthroughSupertype() ) ) }) @@ -3483,4 +3514,76 @@ describe("Schema", () => { strictEqual(SchemaAST.format(schema.ast), `[string, number & finite <-> string]`) }) }) + + it("decodeTo as composition", async () => { + const From = Schema.Struct({ + a: Schema.String, + b: Schema.FiniteFromString + }) + + const To = Schema.Struct({ + a: Schema.FiniteFromString, + b: Schema.UndefinedOr(Schema.Number) + }) + + const schema = From.pipe(Schema.decodeTo(To)) + + await assertions.decoding.succeed(schema, { a: "1", b: "2" }, { expected: { a: 1, b: 2 } }) + + await assertions.encoding.succeed(schema, { a: 1, b: 2 }, { expected: { a: "1", b: "2" } }) + await assertions.encoding.fail( + schema, + { a: 1, b: NaN }, + `{ readonly "a": string; readonly "b": string <-> number & finite } <-> { readonly "a": number & finite; readonly "b": number | undefined } +└─ ["b"] + └─ string <-> number & finite + └─ number & finite + └─ finite + └─ Invalid data NaN` + ) + await assertions.encoding.fail( + schema, + { a: 1, b: undefined }, + `{ readonly "a": string; readonly "b": string <-> number & finite } <-> { readonly "a": number & finite; readonly "b": number | undefined } +└─ ["b"] + └─ string <-> number & finite + └─ Expected number & finite, actual undefined` + ) + }) + + it("encodeTo as composition", async () => { + const From = Schema.Struct({ + a: Schema.String, + b: Schema.FiniteFromString + }) + + const To = Schema.Struct({ + a: Schema.FiniteFromString, + b: Schema.UndefinedOr(Schema.Number) + }) + + const schema = To.pipe(Schema.encodeTo(From)) + + await assertions.decoding.succeed(schema, { a: "1", b: "2" }, { expected: { a: 1, b: 2 } }) + + await assertions.encoding.succeed(schema, { a: 1, b: 2 }, { expected: { a: "1", b: "2" } }) + await assertions.encoding.fail( + schema, + { a: 1, b: NaN }, + `{ readonly "a": string; readonly "b": string <-> number & finite } <-> { readonly "a": number & finite; readonly "b": number | undefined } +└─ ["b"] + └─ string <-> number & finite + └─ number & finite + └─ finite + └─ Invalid data NaN` + ) + await assertions.encoding.fail( + schema, + { a: 1, b: undefined }, + `{ readonly "a": string; readonly "b": string <-> number & finite } <-> { readonly "a": number & finite; readonly "b": number | undefined } +└─ ["b"] + └─ string <-> number & finite + └─ Expected number & finite, actual undefined` + ) + }) }) diff --git a/packages/effect/test/SchemaFormatter.test.ts b/packages/effect/test/SchemaFormatter.test.ts index 449975ca75..1a3cdc09bb 100644 --- a/packages/effect/test/SchemaFormatter.test.ts +++ b/packages/effect/test/SchemaFormatter.test.ts @@ -1,4 +1,4 @@ -import { Effect, Option, Schema, SchemaCheck, SchemaFormatter, SchemaGetter, SchemaIssue, SchemaParser } from "effect" +import { Effect, Option, Schema, SchemaCheck, SchemaFormatter, SchemaGetter, SchemaIssue, SchemaToParser } from "effect" import { describe, it } from "vitest" import * as Util from "./SchemaTest.js" import { deepStrictEqual, fail, strictEqual, throws } from "./utils/assert.js" @@ -15,7 +15,7 @@ const assertStructuredIssue = async ( input: unknown, expected: ReadonlyArray ) => { - const r = await SchemaParser.decodeUnknown(schema)(input, { errors: "all" }).pipe( + const r = await SchemaToParser.decodeUnknownEffect(schema)(input, { errors: "all" }).pipe( Effect.mapError((issue) => SchemaFormatter.StructuredFormatter.format(issue)), Effect.result, Effect.runPromise @@ -118,7 +118,7 @@ describe("StructuredFormatter", () => { it("Forbidden", async () => { const schema = Schema.Struct({ a: Schema.String.pipe(Schema.decodeTo(Schema.String, { - decode: SchemaGetter.fail((o) => new SchemaIssue.Forbidden(o, { description: "my message" })), + decode: SchemaGetter.fail((os) => new SchemaIssue.Forbidden(os, { description: "my message" })), encode: SchemaGetter.passthrough() })) }) diff --git a/packages/effect/test/SchemaTest.ts b/packages/effect/test/SchemaTest.ts index d6b2d00f20..96fd547dda 100644 --- a/packages/effect/test/SchemaTest.ts +++ b/packages/effect/test/SchemaTest.ts @@ -1,5 +1,5 @@ import type { Context, SchemaAST, SchemaIssue } from "effect" -import { Effect, Result, Schema, SchemaFormatter, SchemaParser, SchemaResult, SchemaSerializer } from "effect" +import { Effect, Result, Schema, SchemaFormatter, SchemaResult, SchemaSerializer, SchemaToParser } from "effect" export const assertions = (asserts: { readonly deepStrictEqual: (actual: unknown, expected: unknown) => void @@ -34,7 +34,7 @@ export const assertions = (asserts: { expected?: S["Type"] ) { return out.effect.succeed( - SchemaResult.asEffect(SchemaParser.make(schema)(input)), + SchemaResult.asEffect(SchemaToParser.makeSchemaResult(schema)(input)), expected === undefined ? input : expected ) }, @@ -45,7 +45,7 @@ export const assertions = (asserts: { message: string, options?: Schema.MakeOptions ) { - return out.effect.fail(SchemaResult.asEffect(SchemaParser.make(schema)(input, options)), message) + return out.effect.fail(SchemaResult.asEffect(SchemaToParser.makeSchemaResult(schema)(input, options)), message) } }, @@ -83,7 +83,7 @@ export const assertions = (asserts: { expected?: unknown ) { return out.effect.succeed( - Schema.encode(SchemaSerializer.json(Schema.typeCodec(schema)))(input), + Schema.encodeEffect(SchemaSerializer.json(Schema.typeCodec(schema)))(input), arguments.length > 2 ? expected : input ) }, @@ -94,7 +94,7 @@ export const assertions = (asserts: { message: string ) { return out.effect.fail( - Schema.encode(SchemaSerializer.json(Schema.typeCodec(schema)))(input).pipe( + Schema.encodeEffect(SchemaSerializer.json(Schema.typeCodec(schema)))(input).pipe( Effect.mapError((err) => err.issue) ), message @@ -133,7 +133,7 @@ export const assertions = (asserts: { expected?: A ) { return out.effect.succeed( - Schema.decode(SchemaSerializer.json(Schema.typeCodec(schema)))(input), + Schema.decodeEffect(SchemaSerializer.json(Schema.typeCodec(schema)))(input), arguments.length > 2 ? expected : input ) }, @@ -144,7 +144,7 @@ export const assertions = (asserts: { message: string ) { return out.effect.fail( - Schema.decode(SchemaSerializer.json(Schema.typeCodec(schema)))(input).pipe( + Schema.decodeEffect(SchemaSerializer.json(Schema.typeCodec(schema)))(input).pipe( Effect.mapError((err) => err.issue) ), message @@ -185,7 +185,7 @@ export const assertions = (asserts: { readonly provide?: ReadonlyArray, any]> | undefined } | undefined ) { - const decoded = SchemaParser.decodeUnknownSchemaResult(schema)(input, options?.parseOptions) + const decoded = SchemaToParser.decodeUnknownSchemaResult(schema)(input, options?.parseOptions) const eff = Result.isResult(decoded) ? Effect.fromResult(decoded) : decoded const effWithMessage = Effect.catch(eff, (issue) => Effect.fail(SchemaFormatter.TreeFormatter.format(issue))) let provided = effWithMessage @@ -214,7 +214,7 @@ export const assertions = (asserts: { readonly provide?: ReadonlyArray, any]> | undefined } | undefined ) { - const decoded = SchemaParser.decodeUnknownSchemaResult(schema)(input, options?.parseOptions) + const decoded = SchemaToParser.decodeUnknownSchemaResult(schema)(input, options?.parseOptions) const eff = Result.isResult(decoded) ? Effect.fromResult(decoded) : decoded let provided = eff if (options?.provide) { @@ -241,7 +241,7 @@ export const assertions = (asserts: { } | undefined ) { // Account for `expected` being `undefined` - const encoded = SchemaParser.encodeUnknownSchemaResult(schema)(input, options?.parseOptions) + const encoded = SchemaToParser.encodeUnknownSchemaResult(schema)(input, options?.parseOptions) const eff = Result.isResult(encoded) ? Effect.fromResult(encoded) : encoded return out.effect.succeed( Effect.catch(eff, (issue) => Effect.fail(SchemaFormatter.TreeFormatter.format(issue))), @@ -262,7 +262,7 @@ export const assertions = (asserts: { readonly parseOptions?: SchemaAST.ParseOptions | undefined } | undefined ) { - const encoded = SchemaParser.encodeUnknownSchemaResult(schema)(input, options?.parseOptions) + const encoded = SchemaToParser.encodeUnknownSchemaResult(schema)(input, options?.parseOptions) return out.effect.fail(SchemaResult.asEffect(encoded), message) } },