Files
effect/schema/CHANGELOG.md
T

299 KiB

@effect/schema

0.75.5

Patch Changes

  • #3792 382556f Thanks @gcanti! - resolve parse error when using pick with union of class schemas, closes #3751

  • #3790 97cb014 Thanks @gcanti! - Equivalence: Fixed a bug related to discriminated tuples.

    Example:

    The following equivalence check was incorrectly returning false:

    import * as E from "@effect/schema/Equivalence"
    import * as S from "@effect/schema/Schema"
    
    // Union of discriminated tuples
    const schema = S.Union(
      S.Tuple(S.Literal("a"), S.String),
      S.Tuple(S.Literal("b"), S.Number)
    )
    
    const equivalence = E.make(schema)
    
    console.log(equivalence(["a", "x"], ["a", "x"]))
    // false
    

0.75.4

Patch Changes

  • Updated dependencies [61a99b2]:
    • effect@3.9.2

0.75.3

Patch Changes

  • #3761 360ec14 Thanks @gcanti! - Allow Schema.Either to support Schema.Never without type errors, closes #3755.

    • Updated the type parameters of format to extend Schema.All instead of Schema<A, I, R>.
    • Updated the type parameters of Schema.EitherFromSelf to extend Schema.All instead of Schema.Any.
    • Updated the type parameters of Schema.Either to extend Schema.All instead of Schema.Any.
    • Updated the type parameters of Schema.EitherFromUnion to extend Schema.All instead of Schema.Any.

0.75.2

Patch Changes

  • #3753 f02b354 Thanks @gcanti! - Enhanced Error Reporting for Discriminated Union Tuple Schemas, closes #3752

    Previously, irrelevant error messages were generated for each member of the union. Now, when a discriminator is present in the input, only the relevant member will trigger an error.

    Before

    import * as Schema from "@effect/schema/Schema"
    
    const schema = Schema.Union(
      Schema.Tuple(Schema.Literal("a"), Schema.String),
      Schema.Tuple(Schema.Literal("b"), Schema.Number)
    ).annotations({ identifier: "MyUnion" })
    
    console.log(Schema.decodeUnknownSync(schema)(["a", 0]))
    /*
    throws:
    ParseError: MyUnion
    ├─ readonly ["a", string]
    │  └─ [1]
    │     └─ Expected string, actual 0
    └─ readonly ["b", number]
       └─ [0]
          └─ Expected "b", actual "a"
    */
    

    After

    import * as Schema from "@effect/schema/Schema"
    
    const schema = Schema.Union(
      Schema.Tuple(Schema.Literal("a"), Schema.String),
      Schema.Tuple(Schema.Literal("b"), Schema.Number)
    ).annotations({ identifier: "MyUnion" })
    
    console.log(Schema.decodeUnknownSync(schema)(["a", 0]))
    /*
    throws:
    ParseError: MyUnion
    └─ readonly ["a", string]
       └─ [1]
          └─ Expected string, actual 0
    */
    

0.75.1

Patch Changes

  • #3740 3b2ad1d Thanks @tim-smart! - revert deno Inspectable changes

  • Updated dependencies [3b2ad1d]:

    • effect@3.9.1

0.75.0

Minor Changes

  • #3620 0ba66f2 Thanks @tim-smart! - add deno support to Inspectable

Patch Changes

0.74.2

Patch Changes

0.74.1

Patch Changes

  • #3669 734eae6 Thanks @gcanti! - Add description annotation to the encoded part of NumberFromString.

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.NumberFromString
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "string"
    }
    */
    

    After

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.NumberFromString
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "string",
      "description": "a string that will be parsed into a number"
    }
    */
    
  • #3667 fd83d0e Thanks @gcanti! - Remove default json schema annotations from string, number and boolean.

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.String.annotations({ examples: ["a", "b"] })
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "string",
      "description": "a string",
      "title": "string",
      "examples": [
        "a",
        "b"
      ]
    }
    */
    

    After

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.String.annotations({ examples: ["a", "b"] })
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "string",
      "examples": [
        "a",
        "b"
      ]
    }
    */
    
  • #3673 ad7e1de Thanks @gcanti! - Add more description annotations.

  • #3672 090e41c Thanks @gcanti! - JSON Schema: handle refinements where the 'from' part includes a transformation, closes #3662

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Date
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    /*
    throws
    Error: Missing annotation
    details: Generating a JSON Schema for this schema requires a "jsonSchema" annotation
    schema (Refinement): Date
    */
    

    After

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Date
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "string",
      "description": "a string that will be parsed into a Date"
    }
    */
    
  • #3672 090e41c Thanks @gcanti! - Add description annotation to the encoded part of DateFromString.

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.DateFromString
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "string"
    }
    */
    

    After

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.DateFromString
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "string",
      "description": "a string that will be parsed into a Date"
    }
    */
    
  • Updated dependencies [4509656]:

    • effect@3.8.4

0.74.0

Minor Changes

  • #3654 de48aa5 Thanks @gcanti! - Remove internal sorting of property signatures, closes #3652

0.73.4

Patch Changes

  • Updated dependencies [bb5ec6b]:
    • effect@3.8.3

0.73.3

Patch Changes

  • #3635 e6440a7 Thanks @gcanti! - Stable filters such as minItems, maxItems, and itemsCount now generate multiple errors when the 'errors' option is set to 'all', closes #3633

    Example:

    import { ArrayFormatter, Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      tags: Schema.Array(Schema.String.pipe(Schema.minLength(2))).pipe(
        Schema.minItems(3)
      )
    })
    
    const invalidData = { tags: ["AB", "B"] }
    
    const either = Schema.decodeUnknownEither(schema, { errors: "all" })(
      invalidData
    )
    if (either._tag === "Left") {
      console.log(ArrayFormatter.formatErrorSync(either.left))
      /*
      Output:
      [
        {
          _tag: 'Type',
          path: [ 'tags', 1 ],
          message: 'Expected a string at least 2 character(s) long, actual "B"'
        },
        {
          _tag: 'Type',
          path: [ 'tags' ],
          message: 'Expected an array of at least 3 items, actual ["AB","B"]'
        }
      ]
      */
    }
    

    Previously, only the issue related to the [ 'tags', 1 ] path was reported.

0.73.2

Patch Changes

  • Updated dependencies [f0d8ef1]:
    • effect@3.8.2

0.73.1

Patch Changes

  • #3619 f56ab78 Thanks @gcanti! - add Date filters (less than, greater than, between), closes #3606

  • Updated dependencies [10bf621, ae36fa6]:

    • effect@3.8.1

0.73.0

Minor Changes

  • #3589 7fdf9d9 Thanks @gcanti! - Updates the constraints for members within a union from the more restrictive Schema.Any to the more inclusive Schema.All, closes #3587.

    Affected APIs include:

    • Schema.Union
    • Schema.UndefinedOr
    • Schema.NullOr
    • Schema.NullishOr
    • Schema.optional
    • AST.Union.make now retains duplicate members and no longer eliminates the neverKeyword.

Patch Changes

0.72.4

Patch Changes

  • Updated dependencies [35a0f81]:
    • effect@3.7.3

0.72.3

Patch Changes

  • #3560 f6acb71 Thanks @gcanti! - Enhanced the generation of recursive Arbitraries to prevent infinite nesting, closes #3512

0.72.2

Patch Changes

0.72.1

Patch Changes

0.72.0

Patch Changes

0.71.4

Patch Changes

  • Updated dependencies [e809286]:
    • effect@3.6.8

0.71.3

Patch Changes

  • Updated dependencies [50ec889]:
    • effect@3.6.7

0.71.2

Patch Changes

0.71.1

Patch Changes

0.71.0

Minor Changes

  • #3433 c1987e2 Thanks @gcanti! - Make json schema output more compatible with Open AI structured output, closes #3432.

    JSONSchema

    • remove oneOf in favour of anyOf (e.g. in JsonSchema7object, JsonSchema7empty, JsonSchema7Enums)
    • remove const in favour of enum (e.g. in JsonSchema7Enums)
    • remove JsonSchema7Const type
    • remove JsonSchema7OneOf type

    AST

    • remove identifier annotation from Schema.Null
    • remove identifier annotation from Schema.Object

Patch Changes

  • #3448 1ceed14 Thanks @tim-smart! - add Schema.ArrayEnsure & Schema.NonEmptyArrayEnsure

    These schemas can be used to ensure that a value is an array, from a value that may be an array or a single value.

    import { Schema } from "@effect/schema"
    
    const schema = Schema.ArrayEnsure(Schema.String)
    
    Schema.decodeUnknownSync(schema)("hello")
    // => ["hello"]
    
    Schema.decodeUnknownSync(schema)(["a", "b", "c"])
    // => ["a", "b", "c"]
    
  • #3450 0e42a8f Thanks @tim-smart! - update dependencies

  • Updated dependencies [8295281, c940df6, 00b6c6d, f8d95a6]:

    • effect@3.6.4

0.70.4

Patch Changes

  • Updated dependencies [04adcac]:
    • effect@3.6.3

0.70.3

Patch Changes

  • #3430 99ad841 Thanks @gcanti! - Fix return types for attachPropertySignature function.

    This commit addresses an inconsistency in the return types between the curried and non-curried versions of the attachPropertySignature function. Previously, the curried version returned a Schema, while the non-curried version returned a SchemaClass.

  • Updated dependencies [fd4b2f6]:

    • effect@3.6.2

0.70.2

Patch Changes

0.70.1

Patch Changes

  • #3347 3dce357 Thanks @gcanti! - Enhanced Parsing with TemplateLiteralParser, closes #3307

    In this update we've introduced a sophisticated API for more refined string parsing: TemplateLiteralParser. This enhancement stems from recognizing limitations in the Schema.TemplateLiteral and Schema.pattern functionalities, which effectively validate string formats without extracting structured data.

    Overview of Existing Limitations

    The Schema.TemplateLiteral function, while useful as a simple validator, only verifies that an input conforms to a specific string pattern by converting template literal definitions into regular expressions. Similarly, Schema.pattern employs regular expressions directly for the same purpose. Post-validation, both methods require additional manual parsing to convert the validated string into a usable data format.

    Introducing TemplateLiteralParser

    To address these limitations and eliminate the need for manual post-validation parsing, the new TemplateLiteralParser API has been developed. It not only validates the input format but also automatically parses it into a more structured and type-safe output, specifically into a tuple format.

    This new approach enhances developer productivity by reducing boilerplate code and simplifying the process of working with complex string inputs.

    Example (string based schemas)

    import { Schema } from "@effect/schema"
    
    // const schema: Schema.Schema<readonly [number, "a", string], `${string}a${string}`, never>
    const schema = Schema.TemplateLiteralParser(
      Schema.NumberFromString,
      "a",
      Schema.NonEmptyString
    )
    
    console.log(Schema.decodeEither(schema)("100ab"))
    // { _id: 'Either', _tag: 'Right', right: [ 100, 'a', 'b' ] }
    
    console.log(Schema.encode(schema)([100, "a", "b"]))
    // { _id: 'Either', _tag: 'Right', right: '100ab' }
    

    Example (number based schemas)

    import { Schema } from "@effect/schema"
    
    // const schema: Schema.Schema<readonly [number, "a"], `${number}a`, never>
    const schema = Schema.TemplateLiteralParser(Schema.Int, "a")
    
    console.log(Schema.decodeEither(schema)("1a"))
    // { _id: 'Either', _tag: 'Right', right: [ 1, 'a' ] }
    
    console.log(Schema.encode(schema)([1, "a"]))
    // { _id: 'Either', _tag: 'Right', right: '1a' }
    
  • #3346 657fc48 Thanks @gcanti! - Implement DecodingFallbackAnnotation to manage decoding errors.

    export type DecodingFallbackAnnotation<A> = (
      issue: ParseIssue
    ) => Effect<A, ParseIssue>
    

    This update introduces a decodingFallback annotation, enabling custom handling of decoding failures in schemas. This feature allows developers to specify fallback behaviors when decoding operations encounter issues.

    Example

    import { Schema } from "@effect/schema"
    import { Effect, Either } from "effect"
    
    // Basic Fallback
    
    const schema = Schema.String.annotations({
      decodingFallback: () => Either.right("<fallback>")
    })
    
    console.log(Schema.decodeUnknownSync(schema)("valid input")) // Output: valid input
    console.log(Schema.decodeUnknownSync(schema)(null)) // Output: <fallback value>
    
    // Advanced Fallback with Logging
    
    const schemaWithLog = Schema.String.annotations({
      decodingFallback: (issue) =>
        Effect.gen(function* () {
          yield* Effect.log(issue._tag)
          yield* Effect.sleep(10)
          return yield* Effect.succeed("<fallback2>")
        })
    })
    
    Effect.runPromise(Schema.decodeUnknown(schemaWithLog)(null)).then(console.log)
    /*
    Output:
    timestamp=2024-07-25T13:22:37.706Z level=INFO fiber=#0 message=Type
    <fallback2>
    */
    

0.70.0

Patch Changes

0.69.3

Patch Changes

  • #3359 7c0da50 Thanks @gcanti! - Add Context field to Schema interface, closes #3356

  • #3363 2fc0ff4 Thanks @gcanti! - export isPropertySignature guard

  • #3357 f262665 Thanks @gcanti! - Improve annotation retrieval from Class APIs, closes #3348.

    Previously, accessing annotations such as identifier and title required explicit casting of the ast field to AST.Transformation. This update refines the type definitions to reflect that ast is always an AST.Transformation, eliminating the need for casting and simplifying client code.

    import { AST, Schema } from "@effect/schema"
    
    class Person extends Schema.Class<Person>("Person")(
      {
        name: Schema.String,
        age: Schema.Number
      },
      { description: "my description" }
    ) {}
    
    console.log(AST.getDescriptionAnnotation(Person.ast.to))
    // { _id: 'Option', _tag: 'Some', value: 'my description' }
    
  • #3343 9bbe7a6 Thanks @gcanti! - - add NonEmptyTrimmedString

    Example

    import { Schema } from "@effect/schema"
    
    console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)("")) // Option.none()
    console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)(" a ")) // Option.none()
    console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)("a")) // Option.some("a")
    
    • add OptionFromNonEmptyTrimmedString, closes #3335

      Example

      import { Schema } from "@effect/schema"
      
      console.log(Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)("")) // Option.none()
      console.log(
        Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)(" a ")
      ) // Option.some("a")
      console.log(Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)("a")) // Option.some("a")
      
  • Updated dependencies [6359644, 7f41e42, f566fd1]:

    • effect@3.5.9

0.69.2

Patch Changes

0.69.1

Patch Changes

  • #3333 f241154 Thanks @gcanti! - Expose success and failure schemas on TaggedRequestClass interface, closes #3331

0.69.0

Minor Changes

  • #3227 20807a4 Thanks @gcanti! - ## Codemod

    For some of the breking changes, a code-mod has been released to make migration as easy as possible.

    You can run it by executing:

    npx @effect/codemod schema-0.69 src/**/*
    

    It might not be perfect - if you encounter issues, let us know! Also make sure you commit any changes before running it, in case you need to revert anything.

    Breaking Changes

    Schema

    • We've improved the TaggedRequest API to make it more intuitive by grouping parameters into a single object (codmod), closes #3144

      Before Update

      class Sample extends Schema.TaggedRequest<Sample>()(
        "Sample",
        Schema.String, // Failure Schema
        Schema.Number, // Success Schema
        { id: Schema.String, foo: Schema.Number } // Payload Schema
      ) {}
      

      After Update

      class Sample extends Schema.TaggedRequest<Sample>()("Sample", {
        payload: {
          id: Schema.String,
          foo: Schema.Number
        },
        success: Schema.Number,
        failure: Schema.String
      }) {}
      
    • change TaggedRequestClass type parameters order (swap Success with Failure)

    • simplify TaggedRequest.Any, use TaggedRequest.All instead

    • To improve clarity, we have renamed nonEmpty filter to nonEmptyString and NonEmpty schema to NonEmptyString (codmod), closes #3115

    • The Record constructor now consistently accepts an object argument, aligning it with similar constructors such as Map and HashMap (codmod), closes #2793

      Before Update

      import { Schema } from "@effect/schema"
      
      const schema = Schema.Record(Schema.String, Schema.Number)
      

      After Update

      import { Schema } from "@effect/schema"
      
      const schema = Schema.Record({ key: Schema.String, value: Schema.Number })
      
    • rename Base64 to Uint8ArrayFromBase64 (codmod)

    • rename Base64Url to Uint8ArrayFromBase64Url (codmod)

    • rename Hex to Uint8ArrayFromHex (codmod)

    • make defect schema required in ExitFromSelf, Exit, CauseFromSelf, CauseFromSelf (codmod) This is for two reasons:

      1. The optionality of defect caused inference issues when the schema was declared within a Struct. In such cases, the R type of the schema was erroneously inferred as unknown instead of never.
      2. In general, schema definitions such as Schema.ExitFromSelf or Schema.Exit shouldn't have a default. The user should actively choose them to avoid hidden behaviors.
    • rename CauseDefectUnknown to Defect (codmod)

    • fix Schema.Void behavior: now accepts any value instead of only validating undefined, closes #3297

    • rename optionalWithOptions interface to optionalWith

    • We've refined the optional and partial APIs by splitting them into two distinct methods: one without options (optional and partial) and another with options (optionalWith and partialWith). This change resolves issues with previous implementations when used with the pipe method:

      Schema.String.pipe(Schema.optional)
      

    ParseResult

    • Missing: change ast field from AST.Annotated to AST.Type
    • Composite: change ast field from AST.Annotated to AST.AST
    • Type: change ast field from AST.Annotated to AST.AST
    • Forbidden: change ast field from AST.Annotated to AST.AST

    AST

    • pass the input of the transformation to transform and transformOrFail APIs

    • fix TemplateLiteralSpan.toString implementation by returning both its type and its literal

      Before

      import { AST } from "@effect/schema"
      
      console.log(String(new AST.TemplateLiteralSpan(AST.stringKeyword, "a"))) // ${string}
      

      Now

      import { AST } from "@effect/schema"
      
      console.log(String(new AST.TemplateLiteralSpan(AST.stringKeyword, "a"))) // ${string}a
      

    Serializable

    • change WithResult fields to standard lowercase (Success -> success, Failure -> failure)
    • rename WithResult.Error to WithResult.Failure

    New Features

    Schema

    • add StringFromBase64 transformation

    • add StringFromBase64Url transformation

    • add StringFromHex transformation

    • add TaggedRequest.All

    • Support for extending Schema.String, Schema.Number, and Schema.Boolean with refinements has been added:

      import { Schema } from "@effect/schema"
      
      const Integer = Schema.Int.pipe(Schema.brand("Int"))
      const Positive = Schema.Positive.pipe(Schema.brand("Positive"))
      
      // Schema.Schema<number & Brand<"Positive"> & Brand<"Int">, number, never>
      const PositiveInteger = Schema.asSchema(Schema.extend(Positive, Integer))
      
      Schema.decodeUnknownSync(PositiveInteger)(-1)
      /*
      throws
      ParseError: Int & Brand<"Int">
      └─ From side refinement failure
        └─ Positive & Brand<"Positive">
            └─ Predicate refinement failure
              └─ Expected Positive & Brand<"Positive">, actual -1
      */
      
      Schema.decodeUnknownSync(PositiveInteger)(1.1)
      /*
      throws
      ParseError: Int & Brand<"Int">
      └─ Predicate refinement failure
        └─ Expected Int & Brand<"Int">, actual 1.1
      */
      

    Serializable

    • add WithResult.SuccessEncoded
    • add WithResult.FailureEncoded
    • add WithResult.Any
    • add WithResult.All
    • add asWithResult
    • add Serializable.Any
    • add Serializable.All
    • add asSerializable
    • add SerializableWithResult.Any
    • add SerializableWithResult.All
    • add asSerializableWithResult

0.68.27

Patch Changes

  • #3310 99bddcf Thanks @fubhy! - Added additional pure annotations to improve tree-shakeability

  • #3311 6921c4f Thanks @gcanti! - Remove incorrect static override type annotations in class definitions.

    This will also improve tree-shakeability.

  • Updated dependencies [3afcc93, 99bddcf]:

    • effect@3.5.7

0.68.26

Patch Changes

  • #3287 f0285d3 Thanks @gcanti! - JSON Schema: change default behavior for property signatures containing undefined

    Changed the default behavior when encountering a required property signature whose type contains undefined. Instead of raising an exception, undefined is now pruned and the field is set as optional.

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      a: Schema.NullishOr(Schema.Number)
    })
    
    const jsonSchema = JSONSchema.make(schema)
    console.log(JSON.stringify(jsonSchema, null, 2))
    /*
    throws
    Error: Missing annotation
    at path: ["a"]
    details: Generating a JSON Schema for this schema requires a "jsonSchema" annotation
    schema (UndefinedKeyword): undefined
    */
    

    Now

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      a: Schema.NullishOr(Schema.Number)
    })
    
    const jsonSchema = JSONSchema.make(schema)
    console.log(JSON.stringify(jsonSchema, null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "required": [], // <=== empty
      "properties": {
        "a": {
          "anyOf": [
            {
              "type": "number"
            },
            {
              "$ref": "#/$defs/null"
            }
          ]
        }
      },
      "additionalProperties": false,
      "$defs": {
        "null": {
          "const": null
        }
      }
    }
    */
    
  • #3291 8ec4955 Thanks @gcanti! - remove type-level error message from optional signature, closes #3290

    This fix eliminates the type-level error message from the optional function signature, which was causing issues in generic contexts.

  • #3284 3ac2d76 Thanks @gcanti! - Fix: Correct Handling of JSON Schema Annotations in Refinements

    Fixes an issue where the JSON schema annotation set by a refinement after a transformation was mistakenly interpreted as an override annotation. This caused the output to be incorrect, as the annotations were not applied as intended.

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Trim.pipe(Schema.nonEmpty())
    
    const jsonSchema = JSONSchema.make(schema)
    console.log(JSON.stringify(jsonSchema, null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "minLength": 1
    }
    */
    

    Now

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Trim.pipe(Schema.nonEmpty())
    
    const jsonSchema = JSONSchema.make(schema)
    console.log(JSON.stringify(jsonSchema, null, 2))
    /*
    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "string"
    }
    */
    
  • Updated dependencies [cc327a1, 4bfe4fb, 2b14d18]:

    • effect@3.5.6

0.68.25

Patch Changes

  • Updated dependencies [a9d7800]:
    • effect@3.5.5

0.68.24

Patch Changes

0.68.23

Patch Changes

0.68.22

Patch Changes

0.68.21

Patch Changes

  • Updated dependencies [55fdd76]:
    • effect@3.5.1

0.68.20

Patch Changes

0.68.19

Patch Changes

0.68.18

Patch Changes

  • #3192 5d5cc6c Thanks @KhraksMamtsov! - Support Capitalize Uncapitalize filters and schemas

  • #3148 359ff8a Thanks @gcanti! - add Serializable.Serializable.Type and Serializable.Serializable.Encoded

  • #3198 f7534b9 Thanks @gcanti! - Add toString to AST.PropertySignature and AST.IndexSignature and fix type display for IndexSignature.

    Before the Change

    Previously, when a type mismatch occurred in Schema.decodeUnknownSync, the error message displayed for IndexSignature was not accurately representing the type used. For example:

    import { Schema } from "@effect/schema"
    
    const schema = Schema.Record(Schema.Char, Schema.String)
    
    Schema.decodeUnknownSync(schema)({ a: 1 })
    /*
    throws
    ParseError: { readonly [x: string]: string }
    └─ ["a"]
       └─ Expected string, actual 1
    */
    

    This output incorrectly indicated [x: string] when the actual index type was Char.

    After the Change

    The toString implementation now correctly reflects the type used in IndexSignature, providing more accurate and informative error messages:

    import { Schema } from "@effect/schema"
    
    const schema = Schema.Record(Schema.Char, Schema.String)
    
    Schema.decodeUnknownSync(schema)({ a: 1 })
    /*
    throws
    ParseError: { readonly [x: Char]: string }
    └─ ["a"]
       └─ Expected string, actual 1
    */
    

    The updated output now correctly displays { readonly [x: Char]: string }, aligning the error messages with the actual data types used in the schema.

  • Updated dependencies [a435e0f, b5554db, a9c4fb3]:

    • effect@3.4.8

0.68.17

Patch Changes

  • #3166 15967cf Thanks @gcanti! - Add filterEffect API, closes #3165

    The filterEffect function enhances the filter functionality by allowing the integration of effects, thus enabling asynchronous or dynamic validation scenarios. This is particularly useful when validations need to perform operations that require side effects, such as network requests or database queries.

    Example: Validating Usernames Asynchronously

    import { Schema } from "@effect/schema"
    import { Effect } from "effect"
    
    async function validateUsername(username: string) {
      return Promise.resolve(username === "gcanti")
    }
    
    const ValidUsername = Schema.String.pipe(
      Schema.filterEffect((username) =>
        Effect.promise(() =>
          validateUsername(username).then((valid) => valid || "Invalid username")
        )
      )
    ).annotations({ identifier: "ValidUsername" })
    
    Effect.runPromise(Schema.decodeUnknown(ValidUsername)("xxx")).then(
      console.log
    )
    /*
    ParseError: ValidUsername
    └─ Transformation process failure
       └─ Invalid username
    */
    
  • #3163 2328e17 Thanks @gcanti! - Add pick and omit static functions to Struct interface, closes #3152.

    pick

    The pick static function available in each struct schema can be used to create a new Struct by selecting particular properties from an existing Struct.

    import { Schema } from "@effect/schema"
    
    const MyStruct = Schema.Struct({
      a: Schema.String,
      b: Schema.Number,
      c: Schema.Boolean
    })
    
    // Schema.Struct<{ a: typeof Schema.String; c: typeof Schema.Boolean; }>
    const PickedSchema = MyStruct.pick("a", "c")
    

    omit

    The omit static function available in each struct schema can be used to create a new Struct by excluding particular properties from an existing Struct.

    import { Schema } from "@effect/schema"
    
    const MyStruct = Schema.Struct({
      a: Schema.String,
      b: Schema.Number,
      c: Schema.Boolean
    })
    
    // Schema.Struct<{ a: typeof Schema.String; c: typeof Schema.Boolean; }>
    const PickedSchema = MyStruct.omit("b")
    
  • Updated dependencies [a5737d6]:

    • effect@3.4.7

0.68.16

Patch Changes

  • #3143 d006cec Thanks @gcanti! - Enhance JSON Schema Support for Refinements in Record Parameters.

    Enhanced JSONSchema.make to properly support refinements as record parameters. Previously, using refinements with Schema.Record resulted in errors when generating JSON schemas.

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Record(
      Schema.String.pipe(Schema.minLength(1)),
      Schema.Number
    )
    
    console.log(JSONSchema.make(schema))
    /*
    throws
    Error: Unsupported index signature parameter
    schema (Refinement): a string at least 1 character(s) long
    */
    

    Now

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Record(
      Schema.String.pipe(Schema.minLength(1)),
      Schema.Number
    )
    
    console.log(JSONSchema.make(schema))
    /*
    Output:
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      required: [],
      properties: {},
      patternProperties: { '': { type: 'number' } },
      propertyNames: {
        type: 'string',
        description: 'a string at least 1 character(s) long',
        minLength: 1
      }
    }
    */
    
  • #3149 cb22726 Thanks @tim-smart! - add Serializable.WithResult.Success/Error inference helpers

  • #3139 e911cfd Thanks @gcanti! - Optimize JSON Schema output for homogeneous tuples (such as non empty arrays).

    This change corrects the JSON Schema generation for S.NonEmptyArray to eliminate redundant schema definitions. Previously, the element schema was unnecessarily duplicated under both items and additionalItems.

0.68.15

Patch Changes

  • #3130 34faeb6 Thanks @gcanti! - Add ReadonlyMapFromRecord and MapFromRecord, closes #3119

    • decoding
      • { readonly [x: string]: VI } -> ReadonlyMap<KA, VA>
    • encoding
      • ReadonlyMap<KA, VA> -> { readonly [x: string]: VI }
    import { Schema } from "@effect/schema"
    
    const schema = Schema.ReadonlyMapFromRecord({
      key: Schema.BigInt,
      value: Schema.NumberFromString
    })
    
    const decode = Schema.decodeUnknownSync(schema)
    const encode = Schema.encodeSync(schema)
    
    console.log(
      decode({
        "1": "4",
        "2": "5",
        "3": "6"
      })
    ) // Map(3) { 1n => 4, 2n => 5, 3n => 6 }
    console.log(
      encode(
        new Map([
          [1n, 4],
          [2n, 5],
          [3n, 6]
        ])
      )
    ) // { '1': '4', '2': '5', '3': '6' }
    
  • Updated dependencies [5c0ceb0, 5c0ceb0, 33735b1, 5c0ceb0, 139d4b3]:

    • effect@3.4.6

0.68.14

Patch Changes

  • #3125 61e5964 Thanks @gcanti! - Add support for Union, Suspend, and Refinement as the second argument of extend, closes #3124

0.68.13

Patch Changes

  • #3117 cb76bcb Thanks @gcanti! - Modified JSONSchema.make to selectively ignore the title and description fields in schema types such as Schema.String, Schema.Number, and Schema.Boolean, closes #3116

    Before

    import { JSONSchema, Schema as S } from "@effect/schema"
    
    const schema = S.Struct({
      foo: S.String,
      bar: S.Number
    })
    
    console.log(JSONSchema.make(schema))
    /*
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      required: [ 'foo', 'bar' ],
      properties: {
        foo: { type: 'string', description: 'a string', title: 'string' },
        bar: { type: 'number', description: 'a number', title: 'number' }
      },
      additionalProperties: false
    }
    */
    

    Now

    import { JSONSchema, Schema as S } from "@effect/schema"
    
    const schema = S.Struct({
      foo: S.String,
      bar: S.Number
    })
    
    console.log(JSONSchema.make(schema))
    /*
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      required: [ 'foo', 'bar' ],
      properties: { foo: { type: 'string' }, bar: { type: 'number' } },
      additionalProperties: false
    }
    */
    

0.68.12

Patch Changes

  • #3101 d990544 Thanks @gcanti! - Generate JSON Schemas correctly for a schema created by extending two refinements using the extend API, ensuring their JSON Schema annotations are preserved.

    Example

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      a: Schema.String
    })
      .pipe(Schema.filter(() => true, { jsonSchema: { a: 1 } }))
      .pipe(
        Schema.extend(
          Schema.Struct({
            b: Schema.Number
          }).pipe(Schema.filter(() => true, { jsonSchema: { b: 2 } }))
        )
      )
    
    console.log(JSONSchema.make(schema))
    /*
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      required: [ 'a', 'b' ],
      properties: {
        a: { type: 'string', description: 'a string', title: 'string' },
        b: { type: 'number', description: 'a number', title: 'number' }
      },
      additionalProperties: false,
      b: 2,
      a: 1
    }
    */
    
  • Updated dependencies [a047af9]:

    • effect@3.4.5

0.68.11

Patch Changes

  • #3087 d71c192 Thanks @gcanti! - Special case S.parseJson to generate JSON Schemas by targeting the "to" side of transformations, closes #3086

    Resolved an issue where JSONSchema.make improperly generated JSON Schemas for schemas defined with S.parseJson(<real schema>). Previously, invoking JSONSchema.make on these transformed schemas produced a JSON Schema corresponding to a string type rather than the underlying real schema.

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    // Define a schema that parses a JSON string into a structured object
    const schema = Schema.parseJson(
      Schema.Struct({
        a: Schema.parseJson(Schema.NumberFromString) // Nested parsing from JSON string to number
      })
    )
    
    console.log(JSONSchema.make(schema))
    /*
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      '$ref': '#/$defs/JsonString',
      '$defs': {
        JsonString: {
          type: 'string',
          description: 'a JSON string',
          title: 'JsonString'
        }
      }
    }
    */
    

    Now

    import { JSONSchema, Schema } from "@effect/schema"
    
    // Define a schema that parses a JSON string into a structured object
    const schema = Schema.parseJson(
      Schema.Struct({
        a: Schema.parseJson(Schema.NumberFromString) // Nested parsing from JSON string to number
      })
    )
    
    console.log(JSONSchema.make(schema))
    /*
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      required: [ 'a' ],
      properties: { a: { type: 'string', description: 'a string', title: 'string' } },
      additionalProperties: false
    }
    */
    
  • Updated dependencies [72638e3, d7dde2b, 9b2fc3b]:

    • effect@3.4.4

0.68.10

Patch Changes

0.68.9

Patch Changes

  • #3074 0b47fdf Thanks @gcanti! - Revert the 0.67.22 patch as it is causing issues with other array filters, closes #3073

0.68.8

Patch Changes

  • #3070 192261b Thanks @gcanti! - Add refineTypeId unique symbol to the refine interface to ensure correct inference of Fields in the Class APIs, closes #3063

  • Updated dependencies [3da1497]:

    • effect@3.4.2

0.68.7

Patch Changes

  • Updated dependencies [66a1910]:
    • effect@3.4.1

0.68.6

Patch Changes

  • #3046 530fa9e Thanks @gcanti! - Fix error message display for composite errors when overwrite = false

    This commit resolves an issue where the custom message for a struct (or tuple or union) was displayed regardless of whether the validation error was related to the entire struct or just a specific part of it. Previously, users would see the custom error message even when the error only concerned a particular field within the struct and the flag overwrite was not set to true.

    import { Schema, TreeFormatter } from "@effect/schema"
    import { Either } from "effect"
    
    const schema = Schema.Struct({
      a: Schema.String
    }).annotations({ message: () => "custom message" })
    
    const res = Schema.decodeUnknownEither(schema)({ a: null })
    if (Either.isLeft(res)) {
      console.log(TreeFormatter.formatErrorSync(res.left))
      // before: custom message
      // now: { readonly a: string }
      //      └─ ["a"]
      //         └─ Expected string, actual null
    }
    

0.68.5

Patch Changes

  • #3043 1d62815 Thanks @gcanti! - Add make constructor to Class-based APIs, closes #3042

    Introduced a make constructor to class-based APIs to facilitate easier instantiation of classes. This method allows developers to create instances of a class without directly using the new keyword.

    Example

    import { Schema } from "@effect/schema"
    
    class MyClass extends Schema.Class<MyClass>("MyClass")({
      someField: Schema.String
    }) {
      someMethod() {
        return this.someField + "bar"
      }
    }
    
    // Create an instance of MyClass using the make constructor
    const instance = MyClass.make({ someField: "foo" }) // same as new MyClass({ someField: "foo" })
    
    // Outputs to console to demonstrate that the instance is correctly created
    console.log(instance instanceof MyClass) // true
    console.log(instance.someField) // "foo"
    console.log(instance.someMethod()) // "foobar"
    

0.68.4

Patch Changes

0.68.3

Patch Changes

  • #3028 d473800 Thanks @gcanti! - Introducing Customizable Parsing Behavior at the Schema Level, closes #3027

    With this latest update, developers can now set specific parse options for each schema using the parseOptions annotation. This flexibility allows for precise parsing behaviors across different levels of your schema hierarchy, giving you the ability to override settings in parent schemas and propagate settings to nested schemas as needed.

    Here's how you can leverage this new feature:

    import { Schema } from "@effect/schema"
    import { Either } from "effect"
    
    const schema = Schema.Struct({
      a: Schema.Struct({
        b: Schema.String,
        c: Schema.String
      }).annotations({
        title: "first error only",
        parseOptions: { errors: "first" } // Only the first error in this sub-schema is reported
      }),
      d: Schema.String
    }).annotations({
      title: "all errors",
      parseOptions: { errors: "all" } // All errors in the main schema are reported
    })
    
    const result = Schema.decodeUnknownEither(schema)(
      { a: {} },
      { errors: "first" }
    )
    if (Either.isLeft(result)) {
      console.log(result.left.message)
    }
    /*
    all errors
    ├─ ["d"]
    │  └─ is missing
    └─ ["a"]
       └─ first error only
          └─ ["b"]
             └─ is missing
    */
    

    Detailed Output Explanation:

    In this example:

    • The main schema is configured to display all errors. Hence, you will see errors related to both the d field (since it's missing) and any errors from the a subschema.
    • The subschema (a) is set to display only the first error. Although both b and c fields are missing, only the first missing field (b) is reported.

0.68.2

Patch Changes

  • #3024 eb341b3 Thanks @gcanti! - Replace Types.Simplify with a custom Simplify to restore nice types for pick and omit

0.68.1

Patch Changes

  • #3015 b51e266 Thanks @gcanti! - - Fix handling of exact option overrides in AST.ParseOptions This commit resolves a bug affecting the exact option within AST.ParseOptions. Previously, the implementation failed to correctly incorporate overrides for the exact setting, resulting in the parser not respecting the specified behavior in extended configurations.
    • Improve error messaging in Pretty.make for unmatched union schemas
  • Updated dependencies [6c89408]:
    • effect@3.3.5

0.68.0

Minor Changes

  • #2906 f6c7977 Thanks @gcanti! - ## Refactoring of the ParseIssue Model

    The ParseIssue model in the @effect/schema/ParseResult module has undergone a comprehensive redesign and simplification that enhances its expressiveness without compromising functionality. This section explores the motivation and details of this refactoring.

    Enhanced Schema.filter API

    The Schema.filter API has been improved to support more complex filtering that can involve multiple properties of a struct. This is especially useful for validations that compare two fields, such as ensuring that a password field matches a confirm_password field, a common requirement in form validations.

    Previous Limitations:

    Previously, while it was possible to implement a filter that compared two fields, there was no straightforward way to attach validation messages to a specific field. This posed challenges, especially in form validations where precise error reporting is crucial.

    Example of Previous Implementation:

    import { ArrayFormatter, Schema } from "@effect/schema"
    import { Either } from "effect"
    
    const Password = Schema.Trim.pipe(Schema.minLength(1))
    
    const MyForm = Schema.Struct({
      password: Password,
      confirm_password: Password
    }).pipe(
      Schema.filter((input) => {
        if (input.password !== input.confirm_password) {
          return "Passwords do not match"
        }
      })
    )
    
    console.log(
      "%o",
      Schema.decodeUnknownEither(MyForm)({
        password: "abc",
        confirm_password: "d"
      }).pipe(Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error)))
    )
    /*
    {
      _id: 'Either',
      _tag: 'Left',
      left: [
        {
          _tag: 'Type',
          path: [],
          message: 'Passwords do not match'
        }
      ]
    }
    */
    

    In this scenario, while the filter functionally works, the lack of a specific error path (path: []) means errors are not as descriptive or helpful as they could be.

    Specifying Error Paths

    With the new improvements, it's now possible to specify an error path along with the message, which enhances error specificity and is particularly beneficial for integration with tools like react-hook-form.

    Updated Implementation Example:

    import { ArrayFormatter, Schema } from "@effect/schema"
    import { Either } from "effect"
    
    const Password = Schema.Trim.pipe(Schema.minLength(1))
    
    const MyForm = Schema.Struct({
      password: Password,
      confirm_password: Password
    }).pipe(
      Schema.filter((input) => {
        if (input.password !== input.confirm_password) {
          return {
            path: ["confirm_password"],
            message: "Passwords do not match"
          }
        }
      })
    )
    
    console.log(
      "%o",
      Schema.decodeUnknownEither(MyForm)({
        password: "abc",
        confirm_password: "d"
      }).pipe(Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error)))
    )
    /*
    {
      _id: 'Either',
      _tag: 'Left',
      left: [
        {
          _tag: 'Type',
          path: [ 'confirm_password' ],
          message: 'Passwords do not match'
        }
      ]
    }
    */
    

    This modification allows the error to be directly associated with the confirm_password field, improving clarity for the end-user.

    Multiple Error Reporting

    The refactored API also supports reporting multiple issues at once, which is useful in forms where several validation checks might fail simultaneously.

    Example of Multiple Issues Reporting:

    import { ArrayFormatter, Schema } from "@effect/schema"
    import { Either } from "effect"
    
    const Password = Schema.Trim.pipe(Schema.minLength(1))
    const OptionalString = Schema.optional(Schema.String)
    
    const MyForm = Schema.Struct({
      password: Password,
      confirm_password: Password,
      name: OptionalString,
      surname: OptionalString
    }).pipe(
      Schema.filter((input) => {
        const issues: Array<Schema.FilterIssue> = []
        // passwords must match
        if (input.password !== input.confirm_password) {
          issues.push({
            path: ["confirm_password"],
            message: "Passwords do not match"
          })
        }
        // either name or surname must be present
        if (!input.name && !input.surname) {
          issues.push({
            path: ["surname"],
            message: "Surname must be present if name is not present"
          })
        }
        return issues
      })
    )
    
    console.log(
      "%o",
      Schema.decodeUnknownEither(MyForm)({
        password: "abc",
        confirm_password: "d"
      }).pipe(Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error)))
    )
    /*
    {
      _id: 'Either',
      _tag: 'Left',
      left: [
        {
          _tag: 'Type',
          path: [ 'confirm_password' ],
          message: 'Passwords do not match'
        },
        {
          _tag: 'Type',
          path: [ 'surname' ],
          message: 'Surname must be present if name is not present'
        }
      ]
    }
    */
    

    The new ParseIssue Model

    The ParseIssue type has undergone a significant restructuring to improve its expressiveness and simplicity. This new model categorizes issues into leaf and composite types, enhancing clarity and making error handling more systematic.

    Structure of ParseIsssue Type:

    export type ParseIssue =
      // leaf
      | Type
      | Missing
      | Unexpected
      | Forbidden
      // composite
      | Pointer
      | Refinement
      | Transformation
      | Composite
    

    Key Changes in the Model:

    1. New Members:

      • Composite: A new class that aggregates multiple ParseIssue instances.
      • Missing: Identifies when a required element or value is absent.
      • Unexpected: Flags unexpected elements or values in the input.
      • Pointer: Points to the part of the data structure where an issue occurs.
    2. Removed Members:

      • Previous categories like Declaration, TupleType, TypeLiteral, Union, Member, Key, and Index have been consolidated under the Composite type for a more streamlined approach.

    Definition of Composite:

    interface Composite {
      readonly _tag: "Composite"
      readonly ast: AST.Annotated
      readonly actual: unknown
      readonly issues: ParseIssue | NonEmptyReadonlyArray<ParseIssue>
      readonly output?: unknown
    }
    

    Refined Error Messaging System

    We've updated our internal function getErrorMessage to enhance how error messages are formatted throughout our application. This function constructs an error message that includes the reason for the error, additional details, the path to where the error occurred, and the schema's AST representation if available.

    Example

    import { JSONSchema, Schema } from "@effect/schema"
    
    JSONSchema.make(Schema.Struct({ a: Schema.Void }))
    /*
    throws:
    Error: Missing annotation
    at path: ["a"]
    details: Generating a JSON Schema for this schema requires a "jsonSchema" annotation
    schema (VoidKeyword): void
    */
    

    Enhancing Tuples with Element Annotations

    Annotations are used to add metadata to tuple elements, which can describe the purpose or requirements of each element more clearly. This can be particularly useful when generating documentation or JSON schemas from your schemas.

    import { JSONSchema, Schema } from "@effect/schema"
    
    // Defining a tuple with annotations for each coordinate in a point
    const Point = Schema.Tuple(
      Schema.element(Schema.Number).annotations({
        title: "X",
        description: "X coordinate"
      }),
      Schema.optionalElement(Schema.Number).annotations({
        title: "Y",
        description: "optional Y coordinate"
      })
    )
    
    // Generating a JSON Schema from the tuple
    console.log(JSONSchema.make(Point))
    /*
    Output:
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      type: 'array',
      minItems: 1,
      items: [
        { type: 'number', description: 'X coordinate', title: 'X' },
        {
          type: 'number',
          description: 'optional Y coordinate',
          title: 'Y'
        }
      ],
      additionalItems: false
    }
    */
    

    Missing messages

    You can provide custom messages for missing fields or elements using the new missingMessage annotation.

    Example (missing field)

    import { Schema } from "@effect/schema"
    
    const Person = Schema.Struct({
      name: Schema.propertySignature(Schema.String).annotations({
        missingMessage: () => "Name is required"
      })
    })
    
    Schema.decodeUnknownSync(Person)({})
    /*
    Output:
    Error: { readonly name: string }
    └─ ["name"]
       └─ Name is required
    */
    

    Example (missing element)

    import { Schema } from "@effect/schema"
    
    const Point = Schema.Tuple(
      Schema.element(Schema.Number).annotations({
        missingMessage: () => "X coordinate is required"
      }),
      Schema.element(Schema.Number).annotations({
        missingMessage: () => "Y coordinate is required"
      })
    )
    
    Schema.decodeUnknownSync(Point)([], { errors: "all" })
    /*
    Output:
    Error: readonly [number, number]
    ├─ [0]
    │  └─ X coordinate is required
    └─ [1]
       └─ Y coordinate is required
    */
    

    Streamlining Annotations

    The individual APIs that were previously used to add annotations to schemas have been removed. This change was made because these individual annotation APIs did not provide significant value and were burdensome to maintain. Instead, you can now use the annotations method directly or the Schema.annotations API for a pipe-able approach.

    Before

    import { Schema } from "@effect/schema"
    
    // Example of adding an identifier using a dedicated API
    const schema = Schema.String.pipe(Schema.identifier("myIdentitifer"))
    

    Now

    import { Schema } from "@effect/schema"
    
    // Directly using the annotations method
    const schema = Schema.String.annotations({ identifier: "myIdentitifer" })
    // or
    const schema2 = Schema.String.pipe(
      // Using the annotations function in a pipe-able format
      Schema.annotations({ identifier: "myIdentitifer" })
    )
    

    Standardize Error Handling for *Either, *Sync and asserts APIs

    Now the *Sync and asserts APIs throw a ParseError while before they was throwing a simple Error with a cause containing a ParseIssue

    import { ParseResult, Schema } from "@effect/schema"
    
    try {
      Schema.decodeUnknownSync(Schema.String)(null)
    } catch (e) {
      console.log(ParseResult.isParseError(e)) // true
    }
    
    const asserts: (u: unknown) => asserts u is string = Schema.asserts(
      Schema.String
    )
    try {
      asserts(null)
    } catch (e) {
      console.log(ParseResult.isParseError(e)) // true
    }
    

    List of Changes

    AST

    • add MissingMessageAnnotation annotations
    • add Type
    • remove verbose option from toString() methods

    Breaking

    • rename Element to OptionalType and add an annotations field
    • change TupleType definition: from rest: ReadonlyArray<AST> to rest: ReadonlyArray<Type>
    • remove TemplateLiteral.make

    Schema

    • add missingMessage annotation to PropertySignature
    • add FilterIssue helper interface

    Breaking

    • remove TupleType.Element type
    • replace OptionalElement API interface with Element API interface
    • remove PropertySignature.GetToken
    • remove duplicated annotation APIs
      • message
      • identifier
      • title
      • description
      • examples
      • default
      • documentation
      • jsonSchema
      • equivalence
      • concurrency
      • concurrency
      • parseIssueTitle
    • remove Secret and SecretFromSelf

    ParseResult

    • add isParseError type guard

    Breaking

    • ParseIssue refactoring
      • make Missing and Unexpected parse issues
      • replace Declaration with Composite
      • remove Union in favour of Composite
      • remove TypeLiteral in favour of Composite
      • remove TupleType in favour of Composite
      • remove Member class
      • merge Key and Index into Pointer
      • Type
        • change message field from Option<string> to string | undefined
      • Refinement
        • rename error field to issue
      • Transformation
        • rename error field to issue
      • Missing
        • add ast: AST.Type field
        • add message field
        • add actual field
      • Unexpected
        • replace ast field with a message field
        • add actual field
    • ParseError
      • rename error property to issue
    • remove missing export
    • Standardize Error Handling for *Either, *Sync and asserts APIs, closes #2968

Patch Changes

  • Updated dependencies [a67b8fe]:
    • effect@3.3.4

0.67.24

Patch Changes

  • #2997 3b15e1b Thanks @gcanti! - Improve error handling (type-level) for improper usage of optional, closes #2995

    This commit addresses concerns raised by users about the confusing behavior when 'optional' is misused in a schema definition. Previously, users experienced unexpected results, such as a schema returning 'Schema.All' when 'optional' was used incorrectly, without clear guidance on the correct usage or error messages.

    Changes:

    • Enhanced the 'optional' method to return a descriptive type-level error when used incorrectly, helping users identify and correct their schema definitions.
    • Updated the Schema.optional() implementation to check its context within a pipeline and ensure it is being used correctly.
    • Added unit tests to verify that the new error handling works as expected and to ensure that correct usage does not affect existing functionality.
  • #2994 3a750b2 Thanks @gcanti! - Expose exact option for strict decoding on missing properties, closes #2993

    This commit addresses an issue where users encountered unexpected decoding behaviors, specifically regarding how undefined values and missing properties are handled. The default behavior of the @effect/schema library treats missing properties as undefined during decoding, which can lead to confusion when stricter validation is expected.

    Changes:

    • Exposed an internal configuration option exțact (default: false), which when set to true, enforces strict decoding that will error on missing properties instead of treating them as undefined.
    • Updated documentation to clearly outline the default and strict decoding behaviors, providing users with guidance on how to enable strict validation.
  • Updated dependencies [06ede85, 7204ca5]:

    • effect@3.3.3

0.67.23

Patch Changes

  • #2991 2ee4f2b Thanks @gcanti! - Remove Simplify from extend, pick, omit, pluck APIs, closes #2989, #2990

  • #2971 9b3b4ac Thanks @gcanti! - Add Schema.NonEmptyChunkFromSelf and Schema.NonEmptyChunk, closes #2961

  • Updated dependencies [3572646, 1aed347, df4bf4b, f085f92]:

    • effect@3.3.2

0.67.22

Patch Changes

  • #2955 d79ca17 Thanks @gcanti! - The minItems filter now checks for an invalid argument (n < 1) and, when valid, refines the type to NonEmptyReadonlyArray<A>.

  • Updated dependencies [eb98c5b, 184fed8, 6068e07, 3a77e20]:

    • effect@3.3.1

0.67.21

Patch Changes

0.67.20

Patch Changes

  • #2926 4c6bc7f Thanks @gcanti! - Add propertyOrder option to ParseOptions to control the order of keys in the output, closes #2925.

    The propertyOrder option provides control over the order of object fields in the output. This feature is particularly useful when the sequence of keys is important for the consuming processes or when maintaining the input order enhances readability and usability.

    By default, the propertyOrder option is set to "none". This means that the internal system decides the order of keys to optimize parsing speed. The order of keys in this mode should not be considered stable, and it's recommended not to rely on key ordering as it may change in future updates without notice.

    Setting propertyOrder to "input" ensures that the keys are ordered as they appear in the input during the decoding/encoding process.

    Example (Synchronous Decoding)

    import { Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      a: Schema.Number,
      b: Schema.Literal("b"),
      c: Schema.Number
    })
    
    // Decoding an object synchronously without specifying the property order
    console.log(Schema.decodeUnknownSync(schema)({ b: "b", c: 2, a: 1 }))
    // Output decided internally: { b: 'b', a: 1, c: 2 }
    
    // Decoding an object synchronously while preserving the order of properties as in the input
    console.log(
      Schema.decodeUnknownSync(schema)(
        { b: "b", c: 2, a: 1 },
        { propertyOrder: "original" }
      )
    )
    // Output preserving input order: { b: 'b', c: 2, a: 1 }
    

    Example (Asynchronous Decoding)

    import { ParseResult, Schema } from "@effect/schema"
    import type { Duration } from "effect"
    import { Effect } from "effect"
    
    // Function to simulate an asynchronous process within the schema
    const effectify = (duration: Duration.DurationInput) =>
      Schema.Number.pipe(
        Schema.transformOrFail(Schema.Number, {
          decode: (x) =>
            Effect.sleep(duration).pipe(Effect.andThen(ParseResult.succeed(x))),
          encode: ParseResult.succeed
        })
      )
    
    // Define a structure with asynchronous behavior in each field
    const schema = Schema.Struct({
      a: effectify("200 millis"),
      b: effectify("300 millis"),
      c: effectify("100 millis")
    }).annotations({ concurrency: 3 })
    
    // Decoding data asynchronously without preserving order
    Schema.decode(schema)({ a: 1, b: 2, c: 3 })
      .pipe(Effect.runPromise)
      .then(console.log)
    // Output decided internally: { c: 3, a: 1, b: 2 }
    
    // Decoding data asynchronously while preserving the original input order
    Schema.decode(schema)({ a: 1, b: 2, c: 3 }, { propertyOrder: "original" })
      .pipe(Effect.runPromise)
      .then(console.log)
    // Output preserving input order: { a: 1, b: 2, c: 3 }
    

0.67.19

Patch Changes

  • #2916 cd7496b Thanks @gcanti! - Add support for AST.Literal in Schema.TemplateLiteral, closes #2913

  • #2915 349a036 Thanks @gcanti! - Align constructors arguments:

    • Refactor Class interface to accept options for disabling validation
    • Refactor TypeLiteral interface to accept options for disabling validation
    • Refactor refine interface to accept options for disabling validation
    • Refactor BrandSchema interface to accept options for disabling validation

    Example

    import { Schema } from "@effect/schema"
    
    const BrandedNumberSchema = Schema.Number.pipe(
      Schema.between(1, 10),
      Schema.brand("MyNumber")
    )
    
    BrandedNumberSchema.make(20, { disableValidation: true }) // Bypasses validation and creates the instance without errors
    
  • Updated dependencies [8c5d280, 6ba6d26, 3f28bf2, 5817820]:

    • effect@3.2.9

0.67.18

Patch Changes

  • #2908 a0dd1c1 Thanks @gcanti! - TemplateLiteral: fix bug related to ${number} span, closes #2907

0.67.17

Patch Changes

  • #2892 d9d22e7 Thanks @gcanti! - Schema

    • add propertySignature API interface (with a from property)
    • extend optional API interface with a from property
    • extend optionalWithOptions API interface with a from property
  • #2901 3c080f7 Thanks @gcanti! - make the AST.TemplateLiteral constructor public

  • #2901 3c080f7 Thanks @gcanti! - add support for string literals to Schema.TemplateLiteral and TemplateLiteral API interface.

    Before

    import { Schema } from "@effect/schema"
    
    // `https://${string}.com` | `https://${string}.net`
    const MyUrl = Schema.TemplateLiteral(
      Schema.Literal("https://"),
      Schema.String,
      Schema.Literal("."),
      Schema.Literal("com", "net")
    )
    

    Now

    import { Schema } from "@effect/schema"
    
    // `https://${string}.com` | `https://${string}.net`
    const MyUrl = Schema.TemplateLiteral(
      "https://",
      Schema.String,
      ".",
      Schema.Literal("com", "net")
    )
    
  • #2905 7d6d875 Thanks @gcanti! - add support for unions to rename, closes #2904

  • #2897 70cda70 Thanks @gcanti! - Add encodedBoundSchema API.

    The encodedBoundSchema function is similar to encodedSchema but preserves the refinements up to the first transformation point in the original schema.

    Function Signature:

    export const encodedBoundSchema = <A, I, R>(schema: Schema<A, I, R>): Schema<I>
    

    The term "bound" in this context refers to the boundary up to which refinements are preserved when extracting the encoded form of a schema. It essentially marks the limit to which initial validations and structure are maintained before any transformations are applied.

    Example Usage:

    import { Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      foo: Schema.String.pipe(Schema.minLength(3), Schema.compose(Schema.Trim))
    })
    
    // The resultingEncodedBoundSchema preserves the minLength(3) refinement,
    // ensuring the string length condition is enforced but omits the Trim transformation.
    const resultingEncodedBoundSchema = Schema.encodedBoundSchema(schema)
    
    // resultingEncodedBoundSchema is the same as:
    Schema.Struct({
      foo: Schema.String.pipe(Schema.minLength(3))
    })
    

    In the provided example:

    • Initial Schema: The schema for foo includes a refinement to ensure strings have a minimum length of three characters and a transformation to trim the string.
    • Resulting Schema: resultingEncodedBoundSchema maintains the minLength(3) condition, ensuring that this validation persists. However, it excludes the trimming transformation, focusing solely on the length requirement without altering the string's formatting.
  • Updated dependencies [fb91f17]:

    • effect@3.2.8

0.67.16

Patch Changes

  • #2890 5745886 Thanks @gcanti! - Fix constructor type inference for classes with all optional fields, closes #2888

    This fix addresses an issue where TypeScript incorrectly inferred the constructor parameter type as an empty object {} when all class fields were optional. Now, the constructor properly recognizes arguments as objects with optional fields (e.g., { abc?: number, xyz?: number }).

  • Updated dependencies [6801fca]:

    • effect@3.2.7

0.67.15

Patch Changes

  • #2882 e2740fc Thanks @gcanti! - add requiredToOptional function to Schema module, closes #2881

  • #2880 60fe3d5 Thanks @gcanti! - add missing makePropertySignature constructor

  • Updated dependencies [cc8ac50]:

    • effect@3.2.6

0.67.14

Patch Changes

  • #2851 c5846e9 Thanks @gcanti! - Add tag and TaggedStruct constructors.

    In TypeScript tags help to enhance type discrimination and pattern matching by providing a simple yet powerful way to define and recognize different data types.

    What is a Tag?

    A tag is a literal value added to data structures, commonly used in structs, to distinguish between various object types or variants within tagged unions. This literal acts as a discriminator, making it easier to handle and process different types of data correctly and efficiently.

    Using the tag Constructor

    The tag constructor is specifically designed to create a property signature that holds a specific literal value, serving as the discriminator for object types. Here's how you can define a schema with a tag:

    import { Schema } from "@effect/schema"
    
    const User = Schema.Struct({
      _tag: Schema.tag("User"),
      name: Schema.String,
      age: Schema.Number
    })
    
    assert.deepStrictEqual(User.make({ name: "John", age: 44 }), {
      _tag: "User",
      name: "John",
      age: 44
    })
    

    In the example above, Schema.tag("User") attaches a _tag property to the User struct schema, effectively labeling objects of this struct type as "User". This label is automatically applied when using the make method to create new instances, simplifying object creation and ensuring consistent tagging.

    Simplifying Tagged Structs with TaggedStruct

    The TaggedStruct constructor streamlines the process of creating tagged structs by directly integrating the tag into the struct definition. This method provides a clearer and more declarative approach to building data structures with embedded discriminators.

    import { Schema } from "@effect/schema"
    
    const User = Schema.TaggedStruct("User", {
      name: Schema.String,
      age: Schema.Number
    })
    
    // `_tag` is optional
    const userInstance = User.make({ name: "John", age: 44 })
    
    assert.deepStrictEqual(userInstance, {
      _tag: "User",
      name: "John",
      age: 44
    })
    

    Multiple Tags

    While a primary tag is often sufficient, TypeScript allows you to define multiple tags for more complex data structuring needs. Here's an example demonstrating the use of multiple tags within a single struct:

    import { Schema } from "@effect/schema"
    
    const Product = Schema.TaggedStruct("Product", {
      category: Schema.tag("Electronics"),
      name: Schema.String,
      price: Schema.Number
    })
    
    // `_tag` and `category` are optional
    const productInstance = Product.make({ name: "Smartphone", price: 999 })
    
    assert.deepStrictEqual(productInstance, {
      _tag: "Product",
      category: "Electronics",
      name: "Smartphone",
      price: 999
    })
    

    This example showcases a product schema that not only categorizes each product under a general tag ("Product") but also specifies a category tag ("Electronics"), enhancing the clarity and specificity of the data model.

0.67.13

Patch Changes

0.67.12

Patch Changes

  • #2814 f8038ca Thanks @gcanti! - Add support for Enums in Record, closes #2811

  • #2816 e376641 Thanks @gcanti! - Add support for Config module, closes #2346

  • Updated dependencies [1af94df, e313a01]:

    • effect@3.2.4

0.67.11

Patch Changes

  • #2803 5af633e Thanks @tim-smart! - update dependencies

  • Updated dependencies [45578e8]:

    • effect@3.2.3

0.67.10

Patch Changes

0.67.9

Patch Changes

0.67.8

Patch Changes

  • Updated dependencies [c1e991d]:
    • effect@3.2.1

0.67.7

Patch Changes

0.67.6

Patch Changes

0.67.5

Patch Changes

0.67.4

Patch Changes

  • #2756 ee08593 Thanks @gcanti! - Improving Predicate Usability of Schema.is

    Before this update, the Schema.is(mySchema) function couldn't be easily used as a predicate or refinement in common array methods like filter or find. This was because the function's signature was:

    (value: unknown, overrideOptions?: AST.ParseOptions) => value is A
    

    Meanwhile, the function expected by methods like filter has the following signature:

    (value: unknown, index: number) => value is A
    

    To make Schema.is compatible with these array methods, we've adjusted the function's signature to accept number as a possible value for the second parameter, in which case it is ignored:

    -(value: unknown, overrideOptions?: AST.ParseOptions) => value is A
    +(value: unknown, overrideOptions?: AST.ParseOptions | number) => value is A
    

    Here's a practical example comparing the behavior before and after the change:

    Before:

    import { Schema } from "@effect/schema"
    
    declare const array: Array<string | number>
    
    /*
    Throws an error:
    No overload matches this call.
    ...
    Types of parameters 'overrideOptions' and 'index' are incompatible.
    */
    const strings = array.filter(Schema.is(Schema.String))
    

    Now:

    import { Schema } from "@effect/schema"
    
    declare const array: Array<string | number>
    
    // const strings: string[]
    const strings = array.filter(Schema.is(Schema.String))
    

    Note that the result has been correctly narrowed to string[].

  • #2746 da6d7d8 Thanks @gcanti! - pick: do not return a ComposeTransformation if none of the picked keys are related to a property signature transformation, closes #2743

0.67.3

Patch Changes

  • Updated dependencies [6ac4847]:
    • effect@3.1.5

0.67.2

Patch Changes

  • #2738 89a3afb Thanks @gcanti! - add cause in errors thrown by asserts, closes #2729

  • #2741 992c8e2 Thanks @gcanti! - Schema.optional: the default option now allows setting a default value for both the decoding phase and the default constructor. Previously, it only set the decoding default. Closes #2740.

    Example

    import { Schema } from "@effect/schema"
    
    const Product = Schema.Struct({
      name: Schema.String,
      price: Schema.NumberFromString,
      quantity: Schema.optional(Schema.NumberFromString, { default: () => 1 })
    })
    
    // Applying defaults in the decoding phase
    console.log(
      Schema.decodeUnknownSync(Product)({ name: "Laptop", price: "999" })
    ) // { name: 'Laptop', price: 999, quantity: 1 }
    console.log(
      Schema.decodeUnknownSync(Product)({
        name: "Laptop",
        price: "999",
        quantity: "2"
      })
    ) // { name: 'Laptop', price: 999, quantity: 2 }
    
    // Applying defaults in the constructor
    console.log(Product.make({ name: "Laptop", price: 999 })) // { name: 'Laptop', price: 999, quantity: 1 }
    console.log(Product.make({ name: "Laptop", price: 999, quantity: 2 })) // { name: 'Laptop', price: 999, quantity: 2 }
    

0.67.1

Patch Changes

  • Updated dependencies [e41e911]:
    • effect@3.1.4

0.67.0

Minor Changes

  • #2634 d7e4997 Thanks @gcanti! - ## Simplifying Type Extraction

    When we work with schemas, it's common to need to extract their types automatically. To make this easier, we've made some changes to the Schema interface. Now, you can easily access Type and Encoded directly from a schema without the need for Schema.Schema.Type and Schema.Schema.Encoded.

    import { Schema } from "@effect/schema"
    
    const PersonSchema = Schema.Struct({
      name: Schema.String,
      age: Schema.NumberFromString
    })
    
    // same as type PersonType = Schema.Schema.Type<typeof PersonSchema>
    type PersonType = typeof PersonSchema.Type
    
    // same as Schema.Schema.Encoded<typeof PersonSchema>
    type PersonEncoded = typeof PersonSchema.Encoded
    

    Default Constructors

    When dealing with data, creating values that match a specific schema is crucial. To simplify this process, we've introduced default constructors for various types of schemas: Structs, filters, and brands.

    Note

    Default constructors associated with a schema Schema<A, I, R> are specifically related to the A type, not the I type.

    Let's dive into each of them with some examples to understand better how they work.

    Example (Struct)

    import { Schema } from "@effect/schema"
    
    const MyStruct = Schema.Struct({
      name: Schema.NonEmpty
    })
    
    MyStruct.make({ name: "a" }) // ok
    MyStruct.make({ name: "" })
    /*
    throws
    Error: { name: NonEmpty }
    └─ ["name"]
       └─ NonEmpty
          └─ Predicate refinement failure
             └─ Expected NonEmpty (a non empty string), actual ""
    */
    

    Example (filter)

    import { Schema } from "@effect/schema"
    
    const MyNumber = Schema.Number.pipe(Schema.between(1, 10))
    
    // const n: number
    const n = MyNumber.make(5) // ok
    MyNumber.make(20)
    /*
    throws
    Error: a number between 1 and 10
    └─ Predicate refinement failure
      └─ Expected a number between 1 and 10, actual 20
    */
    

    Example (brand)

    import { Schema } from "@effect/schema"
    
    const MyBrand = Schema.Number.pipe(
      Schema.between(1, 10),
      Schema.brand("MyNumber")
    )
    
    // const n: number & Brand<"MyNumber">
    const n = MyBrand.make(5) // ok
    MyBrand.make(20)
    /*
    throws
    Error: a number between 1 and 10
    └─ Predicate refinement failure
      └─ Expected a number between 1 and 10, actual 20
    */
    

    When utilizing our default constructors, it's important to grasp the type of value they generate. In the MyBrand example, the return type of the constructor is number & Brand<"MyNumber">, indicating that the resulting value is a number with the added branding "MyNumber".

    This differs from the filter example where the return type is simply number. The branding offers additional insights about the type, facilitating the identification and manipulation of your data.

    Note that default constructors are "unsafe" in the sense that if the input does not conform to the schema, the constructor throws an error containing a description of what is wrong. This is because the goal of default constructors is to provide a quick way to create compliant values (for example, for writing tests or configurations, or in any situation where it is assumed that the input passed to the constructors is valid and the opposite situation is exceptional).

    To have a "safe" constructor, you can use Schema.validateEither:

    import { Schema } from "@effect/schema"
    
    const MyNumber = Schema.Number.pipe(Schema.between(1, 10))
    
    const ctor = Schema.validateEither(MyNumber)
    
    console.log(ctor(5))
    /*
    { _id: 'Either', _tag: 'Right', right: 5 }
    */
    
    console.log(ctor(20))
    /*
    {
      _id: 'Either',
      _tag: 'Left',
      left: {
        _id: 'ParseError',
        message: 'a number between 1 and 10\n' +
          '└─ Predicate refinement failure\n' +
          '   └─ Expected a number between 1 and 10, actual 20'
      }
    }
    */
    

    Default Constructor Values

    When constructing objects, it's common to want to assign default values to certain fields to simplify the creation of new instances. Our new Schema.withConstructorDefault combinator allows you to effortlessly manage the optionality of a field in your default constructor.

    Example

    import { Schema } from "@effect/schema"
    
    const PersonSchema = Schema.Struct({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0)
      )
    })
    
    // The age field is optional and defaults to 0
    console.log(PersonSchema.make({ name: "John" }))
    // => { age: 0, name: 'John' }
    

    Defaults are lazily evaluated, meaning that a new instance of the default is generated every time the constructor is called:

    import { Schema } from "@effect/schema"
    
    const PersonSchema = Schema.Struct({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0)
      ),
      timestamp: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => new Date().getTime())
      )
    })
    
    console.log(PersonSchema.make({ name: "name1" }))
    // => { age: 0, timestamp: 1714232909221, name: 'name1' }
    console.log(PersonSchema.make({ name: "name2" }))
    // => { age: 0, timestamp: 1714232909227, name: 'name2' }
    

    Note how the timestamp field varies.

    Defaults can also be applied using the Class API:

    import { Schema } from "@effect/schema"
    
    class Person extends Schema.Class<Person>("Person")({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0)
      ),
      timestamp: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => new Date().getTime())
      )
    }) {}
    
    console.log(new Person({ name: "name1" }))
    // => Person { age: 0, timestamp: 1714400867208, name: 'name1' }
    console.log(new Person({ name: "name2" }))
    // => Person { age: 0, timestamp: 1714400867215, name: 'name2' }
    

    Default values are also "portable", meaning that if you reuse the same property signature in another schema, the default is carried over:

    import { Schema } from "@effect/schema"
    
    const PersonSchema = Schema.Struct({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0)
      ),
      timestamp: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => new Date().getTime())
      )
    })
    
    const AnotherSchema = Schema.Struct({
      foo: Schema.String,
      age: PersonSchema.fields.age
    })
    
    console.log(AnotherSchema.make({ foo: "bar" })) // => { foo: 'bar', age: 0 }
    

    Defaults can also be applied using the Class API:

    import { Schema } from "@effect/schema"
    
    class Person extends Schema.Class<Person>("Person")({
      name: Schema.NonEmpty,
      age: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => 0)
      ),
      timestamp: Schema.Number.pipe(
        Schema.propertySignature,
        Schema.withConstructorDefault(() => new Date().getTime())
      )
    }) {}
    
    console.log(new Person({ name: "name1" })) // Person { age: 0, timestamp: 1714400867208, name: 'name1' }
    console.log(new Person({ name: "name2" })) // Person { age: 0, timestamp: 1714400867215, name: 'name2' }
    

    Default Decoding Values

    Our new Schema.withDecodingDefault combinator makes it easy to handle the optionality of a field during the decoding process.

    import { Schema } from "@effect/schema"
    
    const MySchema = Schema.Struct({
      a: Schema.optional(Schema.String).pipe(Schema.withDecodingDefault(() => ""))
    })
    
    console.log(Schema.decodeUnknownSync(MySchema)({}))
    // => { a: '' }
    console.log(Schema.decodeUnknownSync(MySchema)({ a: undefined }))
    // => { a: '' }
    console.log(Schema.decodeUnknownSync(MySchema)({ a: "a" }))
    // => { a: 'a' }
    

    If you want to set default values both for the decoding phase and for the default constructor, you can use Schema.withDefaults:

    import { Schema } from "@effect/schema"
    
    const MySchema = Schema.Struct({
      a: Schema.optional(Schema.String).pipe(
        Schema.withDefaults({
          decoding: () => "",
          constructor: () => "-"
        })
      )
    })
    
    console.log(Schema.decodeUnknownSync(MySchema)({}))
    // => { a: '' }
    console.log(Schema.decodeUnknownSync(MySchema)({ a: undefined }))
    // => { a: '' }
    console.log(Schema.decodeUnknownSync(MySchema)({ a: "a" }))
    // => { a: 'a' }
    
    console.log(MySchema.make({})) // => { a: '-' }
    console.log(MySchema.make({ a: "a" })) // => { a: 'a' }
    

    Refactoring of Custom Message System

    We've refactored the system that handles user-defined custom messages to make it more intuitive.

    Now, custom messages no longer have absolute precedence by default. Instead, it becomes an opt-in behavior by explicitly setting a new flag override with the value true. Let's see an example:

    Previous Approach

    import { Schema } from "@effect/schema"
    
    const MyString = Schema.String.pipe(
      Schema.minLength(1),
      Schema.maxLength(2)
    ).annotations({
      // This message always takes precedence
      // So, for any error, the same message will always be shown
      message: () => "my custom message"
    })
    
    const decode = Schema.decodeUnknownEither(MyString)
    
    console.log(decode(null)) // "my custom message"
    console.log(decode("")) // "my custom message"
    console.log(decode("abc")) // "my custom message"
    

    As you can see, no matter where the decoding error is raised, the same error message will always be presented because in the previous version, the custom message by default overrides those generated by previous filters.

    Now, let's see how the same schema works with the new system.

    Current Approach

    import { Schema } from "@effect/schema"
    
    const MyString = Schema.String.pipe(
      Schema.minLength(1),
      Schema.maxLength(2)
    ).annotations({
      // This message is shown only if the maxLength filter fails
      message: () => "my custom message"
    })
    
    const decode = Schema.decodeUnknownEither(MyString)
    
    console.log(decode(null)) // "Expected a string, actual null"
    console.log(decode("")) // `Expected a string at least 1 character(s) long, actual ""`
    console.log(decode("abc")) // "my custom message"
    

    To restore the old behavior (for example, to address the scenario where a user wants to define a single cumulative custom message describing the properties that a valid value must have and does not want to see default messages), you need to set the override flag to true:

    import { Schema } from "@effect/schema"
    
    const MyString = Schema.String.pipe(
      Schema.minLength(1),
      Schema.maxLength(2)
    ).annotations({
      // By setting the `override` flag to `true`
      // this message will always be shown for any error
      message: () => ({ message: "my custom message", override: true })
    })
    
    const decode = Schema.decodeUnknownEither(MyString)
    
    console.log(decode(null)) // "my custom message"
    console.log(decode("")) // "my custom message"
    console.log(decode("abc")) // "my custom message"
    

    The new system is particularly useful when the schema on which custom messages are defined is more complex than a scalar value (like string or number), for example, if it's a struct containing a field that is an array of structs. Let's see an example that illustrates how convenient it is to rely on default messages when the decoding error occurs in a nested structure:

    import { Schema } from "@effect/schema"
    import { pipe } from "effect"
    
    const schema = Schema.Struct({
      outcomes: pipe(
        Schema.Array(
          Schema.Struct({
            id: Schema.String,
            text: pipe(
              Schema.String,
              Schema.message(() => "error_invalid_outcome_type"),
              Schema.minLength(1, { message: () => "error_required_field" }),
              Schema.maxLength(50, { message: () => "error_max_length_field" })
            )
          })
        ),
        Schema.minItems(1, { message: () => "error_min_length_field" })
      )
    })
    
    Schema.decodeUnknownSync(schema, { errors: "all" })({
      outcomes: []
    })
    /*
    throws
    Error: { outcomes: an array of at least 1 items }
    └─ ["outcomes"]
       └─ error_min_length_field
    */
    
    Schema.decodeUnknownSync(schema, { errors: "all" })({
      outcomes: [
        { id: "1", text: "" },
        { id: "2", text: "this one is valid" },
        { id: "3", text: "1234567890".repeat(6) }
      ]
    })
    /*
    throws
    Error: { outcomes: an array of at least 1 items }
    └─ ["outcomes"]
       └─ an array of at least 1 items
          └─ From side refinement failure
             └─ ReadonlyArray<{ id: string; text: a string at most 50 character(s) long }>
                ├─ [0]
                │  └─ { id: string; text: a string at most 50 character(s) long }
                │     └─ ["text"]
                │        └─ error_required_field
                └─ [2]
                   └─ { id: string; text: a string at most 50 character(s) long }
                      └─ ["text"]
                         └─ error_max_length_field
    */
    

    In the previous version, we would have received the message "error_min_length_field" for any decoding error, which is evidently suboptimal and has now been corrected.

    Filter API Interface

    We've introduced a new API interface to the filter API. This allows you to access the refined schema using the exposed from field:

    import { Schema } from "@effect/schema"
    
    const MyFilter = Schema.Struct({
      a: Schema.String
    }).pipe(Schema.filter(() => /* some filter... */ true))
    
    // const aField: typeof Schema.String
    const aField = MyFilter.from.fields.a
    

    The signature of the filter function has been simplified and streamlined to be more ergonomic when setting a default message. In the new signature of filter, the type of the predicate passed as an argument is as follows:

    predicate: (a: A, options: ParseOptions, self: AST.Refinement) =>
      undefined | boolean | string | ParseResult.ParseIssue
    

    with the following semantics:

    • true means the filter is successful.
    • false or undefined means the filter fails and no default message is set.
    • string means the filter fails and the returned string is used as the default message.
    • ParseIssue means the filter fails and the returned ParseIssue is used as an error.

    Let's see an example of how it worked before and how it works now.

    Before

    import { Schema, ParseResult } from "@effect/schema"
    import { Option } from "effect"
    
    const Positive = Schema.Number.pipe(
      Schema.filter((n, _, ast) =>
        n > 0
          ? Option.none()
          : Option.some(new ParseResult.Type(ast, n, "must be positive"))
      )
    )
    
    Schema.decodeUnknownSync(Positive)(-1)
    /*
    throws
    Error: <refinement schema>
    └─ Predicate refinement failure
       └─ must be positive
    */
    

    Now

    import { Schema } from "@effect/schema"
    
    const Positive = Schema.Number.pipe(
      Schema.filter((n) => (n > 0 ? undefined : "must be positive"))
    )
    
    Schema.decodeUnknownSync(Positive)(-1)
    /*
    throws
    Error: { number | filter }
    └─ Predicate refinement failure
       └─ must be positive
    */
    

    JSON Schema Compiler Refactoring

    The JSON Schema compiler has been refactored to be more user-friendly. Now, the make API attempts to produce the optimal JSON Schema for the input part of the decoding phase. This means that starting from the most nested schema, it traverses the chain, including each refinement, and stops at the first transformation found.

    Let's see an example:

    import { JSONSchema, Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      foo: Schema.String.pipe(Schema.minLength(2)),
      bar: Schema.optional(Schema.NumberFromString, {
        default: () => 0
      })
    })
    
    console.log(JSON.stringify(JSONSchema.make(schema), null, 2))
    

    Now, let's compare the JSON Schemas produced in both the previous and new versions.

    Before

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "required": ["bar", "foo"],
      "properties": {
        "bar": {
          "type": "number",
          "description": "a number",
          "title": "number"
        },
        "foo": {
          "type": "string",
          "description": "a string at least 2 character(s) long",
          "title": "string",
          "minLength": 2
        }
      },
      "additionalProperties": false,
      "title": "Struct (Type side)"
    }
    

    As you can see, the JSON Schema produced has:

    • a required foo field, correctly modeled with a constraint ("minLength": 2)
    • a required numeric bar field

    This happens because in the previous version, the JSONSchema.make API by default produces a JSON Schema for the Type part of the schema. That is:

    type Type = Schema.Schema.Type<typeof schema>
    /*
    type Type = {
        readonly foo: string;
        readonly bar: number;
    }
    */
    

    However, typically, we are interested in generating a JSON Schema for the input part of the decoding process, i.e., in this case for:

    type Encoded = Schema.Schema.Encoded<typeof schema>
    /*
    type Encoded = {
        readonly foo: string;
        readonly bar?: string | undefined;
    }
    */
    

    At first glance, a possible solution might be to generate the JSON Schema of Schema.encodedSchema(schema):

    console.log(
      JSON.stringify(JSONSchema.make(Schema.encodedSchema(schema)), null, 2)
    )
    

    But here's what the result would be:

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "required": ["foo"],
      "properties": {
        "foo": {
          "type": "string",
          "description": "a string",
          "title": "string"
        },
        "bar": {
          "type": "string",
          "description": "a string",
          "title": "string"
        }
      },
      "additionalProperties": false
    }
    

    As you can see, we lost the "minLength": 2 constraint, which is the useful part of precisely defining our schemas using refinements.

    After

    Now, let's see what JSONSchema.make API produces by default for the same schema:

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "required": ["foo"],
      "properties": {
        "foo": {
          "type": "string",
          "description": "a string at least 2 character(s) long",
          "title": "string",
          "minLength": 2
        },
        "bar": {
          "type": "string",
          "description": "a string",
          "title": "string"
        }
      },
      "additionalProperties": false,
      "title": "Struct (Encoded side)"
    }
    

    As you can verify, the refinement has been preserved.

    Improve extend to support refinements and suspended schemas

    Now extend supports extending refinements, so you can do something like this:

    import { Schema } from "@effect/schema"
    
    const RefinedStruct = Schema.Struct({
      a: Schema.Number,
      b: Schema.Number
    }).pipe(
      Schema.filter((value) => {
        if (value.a !== value.b) {
          return "`a` must be equal to `b`"
        }
      })
    )
    
    const AnotherStruct = Schema.Struct({
      c: Schema.String,
      d: Schema.String
    })
    
    // in the previous version you would receive an error:
    // Extend: cannot extend `<refinement schema>` with `{ c: string; d: string }` (path [])
    const Extended = Schema.extend(RefinedStruct, AnotherStruct)
    
    console.log(String(Extended))
    
    console.log(
      Schema.decodeUnknownSync(Extended)({ a: 1, b: 1, c: "c", d: "d" })
    )
    // => { a: 1, b: 1, c: 'c', d: 'd' }
    console.log(
      Schema.decodeUnknownSync(Extended)({ a: 1, b: 2, c: "c", d: "d" })
    )
    /*
    throws
    Error: { { readonly a: number; readonly b: number; readonly c: string; readonly d: string } | filter }
    └─ Predicate refinement failure
       └─ `a` must be equal to `b`
    */
    

    We've also added support for Schema.suspend. Here's an example:

    import { Arbitrary, FastCheck, Schema } from "@effect/schema"
    
    // Define a recursive list type
    type List =
      | {
          readonly type: "nil"
        }
      | {
          readonly type: "cons"
          readonly tail: {
            readonly value: number
          } & List // extend
        }
    
    // Define a schema for the list type
    const List: Schema.Schema<List> = Schema.Union(
      Schema.Struct({ type: Schema.Literal("nil") }),
      Schema.Struct({
        type: Schema.Literal("cons"),
        tail: Schema.extend(
          Schema.Struct({ value: Schema.Number }),
          Schema.suspend(() => List) // extend
        )
      })
    )
    
    console.log(
      JSON.stringify(FastCheck.sample(Arbitrary.make(List), 5), null, 2)
    )
    /*
    [
      {
        "type": "cons",
        "tail": {
          "type": "cons",
          "value": 4.8301839079380824e+36,
          "tail": {
            "type": "cons",
            "value": 1.5771055128598197e-29,
            "tail": {
              "type": "nil",
              "value": -15237.7763671875
            }
          }
        }
      },
      {
        "type": "cons",
        "tail": {
          "type": "nil",
          "value": 5.808463088527973e-18
        }
      },
      {
        "type": "nil"
      },
      {
        "type": "nil"
      },
      {
        "type": "cons",
        "tail": {
          "type": "cons",
          "value": -0.7920627593994141,
          "tail": {
            "type": "nil",
            "value": 63.837738037109375
          }
        }
      }
    ]
    */
    

    Patches

    AST

    • fix AST.toString to honor readonly modifiers
    • improve AST.toString for refinements

    Schema

    • return BrandSchema from fromBrand
    • add SchemaClass interface
    • add AnnotableClass interface
    • extend: add support for refinements, closes #2642
    • add pattern json schema annotation to Trimmed
    • add parseNumber number transformation
    • add TaggedClass api interface (exposing a _tag field)
    • add TaggedErrorClass api interface (exposing a _tag field)
    • add TaggedRequestClass api interface (exposing a _tag field)
    • add DateFromNumber schema
    • add Schema.Schema.AsSchema type-level helper to facilitate working with generic schemas.

    Other Breaking Changes

    • move fast-check from peerDependencies to dependencies

    AST

    • add path argument to Compiler API

      -export type Compiler<A> = (ast: AST) => A
      +export type Compiler<A> = (ast: AST, path: ReadonlyArray<PropertyKey>) => A
      
    • remove hash function, you can replace it with the following code:

      import { Hash } from "effect"
      import { AST } from "@effect/schema"
      
      export const hash = (ast: AST.AST): number =>
        Hash.string(JSON.stringify(ast, null, 2))
      

    JSONSchema

    • extend all interfaces with JsonSchemaAnnotations

      export interface JsonSchemaAnnotations {
        title?: string
        description?: string
        default?: unknown
        examples?: Array<unknown>
      }
      

    Schema

    • replace numerous API interfaces with class-based schema definitions

    • rename $Array API interface to `Array# @effect/schema

    • rename $Record API interface to `Record# @effect/schema

    • rename $ReadonlyMap API interface to `ReadonlyMap# @effect/schema

    • rename $Map API interface to `Map# @effect/schema

    • rename $ReadonlySet API interface to `ReadonlySet# @effect/schema

    • rename $Set API interface to `Set# @effect/schema

    • remove asBrandSchema utility

    • change BrandSchema interface

    • remove hash function

      from

      export interface BrandSchema<A extends brand_.Brand<any>, I>
        extends Annotable<BrandSchema<A, I>, A, I>,
          Brand.Constructor<A> {}
      

      to

      export interface BrandSchema<A extends Brand<any>, I, R>
        extends AnnotableClass<BrandSchema<A, I, R>, A, I, R> {
        make(a: Brand.Unbranded<A>): A
      }
      

      Previously, you could directly use the Brand.Constructor, but now you need to use its make constructor:

      Before

      import { Schema } from "@effect/schema"
      
      const UserId = Schema.Number.pipe(Schema.brand("UserId"))
      
      console.log(UserId(1)) // 1
      

      Now

      import { Schema } from "@effect/schema"
      
      const UserId = Schema.Number.pipe(Schema.brand("UserId"))
      
      console.log(UserId.make(1)) // 1
      

0.66.16

Patch Changes

  • Updated dependencies [1f6dc96]:
    • effect@3.1.3

0.66.15

Patch Changes

  • #2710 121d6d9 Thanks @gcanti! - Class API: avoid access before initialization when creating a class with suspended props, closes #2709

0.66.14

Patch Changes

0.66.13

Patch Changes

  • Updated dependencies [e5e56d1]:
    • effect@3.1.1

0.66.12

Patch Changes

0.66.11

Patch Changes

0.66.10

Patch Changes

  • Updated dependencies [18de56b]:
    • effect@3.0.7

0.66.9

Patch Changes

  • #2626 027418e Thanks @fubhy! - Reintroduce custom NoInfer type

  • #2631 8206529 Thanks @gcanti! - add support for data-last subtype overloads in compose

    Before

    import { Schema as S } from "@effect/schema"
    
    S.Union(S.Null, S.String).pipe(S.compose(S.NumberFromString)) // ts error
    S.NumberFromString.pipe(S.compose(S.Union(S.Null, S.Number))) // ts error
    

    Now

    import { Schema as S } from "@effect/schema"
    
    // $ExpectType Schema<number, string | null, never>
    S.Union(S.Null, S.String).pipe(S.compose(S.NumberFromString)) // ok
    // $ExpectType Schema<number | null, string, never>
    S.NumberFromString.pipe(S.compose(S.Union(S.Null, S.Number))) // ok
    
  • Updated dependencies [ffe4f4e, 027418e, ac1898e, ffe4f4e]:

    • effect@3.0.6

0.66.8

Patch Changes

0.66.7

Patch Changes

  • #2595 dd41c6c Thanks @gcanti! - Remove excessive constraint from the pipeable overload of attachPropertySignature, closes #2593

  • Updated dependencies [9a24667]:

    • effect@3.0.4

0.66.6

Patch Changes

  • #2586 9dfc156 Thanks @gcanti! - remove non-tree-shakable compiler dependencies from the Schema module:

    • remove dependency from Arbitrary compiler
    • remove dependency from Equivalence compiler
    • remove dependency from Pretty compiler
  • #2583 80271bd Thanks @suddenlyGiovanni! - - Fixed a typo in the JSDoc comment of the BooleanFromUnknown boolean constructors in Schema.ts

    • Fixed a typo in the JSDoc comment of the split string transformations combinator in Schema.ts
  • #2585 e4ba97d Thanks @gcanti! - JSONSchema: rearrange handling of surrogate annotations to occur after JSON schema annotations

0.66.5

Patch Changes

  • #2582 b3fe829 Thanks @gcanti! - Add default title annotations to both sides of Struct transformations.

    This simple addition helps make error messages shorter and more understandable.

    Before

    import { Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      a: Schema.optional(Schema.String, { exact: true, default: () => "" }),
      b: Schema.String,
      c: Schema.String,
      d: Schema.String,
      e: Schema.String,
      f: Schema.String
    })
    
    Schema.decodeUnknownSync(schema)({ a: 1 })
    /*
    throws
    Error: ({ a?: string; b: string; c: string; d: string; e: string; f: string } <-> { a: string; b: string; c: string; d: string; e: string; f: string })
    └─ Encoded side transformation failure
       └─ { a?: string; b: string; c: string; d: string; e: string; f: string }
          └─ ["a"]
             └─ Expected a string, actual 1
    */
    

    Now

    import { Schema } from "@effect/schema"
    
    const schema = Schema.Struct({
      a: Schema.optional(Schema.String, { exact: true, default: () => "" }),
      b: Schema.String,
      c: Schema.String,
      d: Schema.String,
      e: Schema.String,
      f: Schema.String
    })
    
    Schema.decodeUnknownSync(schema)({ a: 1 })
    /*
    throws
    Error: (Struct (Encoded side) <-> Struct (Type side))
    └─ Encoded side transformation failure
       └─ Struct (Encoded side)
          └─ ["a"]
             └─ Expected a string, actual 1
    */
    
  • #2581 a58b7de Thanks @gcanti! - Fix formatting for Class and brands AST.

  • #2579 d90e8c3 Thanks @gcanti! - Schema: JSONSchema should support make(Class)

    Before

    import { JSONSchema, Schema } from "@effect/schema"
    
    class A extends Schema.Class<A>("A")({
      a: Schema.String
    }) {}
    
    console.log(JSONSchema.make(A)) // throws MissingAnnotation: cannot build a JSON Schema for a declaration without a JSON Schema annotation
    

    Now

    console.log(JSONSchema.make(A))
    /*
    Output:
    {
      '$schema': 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      required: [ 'a' ],
      properties: { a: { type: 'string', description: 'a string', title: 'string' } },
      additionalProperties: false
    }
    */
    

0.66.4

Patch Changes

  • #2577 773b8e0 Thanks @gcanti! - partial / required: add support for renaming property keys in property signature transformations

    Before

    import { Schema } from "@effect/schema"
    
    const TestType = Schema.Struct({
      a: Schema.String,
      b: Schema.propertySignature(Schema.String).pipe(Schema.fromKey("c"))
    })
    
    const PartialTestType = Schema.partial(TestType)
    // throws Error: Partial: cannot handle transformations
    

    Now

    import { Schema } from "@effect/schema"
    
    const TestType = Schema.Struct({
      a: Schema.String,
      b: Schema.propertySignature(Schema.String).pipe(Schema.fromKey("c"))
    })
    
    const PartialTestType = Schema.partial(TestType)
    
    console.log(Schema.decodeUnknownSync(PartialTestType)({ a: "a", c: "c" })) // { a: 'a', b: 'c' }
    console.log(Schema.decodeUnknownSync(PartialTestType)({ a: "a" })) // { a: 'a' }
    
    const RequiredTestType = Schema.required(PartialTestType)
    
    console.log(Schema.decodeUnknownSync(RequiredTestType)({ a: "a", c: "c" })) // { a: 'a', b: 'c' }
    console.log(Schema.decodeUnknownSync(RequiredTestType)({ a: "a" })) // { a: 'a', b: undefined }
    

0.66.3

Patch Changes

  • Updated dependencies [a7b4b84]:
    • effect@3.0.3

0.66.2

Patch Changes

0.66.1

Patch Changes

  • #2550 b2b5d66 Thanks @gcanti! - Fix transformOrFail and transformOrFailFrom signatures in the exported Class interface by adding the missing annotations optional argument

  • #2555 8edacca Thanks @tim-smart! - prevent use of Array as import name to solve bundler issues

  • Updated dependencies [3da0cfa, 570e8d8, 8edacca]:

    • effect@3.0.1

0.66.0

Minor Changes

Patch Changes

0.65.0

Minor Changes

For the updates mentioned below, we've released a codemod to simplify the migration process.

To run it, use the following command:

npx @effect/codemod schema-0.65 src/**/*

The codemod is designed to automate many of the changes needed. However, it might not catch everything, so please let us know if you run into any issues (https://github.com/Effect-TS/codemod/issues). Remember to commit your code changes before running the codemod, just in case you need to undo anything.

  • #2505 0aee906 Thanks @mikearnaldi! - Re-export FastCheck to simplify usage and to resolve long term issues with ESM/CJS

  • #2440 b3acf47 Thanks @gcanti! - ## AST module

    • rename isTransform to isTransformation

    ParseResult module

    • rename Tuple to TupleType

    TreeFormatter module

    • rename formatIssue to formatIssueSync (This change was made to maintain consistency in API naming across all decoding and encoding APIs.)
    • rename formatIssueEffect to formatIssue
    • rename formatError to formatErrorSync
    • rename formatErrorEffect to formatError

    ArrayFormatter module

    • rename formatIssue to formatIssueSync
    • rename formatIssueEffect to formatIssue
    • rename formatError to formatErrorSync
    • rename formatErrorEffect to formatError

    Schema module

    • consolidate transform and transformOrFail parameters into an options object, #2434
    • consolidate Class.transformOrFail and Class.transformOrFailFrom parameters into an options object
    • consolidate declare parameters into an options object
    • consolidate optionalToRequired parameters into an options object
    • consolidate optionalToOptional parameters into an options object
    • Removed negateBigDecimal function (This cleanup was prompted by the realization that numerous functions can be derived from transformations such as negation, Math.abs, increment, etc. However, including all of them in the library is not feasible. Therefore, negateBigDecimal was removed)

    Renaming

    • rename uniqueSymbolFromSelf to UniqueSymbolFromSelf
    • rename undefined to Undefined
    • rename void to Void
    • rename null to Null
    • rename never to Never
    • rename unknown to Unknown
    • rename any to Any
    • rename string to String
    • rename number to Number
    • rename boolean to Boolean
    • rename /bigint/ig to BigInt
    • rename symbolFromSelf to SymbolFromSelf
    • rename object to Object
    • rename union to Union
    • rename nullable to NullOr
    • rename orUndefined to UndefinedOr
    • rename nullish to NullishOr
    • rename tuple to Tuple
    • rename array to Array
    • rename nonEmptyArray to NonEmptyArray
    • rename struct to Struct
    • rename record to Record
    • rename symbol to Symbol
    • rename optionFromSelf to OptionFromSelf
    • rename option to Option
    • rename optionFromNullable to OptionFromNullOr
    • rename optionFromNullish to OptionFromNullishOr
    • rename optionFromOrUndefined to OptionFromUndefinedOr
    • rename eitherFromSelf to EitherFromSelf
    • rename either to Either
    • rename eitherFromUnion to EitherFromUnion
    • rename readonlyMapFromSelf to ReadonlyMapFromSelf
    • rename mapFromSelf to MapFromSelf
    • rename readonlyMap to ReadonlyMap
    • rename map to Map
    • rename readonlySetFromSelf to ReadonlySetFromSelf
    • rename setFromSelf to SetFromSelf
    • rename readonlySet to ReadonlySet
    • rename set to Set
    • rename chunkFromSelf to ChunkFromSelf
    • rename chunk to Chunk
    • rename dataFromSelf to DataFromSelf
    • rename data to Data
    • rename causeFromSelf to CauseFromSelf
    • rename causeDefectUnknown to CauseDefectUnknown
    • rename cause to Cause
    • rename exitFromSelf to ExitFromSelf
    • rename exit to Exit
    • rename hashSetFromSelf to HashSetFromSelf
    • rename hashSet to HashSet
    • rename hashMapFromSelf to HashMapFromSelf
    • rename hashMap to HashMap
    • rename listFromSelf to ListFromSelf
    • rename list to List
    • rename sortedSetFromSelf to SortedSetFromSelf
    • rename sortedSet to SortedSet
    • rename literal to Literal
    • rename enums to Enums
    • rename templateLiteral to TemplateLiteral
  • #2511 0d3231a Thanks @gcanti! - make AST.pick correctly handle key renames

  • #2508 c22b019 Thanks @mikearnaldi! - Rename Arbitrary.Arbitrary to Arbitrary.LazyArbitrary, rename Arbitrary.make to Arbitrary.makeLazy and introduce Arbitrary.make

    Before

    import { Arbitrary, Schema } from "@effect/schema"
    import * as fc from "fast-check"
    
    const Person = Schema.struct({
      name: Schema.string,
      age: Schema.string.pipe(
        Schema.compose(Schema.NumberFromString),
        Schema.int()
      )
    })
    
    const arb = Arbitrary.make(Person)(fc)
    
    console.log(fc.sample(arb, 2))
    

    Now

    import { Arbitrary, FastCheck, Schema } from "@effect/schema"
    
    const Person = Schema.Struct({
      name: Schema.String,
      age: Schema.String.pipe(
        Schema.compose(Schema.NumberFromString),
        Schema.int()
      )
    })
    
    const arb = Arbitrary.make(Person)
    
    console.log(FastCheck.sample(arb, 2))
    

Patch Changes

0.64.20

Patch Changes

  • #2483 42b3651 Thanks @gcanti! - Add ParseIssueTitle annotation, closes #2482

    When a decoding or encoding operation fails, it's useful to have additional details in the default error message returned by TreeFormatter to understand exactly which value caused the operation to fail. To achieve this, you can set an annotation that depends on the value undergoing the operation and can return an excerpt of it, making it easier to identify the problematic value. A common scenario is when the entity being validated has an id field. The ParseIssueTitle annotation facilitates this kind of analysis during error handling.

    The type of the annotation is:

    export type ParseIssueTitleAnnotation = (
      issue: ParseIssue
    ) => string | undefined
    

    If you set this annotation on a schema and the provided function returns a string, then that string is used as the title by TreeFormatter, unless a message annotation (which has the highest priority) has also been set. If the function returns undefined, then the default title used by TreeFormatter is determined with the following priorities:

    • identifier
    • title
    • description
    • ast.toString()

    Example

    import type { ParseIssue } from "@effect/schema/ParseResult"
    import * as S from "@effect/schema/Schema"
    
    const getOrderItemId = ({ actual }: ParseIssue) => {
      if (S.is(S.struct({ id: S.string }))(actual)) {
        return `OrderItem with id: ${actual.id}`
      }
    }
    
    const OrderItem = S.struct({
      id: S.string,
      name: S.string,
      price: S.number
    }).annotations({
      identifier: "OrderItem",
      parseIssueTitle: getOrderItemId
    })
    
    const getOrderId = ({ actual }: ParseIssue) => {
      if (S.is(S.struct({ id: S.number }))(actual)) {
        return `Order with id: ${actual.id}`
      }
    }
    
    const Order = S.struct({
      id: S.number,
      name: S.string,
      items: S.array(OrderItem)
    }).annotations({
      identifier: "Order",
      parseIssueTitle: getOrderId
    })
    
    const decode = S.decodeUnknownSync(Order, { errors: "all" })
    
    // No id available, so the `identifier` annotation is used as the title
    decode({})
    /*
    throws
    Error: Order
    ├─ ["id"]
    │  └─ is missing
    ├─ ["name"]
    │  └─ is missing
    └─ ["items"]
       └─ is missing
    */
    
    // An id is available, so the `parseIssueTitle` annotation is used as the title
    decode({ id: 1 })
    /*
    throws
    Error: Order with id: 1
    ├─ ["name"]
    │  └─ is missing
    └─ ["items"]
       └─ is missing
    */
    
    decode({ id: 1, items: [{ id: "22b", price: "100" }] })
    /*
    throws
    Error: Order with id: 1
    ├─ ["name"]
    │  └─ is missing
    └─ ["items"]
       └─ ReadonlyArray<OrderItem>
          └─ [0]
             └─ OrderItem with id: 22b
                ├─ ["name"]
                │  └─ is missing
                └─ ["price"]
                   └─ Expected a number, actual "100"
    */
    

    In the examples above, we can see how the parseIssueTitle annotation helps provide meaningful error messages when decoding fails.

0.64.19

Patch Changes

  • #2471 58f66fe Thanks @gcanti! - Class API: Added default title annotation to the encoded side.

    Before:

    import * as S from "@effect/schema/Schema"
    
    class MySchema extends S.Class<MySchema>("MySchema")({
      a: S.string,
      b: S.number
    }) {}
    
    S.decodeUnknownSync(MySchema)({}, { errors: "all" })
    /*
    Error: ({ a: string; b: number } <-> MySchema)
    └─ Encoded side transformation failure
       └─ { a: string; b: number }
          ├─ ["a"]
          │  └─ is missing
          └─ ["b"]
             └─ is missing
    */
    

    After:

    import * as S from "@effect/schema/Schema"
    
    class MySchema extends S.Class<MySchema>("MySchema")({
      a: S.string,
      b: S.number
    }) {}
    
    S.decodeUnknownSync(MySchema)({}, { errors: "all" })
    /*
    Error: (MySchema (Encoded side) <-> MySchema)
    └─ Encoded side transformation failure
       └─ MySchema (Encoded side)
          ├─ ["a"]
          │  └─ is missing
          └─ ["b"]
             └─ is missing
    */
    
  • #2465 3cad21d Thanks @gcanti! - length now allows expressing a range

    Example

    import * as S from "@effect/schema/Schema"
    
    const schema = S.string.pipe(
      S.length({ min: 2, max: 4 }, { identifier: "MyRange" })
    )
    
    S.decodeUnknownSync(schema)("")
    /*
    throws:
    Error: MyRange
    └─ Predicate refinement failure
       └─ Expected MyRange (a string at least 2 character(s) and at most 4 character(s) long), actual ""
    */
    
  • Updated dependencies [dadc690]:

    • effect@2.4.18

0.64.18

Patch Changes

0.64.17

Patch Changes

  • #2446 62a7f23 Thanks @gcanti! - ParseResult: Add output field to TupleType and TypeLiteral. While the operation may not be entirely successful, it still provides some useful output or information.

    Examples (Tuple)

    import * as S from "@effect/schema/Schema"
    import * as Either from "effect/Either"
    
    const schema = S.array(S.number)
    const result = S.decodeUnknownEither(schema)([1, "a", 2, "b"], {
      errors: "all"
    })
    if (Either.isLeft(result)) {
      const issue = result.left.error
      if (issue._tag === "TupleType") {
        console.log(issue.output) // [1, 2]
      }
    }
    

    Examples (TypeLiteral)

    import * as S from "@effect/schema/Schema"
    import * as Either from "effect/Either"
    
    const schema = S.record(S.string, S.number)
    const result = S.decodeUnknownEither(schema)(
      { a: 1, b: "b", c: 2, d: "d" },
      { errors: "all" }
    )
    if (Either.isLeft(result)) {
      const issue = result.left.error
      if (issue._tag === "TypeLiteral") {
        console.log(issue.output) // { a: 1, c: 2 }
      }
    }
    
  • #2453 7cc2b41 Thanks @jessekelly881! - added Schema.BooleanFromUnknown

  • #2456 8b46fde Thanks @gcanti! - add set, setFromSelf, map, mapFromSelf

  • Updated dependencies [5170ce7]:

    • effect@2.4.16

0.64.16

Patch Changes

  • #2428 a31917a Thanks @gcanti! - export null from the AST module

  • #2436 4cd2bed Thanks @patroza! - fix: Schema JSDOC and editor click-follow for fields on struct and class

  • #2442 6cc6267 Thanks @gcanti! - Enums are now exposed under an enums property of the schema, closes #2441:

    enum Fruits {
      Apple,
      Banana
    }
    
    // $ExpectType enums<typeof Fruits>
    S.enums(Fruits)
    
    // $ExpectType typeof Fruits
    S.enums(Fruits).enums
    
    // $ExpectType Fruits.Apple
    S.enums(Fruits).enums.Apple
    
    // $ExpectType Fruits.Banana
    S.enums(Fruits).enums.Banana
    

0.64.15

Patch Changes

0.64.14

Patch Changes

0.64.13

Patch Changes

0.64.12

Patch Changes

  • #2359 9392de6 Thanks @tim-smart! - preserve defect information in Cause.Die

  • #2385 3307729 Thanks @tim-smart! - align runtime tuple behaviour to ts 5.4:

    from

    // ts 5.3
    type A = readonly [string, ...number[], boolean]
    type B = Required<A> // readonly [string, ...(number | boolean)[], number | boolean]
    

    to

    // ts 5.4
    type A = readonly [string, ...number[], boolean]
    type B = Required<A> // readonly [string, ...number[], boolean]
    
  • #2359 9392de6 Thanks @tim-smart! - use provided message in Schema.TaggedError .toString

  • #2385 3307729 Thanks @tim-smart! - update typescript to 5.4

  • #2396 d17a427 Thanks @sukovanej! - Fix extend with nested union.

  • Updated dependencies [3307729]:

    • effect@2.4.12

0.64.11

Patch Changes

0.64.10

Patch Changes

0.64.9

Patch Changes

0.64.8

Patch Changes

0.64.7

Patch Changes

  • Updated dependencies [71fd528]:
    • effect@2.4.9

0.64.6

Patch Changes

  • #2347 595140a Thanks @gcanti! - add back BrandSchema and introduce asBrandSchema utility

  • #2353 5f5fcd9 Thanks @tim-smart! - make optional dual:

    import * as S from "@effect/schema/Schema"
    
    const schema = S.struct({
      a: S.string.pipe(S.optional())
    })
    
    // same as:
    const schema2 = S.struct({
      a: S.optional(S.string)
    })
    
  • #2356 7a45ad0 Thanks @gcanti! - make partial dual:

    import * as S from "@effect/schema/Schema"
    
    const schema = S.struct({ a: S.string }).pipe(S.partial())
    
    // same as:
    const schema2 = S.partial(S.struct({ a: S.string }))
    
  • #2339 5c3b1cc Thanks @gcanti! - use Simplify from effect/Types in TaggedClass, TaggedError and TaggedRequest to avoid errors in Schema.d.ts, closes #1841

  • #2343 6f7dfc9 Thanks @gcanti! - improve pick/omit and add support for Class

  • #2337 88b8583 Thanks @gcanti! - JSONSchema: allow overrides through annotations, closes #1823

  • #2348 cb20824 Thanks @gcanti! - feedback: expose Class API identifiers

  • #2350 a45a525 Thanks @gcanti! - refactor unions: remove sorting, flattening, and unification

  • Updated dependencies [bb0b69e, 6b20bad, 4e64e9b, 3851a02, 5f5fcd9, 814e5b8]:

    • effect@2.4.8

0.64.5

Patch Changes

  • #2332 d0f56c6 Thanks @gcanti! - add missing Date api interfaces:

    • DateFromSelf
    • ValidDateFromSelf
    • DateFromString
    • $Date

0.64.4

Patch Changes

  • Updated dependencies [eb93283]:
    • effect@2.4.7

0.64.3

Patch Changes

  • #2320 cfef6ec Thanks @gcanti! - feedback: remove array overload to restore pipeability to the API

0.64.2

Patch Changes

  • #2310 89748c9 Thanks @gcanti! - merge Parser module into ParseResult:

    • remove Parser module
    • remove internal/parseResult internal module
  • Updated dependencies [4f35a7e, 9971186]:

    • effect@2.4.6

0.64.1

Patch Changes

0.64.0

Minor Changes

Breaking Changes

  • The Format module has been removed

AST module

  • Tuple has been refactored to TupleType, and its _tag has consequently been renamed. The type of its rest property has changed from Option.Option<ReadonlyArray.NonEmptyReadonlyArray<AST>> to ReadonlyArray<AST>.

  • Transform has been refactored to Transformation, and its _tag property has consequently been renamed. Its property transformation has now the type TransformationKind = FinalTransformation | ComposeTransformation | TypeLiteralTransformation.

  • createRecord has been removed

  • AST.to has been renamed to AST.typeAST

  • AST.from has been renamed to AST.encodedAST

  • ExamplesAnnotation and DefaultAnnotation now accept a type parameter

  • format has been removed: Before

    AST.format(ast, verbose?)
    

    Now

    ast.toString(verbose?)
    
  • setAnnotation has been removed (use annotations instead)

  • mergeAnnotations has been renamed to annotations

  • move defaultParseOption from Parser.ts to AST.ts

ParseResult module

  • The ParseResult module now uses classes and custom constructors have been removed: Before

    import * as ParseResult from "@effect/schema/ParseResult"
    
    ParseResult.type(ast, actual)
    

    Now

    import * as ParseResult from "@effect/schema/ParseResult"
    
    new ParseResult.Type(ast, actual)
    
  • Transform has been refactored to Transformation, and its kind property now accepts "Encoded", "Transformation", or "Type" as values

Schema module

  • uniqueSymbol has been renamed to uniqueSymbolFromSelf

  • Schema.Schema.To has been renamed to Schema.Schema.Type, and Schema.to to Schema.typeSchema

  • Schema.Schema.From has been renamed to Schema.Schema.Encoded, and Schema.from to Schema.encodedSchema

  • The type parameters of TaggedRequest have been swapped

  • The signature of PropertySignature has been changed from PropertySignature<From, FromOptional, To, ToOptional> to PropertySignature<ToToken extends Token, To, Key extends PropertyKey, FromToken extends Token, From, R>

  • Class APIs

    • Class APIs now expose fields and require an identifier
      -class A extends S.Class<A>()({ a: S.string }) {}
      +class A extends S.Class<A>("A")({ a: S.string }) {}
      
  • element and rest have been removed in favor of tuple:

    Before

    import * as S from "@effect/schema/Schema"
    
    const schema1 = S.tuple().pipe(S.rest(S.number), S.element(S.boolean))
    
    const schema2 = S.tuple(S.string).pipe(S.rest(S.number), S.element(S.boolean))
    

    Now

    import * as S from "@effect/schema/Schema"
    
    const schema1 = S.tuple([], S.number, S.boolean)
    
    const schema2 = S.tuple([S.string], S.number, S.boolean)
    
  • optionalElement has been refactored:

    Before

    import * as S from "@effect/schema/Schema"
    
    const schema = S.tuple(S.string).pipe(S.optionalElement(S.number))
    

    Now

    import * as S from "@effect/schema/Schema"
    
    const schema = S.tuple(S.string, S.optionalElement(S.number))
    
  • use TreeFormatter in BrandSchemas

  • Schema annotations interfaces have been refactored into a namespace Annotations

  • the annotations option of the optional constructor has been replaced by the annotations method Before

    S.optional(S.string, {
      exact: true,
      annotations: { description: "description" }
    })
    

    Now

    S.optional(S.string, { exact: true }).annotations({
      description: "description"
    })
    
  • Updated the pluck function to return Schema<A[K], { readonly [key]: I[K] }> instead of Schema<A[K], I>. Removed the { transformation: false } option in favor of selecting the specific field from the fields exposed by a struct.

  • Removed propertySignatureAnnotations, use propertySignature(schema).annotations().

  • Updated the function name headOr to headOrElse to align with the standard naming convention.

Serializable module

  • The type parameters of SerializableWithResult and WithResult have been swapped

Patch Changes

  • #2172 5d47ee0 Thanks @gcanti! - ## AST module

    • expose the getTemplateLiteralRegExp API

    Schema module

    • enhance the struct API to allow records:

      const schema1 = S.struct(
        { a: S.number },
        { key: S.string, value: S.number }
      )
      // or
      const schema2 = S.struct({ a: S.number }, S.record(S.string, S.number))
      
    • enhance the extend API to allow nested (non-overlapping) fields:

      const A = S.struct({ a: S.struct({ b: S.string }) })
      const B = S.struct({ a: S.struct({ c: S.number }) })
      const schema = S.extend(A, B)
      /*
      same as:
      const schema = S.struct({
        a: S.struct({
          b: S.string,
          c: S.number
        })
      })
      */
      
    • add Annotable interface

    • add asSchema

    • add add Schema.Any, Schema.All, Schema.AnyNoContext helpers

    • refactor annotations API to be a method within the Schema interface

    • add support for AST.keyof, AST.getPropertySignatures, Parser.getSearchTree to Classes

    • fix BrandAnnotation type and add getBrandAnnotation

    • add annotations? parameter to Class constructors:

      import * as AST from "@effect/schema/AST"
      import * as S from "@effect/schema/Schema"
      
      class A extends S.Class<A>("A")(
        {
          a: S.string
        },
        { description: "some description..." } // <= annotations
      ) {}
      
  • Updated dependencies [5d47ee0, 817a04c, d90a99d, dd05faa, dd05faa, 802674b]:

    • effect@2.4.4

0.63.4

Patch Changes

0.63.3

Patch Changes

0.63.2

Patch Changes

  • #2222 39f583e Thanks @gcanti! - TaggedClass: ensure constructor parameters don't overwrite the tag

  • #2227 f428198 Thanks @gcanti! - add ConcurrencyAnnotation, default value: undefined (sequential)

    Example:

    const schema = S.struct({
      a: S.string,
      b: S.number
    }).pipe(S.concurrency(1 /* number | "unbounded" | "inherit" | undefined */))
    
  • #2221 c035972 Thanks @tim-smart! - ensure Schema.Class is compatible without strictNullCheck

  • Updated dependencies [a4a0006, 0a37676, 6f503b7]:

    • effect@2.4.1

0.63.1

Patch Changes

  • #2209 5d30853 Thanks @steffanek! - Add pickLiteral to Schema so that we can pick values from a Schema literal as follows:

    import * as S from "@effect/schema/Schema"
    
    const schema = S.literal("a", "b", "c").pipe(S.pickLiteral("a", "b")) // same as S.literal("a", "b")
    
    S.decodeUnknownSync(schema)("a") // ok
    S.decodeUnknownSync(schema)("b") // ok
    S.decodeUnknownSync(schema)("c")
    /*
    Error: "a" | "b"
    ├─ Union member
    │  └─ Expected "a", actual "c"
    └─ Union member
       └─ Expected "b", actual "c"
    */
    
  • #2217 6e350ed Thanks @gcanti! - JSONSchema: prune UndefinedKeyword if the property signature is marked as optional and contains a union that includes UndefinedKeyword, closes #2068

0.63.0

Minor Changes

  • #2101 54ddbb7 Thanks @github-actions! - Updated the MessageAnnotation type to accept a ParseIssue; it's now (issue: ParseResult.ParseIssue) => string to support custom error messages, which can be triggered under any circumstances.

    You can retrieve the actual value by accessing the actual property of the issue object:

    import * as S from "@effect/schema/Schema";
    
    const schema = S.string.pipe(
      S.filter((s): s is string => s.length === 1, {
    -    message: (actual) => `invalid value ${actual}`,
    +    message: (issue) => `invalid value ${issue.actual}`,
      })
    );
    
  • #2101 a025b12 Thanks @github-actions! - Swap type params of Either from Either<E, A> to Either<R, L = never>.

    Along the same line of the other changes this allows to shorten the most common types such as:

    import { Either } from "effect"
    
    const right: Either.Either<string> = Either.right("ok")
    

Patch Changes

0.62.9

Patch Changes

0.62.8

Patch Changes

0.62.7

Patch Changes

  • #2141 dbff62c Thanks @gcanti! - add { exact: true } optional argument to the partial API, mirroring the implementation in the optional API, closes #2140

    The partial operation allows you to make all properties within a schema optional.

    By default, the partial operation adds a union with undefined to the types. If you wish to avoid this, you can opt-out by passing a { exact: true } argument to the partial operation.

    Example

    import * as S from "@effect/schema/Schema"
    
    /*
    const schema: S.Schema<{
        readonly a?: string | undefined;
    }, {
        readonly a?: string | undefined;
    }, never>
    */
    const schema = S.partial(S.struct({ a: S.string }))
    
    S.decodeUnknownSync(schema)({ a: "a" }) // ok
    S.decodeUnknownSync(schema)({ a: undefined }) // ok
    
    /*
    const exact: S.Schema<{
        readonly a?: string;
    }, {
        readonly a?: string;
    }, never>
    */
    const exactSchema = S.partial(S.struct({ a: S.string }), { exact: true })
    
    S.decodeUnknownSync(exactSchema)({ a: "a" }) // ok
    S.decodeUnknownSync(exactSchema)({ a: undefined })
    /*
    throws:
    Error: { a?: string }
    └─ ["a"]
       └─ Expected a string, actual undefined
    */
    
  • #2128 e572b07 Thanks @tim-smart! - allow passing structs when encoding schema classes

    The following will no longer throw an error:

    import * as S from "@effect/schema/Schema"
    
    class C extends S.Class<C>()({
      n: S.NumberFromString
    }) {
      get b() {
        return 1
      }
    }
    class D extends S.Class<D>()({
      n: S.NumberFromString,
      b: S.number
    }) {}
    
    console.log(S.encodeSync(D)(new C({ n: 1 })))
    // Output: { b: 1, n: '1' }
    
  • #2123 e787a57 Thanks @gcanti! - Refactor the declare signature to ensure that the decoding and encoding functions do not utilize context.

    As a result, we can relax the signature of the following functions to accept R !== never:

    • Parser.validateSync
    • Parser.validateOption
    • Parser.validateEither
    • Parser.is
    • Parser.asserts
    • Schema.validateSync
    • Schema.validateOption
    • Schema.validateEither
    • Schema.is
    • Schema.asserts

    Additionally, the Class API no longer requires the optional argument disableValidation to be true when R !== never.

  • Updated dependencies [b1163b2, b46b869, de1b226, a663390, ff88f80, 11be07b, c568645, 88835e5, b415577, ff8046f]:

    • effect@2.3.6

0.62.6

Patch Changes

  • #2121 aef2b8b Thanks @gcanti! - Use the identity function in the transformation defining a schema class

  • #2124 7eecb1c Thanks @gcanti! - ParseResult: add missing decode / encode exports

  • Updated dependencies [b881365]:

    • effect@2.3.5

0.62.5

Patch Changes

  • Updated dependencies [17bda66]:
    • effect@2.3.4

0.62.4

Patch Changes

  • #2108 1c6d18b Thanks @gcanti! - Schema: add transformation: false option to pluck.

    Given a schema Schema<A, I, R> and a key K, this function extracts a specific field from the A type, producing a new schema that represents a transformation from the I type to A[K].

    If the option { transformation: false } is provided, the returned schema Schema<A[K], I[K], R> only represents the value of the field without any transformation.

    Example

    import * as S from "@effect/schema/Schema"
    
    // ---------------------------------------------
    // use case: pull out a single field from a
    // struct through a transformation
    // ---------------------------------------------
    
    const mytable = S.struct({
      column1: S.NumberFromString,
      column2: S.number
    })
    
    // const pullOutColumn1: S.Schema<number, {
    //     readonly column1: string;
    //     readonly column2: number;
    // }, never>
    const pullOutColumn1 = mytable.pipe(S.pluck("column1"))
    
    console.log(
      S.decode(S.array(pullOutColumn1))([
        { column1: "1", column2: 100 },
        { column1: "2", column2: 300 }
      ])
    )
    // Output: { _id: 'Either', _tag: 'Right', right: [ 1, 2 ] }
    
    // ---------------------------------------------
    // use case: pull out a single field from a
    // struct (no transformation)
    // ---------------------------------------------
    
    // const pullOutColumn1Value: S.Schema<number, string, never>
    const pullOutColumn1Value = mytable.pipe(
      S.pluck("column1", { transformation: false })
    )
    
    console.log(S.decode(S.array(pullOutColumn1Value))(["1", "2"]))
    // Output: { _id: 'Either', _tag: 'Right', right: [ 1, 2 ] }
    
  • #2110 13d3266 Thanks @gcanti! - make headOr dual

  • #2111 a344b42 Thanks @gcanti! - add support for unions to keyof

0.62.3

Patch Changes

0.62.2

Patch Changes

0.62.1

Patch Changes

  • Updated dependencies [b5a8215]:
    • effect@2.3.1

0.62.0

Minor Changes

  • #2006 9a2d1c1 Thanks @github-actions! - With this change we now require a string key to be provided for all tags and renames the dear old Tag to GenericTag, so when previously you could do:

    import { Effect, Context } from "effect"
    interface Service {
      readonly _: unique symbol
    }
    const Service = Context.Tag<
      Service,
      {
        number: Effect.Effect<never, never, number>
      }
    >()
    

    you are now mandated to do:

    import { Effect, Context } from "effect"
    interface Service {
      readonly _: unique symbol
    }
    const Service = Context.GenericTag<
      Service,
      {
        number: Effect.Effect<never, never, number>
      }
    >("Service")
    

    This makes by default all tags globals and ensures better debuggaility when unexpected errors arise.

    Furthermore we introduce a new way of constructing tags that should be considered the new default:

    import { Effect, Context } from "effect"
    class Service extends Context.Tag("Service")<
      Service,
      {
        number: Effect.Effect<never, never, number>
      }
    >() {}
    
    const program = Effect.flatMap(Service, ({ number }) => number).pipe(
      Effect.flatMap((_) => Effect.log(`number: ${_}`))
    )
    

    this will use "Service" as the key and will create automatically an opaque identifier (the class) to be used at the type level, it does something similar to the above in a single shot.

  • #2006 1a77f72 Thanks @github-actions! - change Effect type parameters order from Effect<R, E, A> to Effect<A, E = never, R = never>

  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch readonlyMapFromSelf, readonlyMap from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema"
    
    S.readonlyMapFromSelf(S.string, S.number)
    S.readonlyMap(S.string, S.number)
    

    Now:

    import * as S from "@effect/schema/Schema"
    
    S.readonlyMapFromSelf({ key: S.string, value: S.number })
    S.readonlyMap({ key: S.string, value: S.number })
    
  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch hashMapFromSelf, hashMap from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema"
    
    S.hashMapFromSelf(S.string, S.number)
    S.hashMap(S.string, S.number)
    

    Now:

    import * as S from "@effect/schema/Schema"
    
    S.hashMapFromSelf({ key: S.string, value: S.number })
    S.hashMap({ key: S.string, value: S.number })
    
  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch causeFromSelf, cause from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema"
    
    S.causeFromSelf(S.string)
    S.causeFromSelf(S.string, S.unknown)
    S.cause(S.string)
    S.cause(S.string, S.unknown)
    

    Now:

    import * as S from "@effect/schema/Schema"
    
    S.causeFromSelf({ error: S.string })
    S.causeFromSelf({ error: S.string, defect: S.unknown })
    S.cause({ error: S.string })
    S.cause({ error: S.string, defect: S.unknown })
    
  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch exitFromSelf, exit from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema"
    
    S.exitFromSelf(S.string, S.number)
    S.exit(S.string, S.number)
    

    Now:

    import * as S from "@effect/schema/Schema"
    
    S.exitFromSelf({ failure: S.string, success: S.number })
    S.exit({ failure: S.string, success: S.number })
    
  • #2006 a34dbdc Thanks @github-actions! - - Schema: change type parameters order from Schema<R, I, A> to Schema<A, I = A, R = never>

    • Serializable: change type parameters order from Serializable<R, I, A> to Serializable<A, I, R>
    • Class: change type parameters order from Class<R, I, A, C, Self, Inherited> to Class<A, I, R, C, Self, Inherited>
    • PropertySignature: change type parameters order from PropertySignature<R, From, FromIsOptional, To, ToIsOptional> to PropertySignature<From, FromIsOptional, To, ToIsOptional, R = never>
  • #2006 d3f9f4d Thanks @github-actions! - Schema: switch eitherFromSelf, either, eitherFromUnion from positional arguments to a single options argument:

    Before:

    import * as S from "@effect/schema/Schema"
    
    S.eitherFromSelf(S.string, S.number)
    S.either(S.string, S.number)
    S.eitherFromUnion(S.string, S.number)
    

    Now:

    import * as S from "@effect/schema/Schema"
    
    S.eitherFromSelf({ left: S.string, right: S.number })
    S.either({ left: S.string, right: S.number })
    S.eitherFromUnion({ left: S.string, right: S.number })
    
  • #2006 02c3461 Thanks @github-actions! - With this change we remove the Data.Data type and we make Equal.Equal & Hash.Hash implicit traits.

    The main reason is that Data.Data<A> was structurally equivalent to A & Equal.Equal but extending Equal.Equal doesn't mean that the equality is implemented by-value, so the type was simply adding noise without gaining any level of safety.

    The module Data remains unchanged at the value level, all the functions previously available are supposed to work in exactly the same manner.

    At the type level instead the functions return Readonly variants, so for example we have:

    import { Data } from "effect"
    
    const obj = Data.struct({
      a: 0,
      b: 1
    })
    

    will have the obj typed as:

    declare const obj: {
      readonly a: number
      readonly b: number
    }
    
  • #2006 9a2d1c1 Thanks @github-actions! - This change enables Effect.serviceConstants and Effect.serviceMembers to access any constant in the service, not only the effects, namely it is now possible to do:

    import { Effect, Context } from "effect"
    
    class NumberRepo extends Context.TagClass("NumberRepo")<
      NumberRepo,
      {
        readonly numbers: Array<number>
      }
    >() {
      static numbers = Effect.serviceConstants(NumberRepo).numbers
    }
    
  • #2006 56b8691 Thanks @github-actions! - Fix usage of Schema.TaggedError in combination with Unify.

    When used with Unify we previously had:

    import { Schema } from "@effect/schema"
    import type { Unify } from "effect"
    
    class Err extends Schema.TaggedError<Err>()("Err", {}) {}
    
    // $ExpectType Effect<unknown, unknown, unknown>
    export type IdErr = Unify.Unify<Err>
    

    With this fix we now have:

    import { Schema } from "@effect/schema"
    import type { Unify } from "effect"
    
    class Err extends Schema.TaggedError<Err>()("Err", {}) {}
    
    // $ExpectType Err
    export type IdErr = Unify.Unify<Err>
    

Patch Changes

0.61.7

Patch Changes

0.61.6

Patch Changes

0.61.5

Patch Changes

0.61.4

Patch Changes

0.61.3

Patch Changes

0.61.2

Patch Changes

  • #1988 64f710a Thanks @gcanti! - Class constructor: avoid overwriting props with additionalProps, closes #1987

0.61.1

Patch Changes

0.61.0

Minor Changes

  • #1922 62b40e8 Thanks @gcanti! - Refactoring:

    • Schema:
      • refactor Schema.declare API to make it safe
      • add Schema.declare overloads
      • add encodeUnknown* APIs
      • rename parse* APIs to decodeUnknown*
      • symplify brand implementation
      • rename params to annotation in typeId annotation
      • add optional { strict: false } parameter to compose
      • Class
        • rename transform to transformOrFail
        • rename transformFrom to transformOrFailFrom
      • add hashSet and hashSetFromSelf
      • add hashMap and hashMapFromSelf
      • add list and listFromSelf
    • AST:
      • return ParseResult.ParseIssue instead of ParseResult.ParseError in all APIs
      • Declaration
        • split decode into decodeUnknown / encodeUnknown
        • remove type field
    • ParseResult
      • align mapBoth with Effect (i.e. onFailure, onSuccess handlers)
      • add missing Declaration node in ParseIssue
  • #1922 62b40e8 Thanks @gcanti! - add context tracking to Schema, closes #1873

Patch Changes

0.60.7

Patch Changes

0.60.6

Patch Changes

  • Updated dependencies [21b9edd]:
    • effect@2.1.2

0.60.5

Patch Changes

0.60.4

Patch Changes

0.60.3

Patch Changes

0.60.2

Patch Changes

0.60.1

Patch Changes

  • Updated dependencies [f7f19f6]:
    • effect@2.0.5

0.60.0

Minor Changes

  • #1913 b557a10 Thanks @gcanti! - ParseResult refactoring:

    • remove ParseResult type
    • rename mapLeft to mapError
    • rename bimap to mapBoth

Patch Changes

0.59.1

Patch Changes

0.59.0

Minor Changes

  • #1878 c4b84f7 Thanks @gcanti! - Schema: remove from/to API in favour of make in:

    • Equivalence
    • JSONSchema
    • Pretty

Patch Changes

0.58.0

Minor Changes

  • #1877 a904a73 Thanks @gcanti! - Schema: Arbitrary remove from/to API in favour of make

  • #1842 7b2f874 Thanks @fubhy! - Schema: simplify AST.createRefinement return type

  • #1842 7b2f874 Thanks @fubhy! - Schema: refactor ParseResult module:

    • add Union issue, and replace UnionMember with Union
    • add Tuple issue, and replace Index with Tuple
    • add TypeLiteral issue
    • add Transform issue
    • add Refinement issue
    • add ast field to Member
    • rename UnionMember to Member
    • Type: rename expected to ast
    • ParseError replace errors field with error field and refactor parseError constructor accordingly
    • Index replace errors field with error field
    • Key replace errors field with error field
    • Member replace errors field with error field
    • ParseError replace errors field with error field
    • make ParseError a Data.TaggedError
    • Forbidden: add actual field

Patch Changes

0.57.2

Patch Changes

  • Updated dependencies [d5a1949]:
    • effect@2.0.2

0.57.1

Patch Changes

  • Updated dependencies [16bd87d]:
    • effect@2.0.1

0.57.0

Minor Changes

Patch Changes

0.56.1

Patch Changes

  • #684 6b9585b Thanks @patroza! - improve: Actually use Arbitrary interface in to/from/unsafe signature

  • #679 0f8a8f1 Thanks @gcanti! - Schema: add annotations argument to attachPropertySignature

0.56.0

Minor Changes

0.55.0

Minor Changes

  • #649 d80b933 Thanks @gcanti! - Arbitrary: should throw on declarations without annotations

  • #669 294dfad Thanks @gcanti! - Schema: refactor parseJson to replace ParseJson and fromJson

  • #649 d80b933 Thanks @gcanti! - Schema: refactor S.optional API.

    Upgrade Guide:

    • S.optional(schema, { exact: true }) replaces the old S.optional(schema)
    • S.optional(schema, { exact: true, default: () => A }) replaces the old S.optional(schema).withDefault(() => A)
    • S.optional(schema, { exact: true, as: "Option" }) replaces the old S.optional(schema).toOption()
  • #649 d80b933 Thanks @gcanti! - Schema: replace propertySignature constructor with propertySignatureAnnotations combinator

  • #669 294dfad Thanks @gcanti! - Schema: simplify split parameters to only accept separator

  • #669 294dfad Thanks @gcanti! - Schema: remove useless combinators

    • lowercase
    • uppercase
    • trim
    • numberFromString
    • symbolFromString
    • bigintFromString
    • bigintFromNumber
    • secret
    • durationFromHrTime
    • durationFromMillis
    • durationFromNanos
    • uint8ArrayFromNumbers
    • base64
    • base64url
    • hex
    • dateFromString
    • bigDecimalFromNumber
    • bigDecimalFromString
    • not

Patch Changes

0.54.1

Patch Changes

0.54.0

Minor Changes

0.53.3

Patch Changes

0.53.2

Patch Changes

0.53.1

Patch Changes

0.53.0

Minor Changes

Patch Changes

  • #645 ece6128 Thanks @gcanti! - ensure that JSON Schema annotations can be exclusively applied to refinements

0.52.0

Minor Changes

Patch Changes

0.51.5

Patch Changes

  • #629 f690ebe Thanks @gcanti! - Schema: add filter overloading returning Option

    For more complex scenarios, you can return an Option<ParseError> type instead of a boolean. In this context, None indicates success, and Some(error) rejects the input with a specific error

0.51.4

Patch Changes

0.51.3

Patch Changes

0.51.2

Patch Changes

0.51.1

Patch Changes

0.51.0

Minor Changes

Patch Changes

0.50.0

Minor Changes

  • #593 cbc2e3f Thanks @gcanti! - ParseResult: merge failure APIs into fail

  • #607 e85aefb Thanks @gcanti! - Bug Fix: align index signature behaviour to TypeScript

  • #589 3b99569 Thanks @gcanti! - - remove ValidDate (which is just an alias of Date)

    • add DateFromString (decodes from string, output: possibly invalid Date)
  • #593 cbc2e3f Thanks @gcanti! - ParseResult: rename success to succeed (standard naming)

Patch Changes

  • #597 caeed29 Thanks @jessekelly881! - added BigDecimal

  • #585 5b27f03 Thanks @gcanti! - improve JSON Schema output:

    • rename dependencies to $defs
    • remove "type" from const schemas
    • use "oneOf" for enums and add "title"s
    • add support for record(pattern, number)
    • add "$id" and "$comment" properties
    • literals should be converted to enum instead of anyOf, closes #579
  • #603 8e21d7e Thanks @gcanti! - TreeFormatter: enhance formatActual for data types with a custom toString implementation, closes #600

0.49.4

Patch Changes

0.49.3

Patch Changes

0.49.2

Patch Changes

  • #587 64fe91f Thanks @gcanti! - DateFromSelf: its arbitrary should also generate "Invalid Date"s

0.49.1

Patch Changes

0.49.0

Minor Changes

Patch Changes

0.48.4

Patch Changes

0.48.3

Patch Changes

0.48.2

Patch Changes

0.48.1

Patch Changes

0.48.0

Minor Changes

0.47.7

Patch Changes

0.47.6

Patch Changes

0.47.5

Patch Changes

  • #553 522161a Thanks @gcanti! - Fix bug in property signature transformations when used for renaming (old key/value pair was not removed)

0.47.4

Patch Changes

  • #550 5167e2d Thanks @gcanti! - attachPropertySignature: add support for symbols as values

0.47.3

Patch Changes

0.47.2

Patch Changes

0.47.1

Patch Changes

0.47.0

Minor Changes

0.46.4

Patch Changes

0.46.3

Patch Changes

0.46.2

Patch Changes

0.46.1

Patch Changes

0.46.0

Minor Changes

0.45.8

Patch Changes

0.45.7

Patch Changes

0.45.6

Patch Changes

0.45.5

Patch Changes

0.45.4

Patch Changes

0.45.3

Patch Changes

  • #500 e9ff876 Thanks @gcanti! - Arbitrary: remove NaN while generating numeric template literals

0.45.2

Patch Changes

0.45.1

Patch Changes

  • #496 ff360c6 Thanks @gcanti! - Arbitrary: fix issue with generating optional tuple elements

0.45.0

Minor Changes

Patch Changes

0.44.0

Minor Changes

0.43.2

Patch Changes

  • #485 0a20788 Thanks @gcanti! - Arbitrary: use Math.fround when creating number constraints, closes #484

0.43.1

Patch Changes

0.43.0

Minor Changes

0.42.0

Minor Changes

0.41.1

Patch Changes

0.41.0

Minor Changes

0.40.2

Patch Changes

0.40.1

Patch Changes

0.40.0

Minor Changes

0.39.2

Patch Changes

0.39.1

Patch Changes

0.39.0

Minor Changes

0.38.0

Minor Changes

  • #439 2197496 Thanks @gcanti! - Schema: remove *Result APIs

    • decodeResult (use decode instead)
    • encodeResult (use encode instead)
    • parseResult (use parse instead)
    • validateResult (use validate instead)

Patch Changes

  • #447 0252143 Thanks @gcanti! - int filter: use Number.isSafeInteger instead of Number.isInteger

0.37.2

Patch Changes

0.37.1

Patch Changes

0.37.0

Minor Changes

0.36.5

Patch Changes

0.36.4

Patch Changes

  • #434 994a37e Thanks @gcanti! - Exclude property signatures from index signatures validations, fix #433

0.36.3

Patch Changes

0.36.2

Patch Changes

0.36.1

Patch Changes

0.36.0

Minor Changes

0.35.1

Patch Changes

0.35.0

Minor Changes

  • #401 8b1ae6b Thanks @gcanti! - backport AST changes from POC:

    • change decode in Declaration- change decode in Refinement (to filter)
    • remove isReversed from Refinement
    • add transformation to Transform (and remove decode, encode, propertySignatureTransformations)
    • refactor PropertySignature
  • #401 8b1ae6b Thanks @gcanti! - refactor annotations: keys must be symbols

  • #411 2f6c4d1 Thanks @gcanti! - rename symbol to symbolFromSelf and add symbol which decodes/encodes from/to string

  • #401 8b1ae6b Thanks @gcanti! - remove Spread in favour of /data/Types#Simplify

  • #413 20ef377 Thanks @tim-smart! - update /io

  • #401 8b1ae6b Thanks @gcanti! - fix fromBrand definition (self is a Schema<I, A> now instead of Schema)

  • #401 8b1ae6b Thanks @gcanti! - rename bigint to bigintFromSelf and BigintFromString to bigint

  • #401 8b1ae6b Thanks @gcanti! - change transformation display in error messages (from A -> B to A <-> B)

  • #401 8b1ae6b Thanks @gcanti! - move From, To to Schema namespace (conforming to the ecosystem standard)

  • #401 8b1ae6b Thanks @gcanti! - rename transformResult to transformOrFail and change signature (add additional ast parameter to transformations)

Patch Changes

0.34.0

Minor Changes

Patch Changes

0.33.2

Patch Changes

0.33.1

Patch Changes

0.33.0

Minor Changes

Patch Changes

0.32.0

Minor Changes

0.31.0

Minor Changes

0.30.4

Patch Changes

0.30.3

Patch Changes

0.30.2

Patch Changes

0.30.1

Patch Changes

0.30.0

Minor Changes

0.29.1

Patch Changes

0.29.0

Minor Changes

0.28.0

Minor Changes

0.27.0

Minor Changes

0.26.1

Patch Changes

0.26.0

Minor Changes

0.25.0

Minor Changes

0.24.0

Minor Changes

Patch Changes

0.23.0

Minor Changes

0.22.0

Minor Changes

0.21.1

Patch Changes

0.21.0

Minor Changes

0.20.3

Patch Changes

0.20.2

Patch Changes

0.20.1

Patch Changes

0.20.0

Minor Changes

0.19.3

Patch Changes

  • #285 39d3c55 Thanks @gcanti! - AST: memoize createLazy

  • #285 39d3c55 Thanks @gcanti! - Arbitrary: fix maximum call stack size exceeded when producing nested arrays and records that are too deep

0.19.2

Patch Changes

0.19.1

Patch Changes

0.19.0

Minor Changes

0.18.0

Minor Changes

0.17.5

Patch Changes

  • #272 d91a7a7 Thanks @gcanti! - pick / omit: add support for structs with property signature transformations

0.17.4

Patch Changes

0.17.3

Patch Changes

0.17.2

Patch Changes

0.17.1

Patch Changes

  • #256 162e099 Thanks @gcanti! - leverage annotations (e.g. maxLength, int, between) to improve fast-check performance

0.17.0

Minor Changes

0.16.0

Minor Changes

0.15.0

Minor Changes

0.14.1

Patch Changes

0.14.0

Minor Changes

Patch Changes

0.13.1

Patch Changes

  • #234 9ed0ee2 Thanks @gcanti! - attachPropertySignature as PropertySignatureTransformation

0.13.0

Minor Changes

0.12.1

Patch Changes

0.12.0

Minor Changes

0.11.1

Patch Changes

0.11.0

Minor Changes

Patch Changes

0.10.0

Minor Changes

0.9.1

Patch Changes

0.9.0

Minor Changes

0.8.3

Patch Changes

0.8.2

Patch Changes

0.8.1

Patch Changes

0.8.0

Minor Changes

Patch Changes

0.7.1

Patch Changes

0.7.0

Minor Changes

0.6.0

Minor Changes

Patch Changes

0.5.0

Minor Changes

  • #178 f60341f Thanks @gcanti! - merge transformEither and transformEffect into transformResult

0.4.0

Minor Changes

Patch Changes

0.3.1

Patch Changes

0.3.0

Minor Changes

Patch Changes

0.2.1

Patch Changes

0.2.0

Minor Changes

Patch Changes

0.1.0

Minor Changes

Patch Changes

0.0.5

Patch Changes

0.0.4

Patch Changes

  • #115 1555a81 Thanks @gcanti! - Optimize decoding of unions using a heuristic based on literals

0.0.3

Patch Changes

0.0.2

Patch Changes

0.0.1

Patch Changes